15

I'd like to record some dynamic behaviors into some global variables. So I wrote a pass to instrument the code and insert some instructions to update the global variable. I tried to use the GlobalVariable constructor to define a global variable, but there are two problems. First, how can I DEFINE the global variables in the module containing main function? Second, how can I DECLARE those global variables in other modules? It's like "extern double someThing;".

The target programs are written in C.

dalibocai
  • 2,289
  • 5
  • 29
  • 45

1 Answers1

30

There is a tool which can answer this and many other questions about LLVM API: llc -march=cpp. You can generate a bitcode file using Clang or llvm-gcc, and then build a C++ code which should reconstruct the same module using the cpp backend.

A sample output, showing how to define a global int * variable:

// Global Variable Declarations

GlobalVariable* gvar_ptr_abc = new GlobalVariable(/*Module=*/*mod, 
        /*Type=*/PointerTy_0,
        /*isConstant=*/false,
        /*Linkage=*/GlobalValue::CommonLinkage,
        /*Initializer=*/0, // has initializer, specified below
        /*Name=*/"abc");
gvar_ptr_abc->setAlignment(4);

// Constant Definitions
ConstantPointerNull* const_ptr_2 = ConstantPointerNull::get(PointerTy_0);

// Global Variable Definitions
gvar_ptr_abc->setInitializer(const_ptr_2);
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
SK-logic
  • 9,605
  • 1
  • 23
  • 35
  • That looks like C++, not C (the `ConstantPointerNull::get()` call). – Keith Thompson Oct 16 '11 at 21:41
  • 7
    @Keith Thompson, you can't write an LLVM pass in C anyway, so what's the problem? – SK-logic Oct 16 '11 at 21:43
  • 1
    The OP said the target programs are written in C. (I'm not familiar with LLVM, so I won't comment further.) – Keith Thompson Oct 16 '11 at 21:46
  • Thanks for answering part of the question. Can you explain a bit on the use of "CommonLinkage" rather than "ExternalLinkage"? I guess this piece of code implies that I should use the constructor to both declare and define a global variable. The only difference is that for declaration I set the initializer to 0? – dalibocai Oct 16 '11 at 21:48
  • @dalibocai, you'll use `ExternalLinkage` in the module where you're declaring an external variable. This one is a *definition* (see the initialiser). – SK-logic Oct 16 '11 at 21:56
  • 11
    Update to anyone who sees this -- don't bother trying the C++ backend, [it doesn't exist anymore](https://stackoverflow.com/questions/14751403/generate-llvm-c-api-code-as-backend). – tonysdg Sep 14 '17 at 20:55
  • Is there a reason to initialize it afterwards, rather than just create the constant first and pass directly as initializer? – Jeppe Nov 16 '22 at 20:03