Shachar Shemesh
Shachar Shemesh

Reputation: 8573

Create and reference a string literal via LLVM C interface

I'm trying to create a string literal via LLVM C API, and get a C style pointer to its first member. LLVMBuildGlobalStringPtr does the trick nicely, but I can't use it because my source string might contain nulls.

I cannot seem to find documentation on how to create an initialized, unnamed, constant global string.

I've tried using LLVMConstString to create the string and LLVMConstIntToPtr to get its address (and, then, GetElementPointer to convert to i8*). I can get LLVM to compile it, but the resulting object file does not contain the string, and the code returns a pointer that seems random.

Upvotes: 1

Views: 753

Answers (1)

Shachar Shemesh
Shachar Shemesh

Reputation: 8573

I've found the answer. The following code segment seems to do the trick:

LLVMValueRef defineStringLiteral( const char *sourceString, size_t size ) {
    LLVMTypeRef strType = LLVMArrayType( LLVMInt8Type(), size );
    LLVMValueRef str = LLVMAddGlobal(module->getLLVMModule(), strType, "");
    LLVMSetInitializer(str, LLVMConstString( sourceString, size, true ));
    LLVMSetGlobalConstant(str, true);
    LLVMSetLinkage(str, LLVMPrivateLinkage);
    LLVMSetUnnamedAddress(str, LLVMGlobalUnnamedAddr);
    LLVMSetAlignment(str, 1);


    LLVMValueRef zeroIndex = LLVMConstInt( LLVMInt64Type(), 0, true );
    LLVMValueRef indexes[2] = { zeroIndex, zeroIndex };

    LLVMValueRef gep = LLVMBuildInBoundsGEP2(builder, strType, str, indexes, 2, "");

    return gep;
}

Upvotes: 2

Related Questions