[cfe-dev] How to emit a "printf" call into LLVM IR representation code

peng li peterlee at cs.utah.edu
Wed May 19 01:24:47 PDT 2010


Hi There

I found that Clang can emit the intrinsic method easily if you can 
specify the intrinsic ID supported by LLVM, for example:

  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1); 
  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, 
Ops.RHS); // snippet code of "EmitOverflowCheckedBinOp" in CGExprScalar.cpp

However, seems the "printf" does not belong to the intrinsic category. I 
carefully checked the code and found that "printf" is dealt with via the 
member function "CodeGenFunction::EmitCall" in CGCall.cpp.
Within this member function, the printf call is obtained via calling "CS 
= Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size())", the 
signature of CreateCall is defined in IRBuilder.h hearder file:

CallInst <http://llvm.org/doxygen/classllvm_1_1CallInst.html> *CreateCall <http://llvm.org/doxygen/classllvm_1_1IRBuilder.html#a7e31b0c02df2aeed261b103b790cc01e>(Value <http://llvm.org/doxygen/classllvm_1_1Value.html> *Callee, InputIterator ArgBegin,InputIterator ArgEnd, const Twine <http://llvm.org/doxygen/classllvm_1_1Twine.html> &Name <http://llvm.org/doxygen/namespacellvm_1_1GraphProgram.html#a0ad4685976f8c4d4a697a53fbe05d10b> = "") {
     return Insert <http://llvm.org/doxygen/classllvm_1_1IRBuilder.html#a58099a125ba50d21c804b28c9481f5fd>(CallInst::Create <http://llvm.org/doxygen/classllvm_1_1CallInst.html#aba8bae6cf4331b8266b24456933341ad>(Callee, ArgBegin, ArgEnd), Name <http://llvm.org/doxygen/namespacellvm_1_1GraphProgram.html#a0ad4685976f8c4d4a697a53fbe05d10b>);
}


Actually, I also want to resort to CreateCall function to automatically 
emit the concrete printf command, and I think I have finished the first 
argument, which is constructed via
calling "llvm::Value *CodeGenModule::getBuiltinLibFunction(const 
FunctionDecl *FD, unsigned BuiltinID)", where FD can be implemented via 
building a pointer to a FunctionDecl object, BuiltID is 372.
However, I am a little bit confused about how to construct the *Argument 
*vector, for example, let's take a look at a simple printf case.

Printf("Sum: %d\n", sum);

If I want to instrument this printf command, two arguments should be 
dealt with, the first should be i8* type, the second should be i32 type. 
How to infer and assemble those two arguments into two "llvm::value" 
objects
is my question. Any hint is highly appreciated!



Regards


Peng






More information about the cfe-dev mailing list