Getting a pointer to a i8 from a global variable that holds a constant string

Hello,

I’m trying to get the pointer to the first element of a string (so that I can pass it to a function).
The string itself is a constant kept in a global variable.
My end goal is to generate the IR for something like “puts(“Hello World”)”;
I’m stuck on the parameter part of the call instruction.

So far I have something like this:

const std::string& str = strExpr->value();
llvm::ArrayType* type = llvm::ArrayType::get(llvm::IntegerType::get(m_context, 8), str.size()+1);
llvm::GlobalVariable* var = new llvm::GlobalVariable(m_module, type, true, llvm::GlobalValue::PrivateLinkage, nullptr, “.str”);
var->setAlignment(1);;

llvm::Constant* c = llvm::ConstantDataArray::getString(m_context, str);
var->setInitializer(c);

The part below is the one I have problems with:

llvm::ConstantInt* const_int32_12 = llvm::ConstantInt::get(m_context, llvm::APInt(32, llvm::StringRef(“0”), 10));
std::vectorllvm::Constant* const_ptr_14_indices;
const_ptr_14_indices.push_back(const_int32_12);
const_ptr_14_indices.push_back(const_int32_12);
return llvm::ConstantExpr::getGetElementPtr(nullptr,c, const_ptr_14_indices);

I realize that the GlobalVariable should not be declared every time I get in that function but that’s something I’ll fix after I get this working.

Any help here would be appreciated.

Regards,
Lorin

Hi Lorin,

return llvm::ConstantExpr::getGetElementPtr(nullptr,c,
const_ptr_14_indices);

You need to be using the GlobalVariable as the base of the GEP, not
the ConstantDataArray. Then since it's been initialized to the string
you want, your GEP will pick up the first element of that string. The
ConstantDataArray isn't a pointer (it's an [N x i8], notionally in
registers).

Cheers.

Tim.

Hi Lorin

You might want to take a look at the CreateGlobalStringPtr method in the IRBuilder class. It should allow you to insert the string and construct the appropriate GEP automatically.

http://llvm.org/docs/doxygen/html/classllvm_1_1IRBuilder.html#ab81bf85457770dc76f2e536f201db219

Regards,

Snehasish