Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM, Global integer array zeroinitializer

Tags:

c++

llvm

I cannot seem to figure out how to set up zeroinitializer for a global integer array. At the moment my code outputs:

@a = common global [1 x i32], align 4

However, clang foo.c -S -emit-llvm produces:

@a = common global [1 x i32] zeroinitializer, align 4

My code is currently this, my setInitializer() code does not work and is commented out:

TheModule = (argc > 1) ? new Module(argv[1], Context) : new Module("Filename", Context);

// Unrelated code

// currentGlobal->id is a string, currentGlobal->stype->dimension is the array length
TheModule->getOrInsertGlobal(currentGlobal->id, ArrayType::get(Builder.getInt32Ty(), currentGlobal->stype->dimension));
GlobalVariable* gVar = TheModule->getNamedGlobal(currentGlobal->id);
gVar->setLinkage(GlobalValue::CommonLinkage);

// Not working, not sure if this is how it should be done roughly either
/*gVar->setInitializer(
    ConstantArray::get(
        ArrayType::get(Builder.getInt32Ty(), currentGlobal->stype->dimension),
        ArrayRef(0, currentGlobal->stype->dimension)
    )
);*/

gVar->setAlignment(4);
like image 421
asimes Avatar asked Apr 27 '14 22:04

asimes


1 Answers

You need to use an instance of ConstantAggregateZero instead of an instance of ConstantArray.

=== Notice - the below information is outdated ===

In general, if you want to know how to emulate what Clang generates for a particular file, you can use the C++ backend on the Clang-generated file to emit C++ code which generates the same output.

For example, if you go to the LLVM demo page, provide the code int a[5] = {0}; and choose the "LLVM C++ API code" target, you'll get:

// Type Definitions
ArrayType* ArrayTy_0 = ArrayType::get(IntegerType::get(mod->getContext(), 32), 5);

PointerType* PointerTy_1 = PointerType::get(ArrayTy_0, 0);


// Function Declarations

// Global Variable Declarations


GlobalVariable* gvar_array_a = new GlobalVariable(/*Module=*/*mod, 
/*Type=*/ArrayTy_0,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"a");
gvar_array_a->setAlignment(16);

// Constant Definitions
ConstantAggregateZero* const_array_2 = ConstantAggregateZero::get(ArrayTy_0);

// Global Variable Definitions
gvar_array_a->setInitializer(const_array_2);

And you can see the use of ConstantAggregateZero at the one-before-last code line.

like image 157
Oak Avatar answered Oct 06 '22 12:10

Oak