How to emit a "printf" call into LLVM IR representation code

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

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

The easiest way might be to use llvm-gcc and have it emit llvm IR for your sample code. This works for just about anything.

That said in your case what you want appears to be a non-varargs version of printf. In this case you'd need to create a special "printf" that only took the two arguments you want and then call it.

I'm not sure why you're doing this so much more is a bit difficult since I'd be guessing.

-eric