LLVM, Initialize an integer global variable with a value of 0

I am going around in circles through the LLVM / Stack documentation and cannot understand how a global integer variable should be initialized to 0 (first time using LLVM). This is currently part of my code:

TheModule = (argc > 1) ? new Module(argv[1], Context) : new Module("Filename", Context); // Unrelated code // currentGlobal->id is just a string TheModule->getOrInsertGlobal(currentGlobal->id, Builder.getInt32Ty()); llvm::GlobalVariable* gVar = TheModule->getNamedGlobal(currentGlobal->id); gVar->setLinkage(llvm::GlobalValue::CommonLinkage); gVar->setAlignment(4); // What replaces "???" below? //gVar->setInitializer(???); 

This is almost what I want, an example of the output that it can produce:

 @a = common global i32, align 4 @b = common global i32, align 4 @c = common global i32, align 4 

However, clang foo.c -S -emit-llvm produces this, which I also want:

 @a = common global i32 0, align 4 @b = common global i32 0, align 4 @c = common global i32 0, align 4 

As far as I can tell, I need a Constant* where I have "???" but I'm not sure how to do this: http://llvm.org/docs/doxygen/html/classllvm_1_1GlobalVariable.html#a095f8f031d99ce3c0b25478713293dea

+6
source share
1 answer

Use one of the APInt constructors to get a 0-digit ConstantInt (AP stands for arbitrary precision)

 ConstantInt* const_int_val = ConstantInt::get(module->getContext(), APInt(32,0)); 

Then set the initializer value (subclass of Constant)

 global_var->setInitializer(const_int_val); 
+3
source

All Articles