Print 128 bit value at runtime using printf

Hi,

I was trying to print out a 128 bit result at runtime using a call to printf in LLVM.

I am able to print 32 uptil 64 bit integers using the format string “%d” in printf .

Please see the code in red below , as I am having a bit difficulty in trying to print the 128 bit value computed at runtime. The code in red is never executed since the value may never be casted to a ConstantInt.

( I saw this approach on SO - https://stackoverflow.com/questions/5315176/llvm-get-constant-integer-back-from-value )

//========= Relevant code below ==========

Value* val = e->codegen() ;

if(!val)
{
return logError(“Error evaluating argument to function call”);
}

if(val->getType()->isIntegerTy() )
{
if(val->getType()->getIntegerBitWidth() <= 64)
{
tempString = tempString + “%+d,”;
}

// Is this correct ?
else
{

if(ConstantInt* CI = dyn_cast(val))
{

// base 10 and signed
std::string res = CI->getValue().toString(10,true);
val=Builder.CreateGlobalStringPtr(res,“str”);

tempString = tempString + “%+s,”;

}

}

tempString = tempString + “%+d,”;
}

// if any of the 6 floating point types
else if(val->getType()->isFloatingPointTy())
{
tempString = tempString + “%+f,”;

//Apparently this is needed by printf,otehrwise prints 0.000
val = convertType(val,Type::getDoubleTy(TheContext));

}

argsValueVector.push_back(val);
++i;

}

formatString = formatString + tempString + “\n” ;

// For something like printf , insert a format string at the beginning.
if( F->isVarArg() )
{

// every string is declared as a “global constant” at the top of the module.
Value* val=Builder.CreateGlobalStringPtr(formatString,“str”);

std::vector<Value*>::iterator it = argsValueVector.begin();

argsValueVector.insert(it,val);
}

return Builder.CreateCall(F,argsValueVector,“calltmp”) ;

}

The same answer applies now as when you asked last week. printf cannot
format an i128 so you need to do that yourself. You need to write a
"print128" function and insert a call to that instead of (or as well
as) printf. Link your compiled code against your implementation of
print128 and you should be good to go.

Tim.

Please stop dropping llvm-dev from your replies. I've added it back in again.

Can I not just convert the result of the computation into a string and then
use printf to display it ?

Yes, that's another alternative. You can implement a function to just
do the conversion without actually printing it. Ownership is more
complicated: does the function malloc a buffer and return that? Get
one passed in? Use a statically allocated buffer? But for that price
you probably get more flexibility.

Cheers.

Tim.