LLVM get constant integer back from Value*

lurscher picture lurscher · Mar 15, 2011 · Viewed 14.4k times · Source

I create a llvm::Value* from a integer constant like this:

llvm::Value* constValue = llvm::ConstantInt::get( llvmContext , llvm::APInt( node->someInt() ));

now i want to retrieve the compile-time constant value back;

int constIntValue = constValue->???

The examples shown in LLVM Programmer manual seem to imply that cast<> will accept a pointer when using the type (rather than the type plus pointer) template parameter, however i'm pretty sure thats failing as from 2.8:

llvm::Value* foo = 0;
llvm::ConstantInt* intValue = & llvm::cast< llvm::ConstantInt , llvm::Value >(foo );

//build error:
//error: no matching function for call to ‘cast(llvm::Value*&)’

What would be the correct approach here?

Answer

Oak picture Oak · Oct 31, 2012

Eli's answer is great, but it's missing the final part, which is getting the integer back. The full picture should look like this:

if (ConstantInt* CI = dyn_cast<ConstantInt>(Val)) {
  if (CI->getBitWidth() <= 32) {
    constIntValue = CI->getSExtValue();
  }
}

Of course, you can also change it to <= 64 if constIntValue is a 64-bit integer, etc.

And as Eli wrote, if you are confident the value is indeed of type ConstInt, you can use cast<ConstantInt> instead of dyn_cast.