llvm::GlobalVariable usage (newbie question)

The docs are pretty vague about this. After digging into the examples I got the following to work with JIT to gain a pointer to variable elsewhere in the runtime, but I’d like to understand what is going on here, and if there is a, um, nicer API that I’m missing?

llvm::Value* C::getGlobalVariable(const char* name,
llvm::Type* t)
{

auto global = _module->getNamedGlobal(name);
if (!global) {
new llvm::GlobalVariable(

*_module,
t,
true, // constant
llvm::GlobalValue::ExternalLinkage,
nullptr, // no initializer
name);
global = _module->getNamedGlobal(name);
}

return global;
}

Cheers,

– nikodemus

Have you looked at Module::getOrInsertGlobal? It seems to be pretty
much exactly what you're doing.

Cheers.

Tim.

No, thanks for the hint!

A followup question.

Langref says: “LLVM explicitly allows declarations of global variables to be marked constant, even if the final definition of the global is not. This capability can be used to enable slightly better optimization of the program, but requires the language definition to guarantee that optimizations based on the ‘constantness’ are valid for the translation units that do not include the definition.”

Am I correct in surmising that means it’s OK to claim globals in other translation units are constant if they don’t change after the initial definition?