I've the following IR code that I want to generate C++ for:
@gArray = global [10 x i32] [i32 3, i32 4, i32 5, i32 6, i32 0, i32 0, i32 0, i32 0, i32 12, i32 0], align 16
I know I could use these lines of code to initialize the array to all zeros:
ConstantAggregateZero* const_array_2 = ConstantAggregateZero::get(ArrayTy_0);
GArray->setInitializer(const_array_2);
How do I initialize an array in LLVM to a list of values?
You can create a constant initializer list:
std::vector<llvm::Constant*> values;
...
/* Make the value 42 appear in the array - ty is "i32" */
llvm::Constant* c = llvm::Constant::getIntegerValue(ty, 42);
values.push_back(c);
... // Add more values here ...
llvm::Constant* init = llvm::ConstantArray::get(arrayTy_0, values);
GArray->setInitializer(init);
This code (and the 20 or so lines before it) creates a global struct that is initialized: https://github.com/Leporacanthicus/lacsap/blob/master/expr.cpp#L2585
And here is another example using setInitializer - again, it's not an array but a struct, but conceptually there's not much difference between arrays and structs: https://github.com/Leporacanthicus/lacsap/blob/master/expr.cpp#L3376
See also (for example): http://llvm.org/docs/doxygen/html/classllvm_1_1ConstantArray.html