Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM, Initialize an integer global variable with value 0

Tags:

c++

llvm

I've been going in circles through the LLVM documentation / Stack Overflow and cannot figure out how an integer global variable should be initialized as 0 (first time using LLVM). This is some of my code currently:

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 almost does what I want, an example of output 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 want as well:

@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 am not sure how to do it: http://llvm.org/docs/doxygen/html/classllvm_1_1GlobalVariable.html#a095f8f031d99ce3c0b25478713293dea

like image 706
asimes Avatar asked Apr 27 '14 20:04

asimes


1 Answers

Use one of the APInt constructors to get a 0-valued ConstantInt (AP stands for Arbitrary Precision)

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

Then set your initializer value (a Constant subclass)

global_var->setInitializer(const_int_val);
like image 122
Marco A. Avatar answered Oct 20 '22 15:10

Marco A.