Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM String Value objects: How can I retrieve the String from a Value?

Tags:

c++

llvm

llvm-3.0

When building the IR from an existing AST, my AST has some string values (at compile-time they are built from std::string) and I want to set them safely as llvm::Value to use as a part of an expression.

In this case, I don't need to bind the string at run-time, because string values are only meant to resolve stuff as variables, functions or classes at compile-time (the language doesn't support a native string type).

Whats the best way to keep my string content as llvm::Value and still be able to retrieve it at later stages of compilation (when the nesting expressions are built)?

More concretely, if I set the llvm::Value with:

 llvm::Value* v = llvm::ConstantArray::get(llvmContext, myString.c_str());

How do I safely retrieve the string value? Is llvm::ConstantArray the appropriate way to wrap strings?

like image 496
lurscher Avatar asked Dec 04 '11 18:12

lurscher


2 Answers

Yes, ConstantArray is what you should use here. In order to retrieve the value later just use ConstantArray::getAsCString(). If you have assertions turned on, it will assert if something will went wrong (e.g. you will try to grab string from the array w/o zero terminator).

like image 57
Anton Korobeynikov Avatar answered Nov 06 '22 14:11

Anton Korobeynikov


Running http://llvm.org/demo/ on the C code char *x = "asdf"; gives:

@.str = private unnamed_addr constant [5 x i8] c"asdf\00"
@x = global i8* getelementptr inbounds ([5 x i8]* @.str, i64 0, i64 0), align 8

Basically, to get the address of a string, you have to build a global containing it. You can switch http://llvm.org/demo/ to output C++ API calls if you have trouble figuring out how to do that.

like image 27
servn Avatar answered Nov 06 '22 13:11

servn