1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and method
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Instrumentation/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/ConstantVals.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Function.h"
16 #include "llvm/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "Support/StringExtras.h"
25 class InsertTraceCode : public MethodPass {
26 bool TraceBasicBlockExits, TraceFunctionExits;
29 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
30 : TraceBasicBlockExits(traceBasicBlockExits),
31 TraceFunctionExits(traceFunctionExits) {}
33 // Add a prototype for printf if it is not already in the program.
35 bool doInitialization(Module *M);
37 //--------------------------------------------------------------------------
38 // Function InsertCodeToTraceValues
40 // Inserts tracing code for all live values at basic block and/or method
41 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
43 static bool doit(Function *M, bool traceBasicBlockExits,
44 bool traceFunctionExits, Function *Printf);
46 // runOnMethod - This method does the work. Always successful.
48 bool runOnMethod(Function *F) {
49 return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc);
52 } // end anonymous namespace
55 Pass *createTraceValuesPassForMethod() { // Just trace methods
56 return new InsertTraceCode(false, true);
59 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and methods
60 return new InsertTraceCode(true, true);
66 // Add a prototype for printf if it is not already in the program.
68 bool InsertTraceCode::doInitialization(Module *M) {
69 const Type *SBP = PointerType::get(Type::SByteTy);
70 const MethodType *MTy =
71 MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
73 PrintfFunc = M->getOrInsertFunction("printf", MTy);
78 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
79 // Create a constant internal string reference...
80 Constant *Init = ConstantArray::get(str);
82 // Create the global variable and record it in the module
83 // The GV will be renamed to a unique name if needed.
84 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
86 M->getGlobalList().push_back(GV);
92 // Check if this instruction has any uses outside its basic block,
93 // or if it used by either a Call or Return instruction.
95 static inline bool LiveAtBBExit(const Instruction* I) {
96 const BasicBlock *BB = I->getParent();
97 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
98 if (const Instruction *UI = dyn_cast<Instruction>(*U))
99 if (UI->getParent() != BB || isa<ReturnInst>(UI))
106 static inline bool TraceThisOpCode(unsigned opCode) {
107 // Explicitly test for opCodes *not* to trace so that any new opcodes will
108 // be traced by default (VoidTy's are already excluded)
110 return (opCode < Instruction::FirstOtherOp &&
111 opCode != Instruction::Alloca &&
112 opCode != Instruction::PHINode &&
113 opCode != Instruction::Cast);
117 static bool ShouldTraceValue(const Instruction *I) {
119 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
120 TraceThisOpCode(I->getOpcode());
123 static string getPrintfCodeFor(const Value *V) {
124 if (V == 0) return "";
125 switch (V->getType()->getPrimitiveID()) {
127 case Type::UByteTyID: case Type::UShortTyID:
128 case Type::UIntTyID: case Type::ULongTyID:
129 case Type::SByteTyID: case Type::ShortTyID:
130 case Type::IntTyID: case Type::LongTyID:
133 case Type::FloatTyID: case Type::DoubleTyID:
136 case Type::LabelTyID: case Type::PointerTyID:
140 assert(0 && "Illegal value to print out...");
146 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
147 string Message, Function *Printf) {
148 // Escape Message by replacing all % characters with %% chars.
150 while ((Offset = Message.find('%', Offset)) != string::npos) {
151 Message.replace(Offset, 2, "%%");
152 Offset += 2; // Skip over the new %'s
155 Module *Mod = BB->getParent()->getParent();
157 // Turn the marker string into a global variable...
158 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
160 // Turn the format string into an sbyte *
162 new GetElementPtrInst(fmtVal,
163 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
165 BBI = BB->getInstList().insert(BBI, GEP)+1;
167 // Insert the first print instruction to print the string flag:
168 vector<Value*> PrintArgs;
169 PrintArgs.push_back(GEP);
170 if (V) PrintArgs.push_back(V);
171 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
172 BBI = BB->getInstList().insert(BBI, I)+1;
176 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
177 BasicBlock::iterator &BBI,
178 const string &Message, Function *Printf) {
179 std::ostringstream OutStr;
180 if (V) WriteAsOperand(OutStr, V);
181 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
185 // Insert print instructions at the end of the basic block *bb
186 // for each value in valueVec[] that is live at the end of that basic block,
187 // or that is stored to memory in this basic block.
188 // If the value is stored to memory, we load it back before printing
189 // We also return all such loaded values in the vector valuesStoredInFunction
190 // for printing at the exit from the method. (Note that in each invocation
191 // of the method, this will only get the last value stored for each static
192 // store instruction).
193 // *bb must be the block in which the value is computed;
194 // this is not checked here.
196 static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf,
197 vector<Instruction*> *valuesStoredInFunction) {
198 // Get an iterator to point to the insertion location, which is
199 // just before the terminator instruction.
201 BasicBlock::iterator InsertPos = BB->end()-1;
202 assert((*InsertPos)->isTerminator());
204 // If the terminator is a conditional branch, insert the trace code just
205 // before the instruction that computes the branch condition (just to
206 // avoid putting a call between the CC-setting instruction and the branch).
207 // Use laterInstrSet to mark instructions that come after the setCC instr
208 // because those cannot be traced at the location we choose.
210 Instruction *SetCC = 0;
211 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
212 if (!Branch->isUnconditional())
213 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
214 if (I->getParent() == BB) {
216 while (*InsertPos != SetCC)
217 --InsertPos; // Back up until we can insert before the setcc
220 // Copy all of the instructions into a vector to avoid problems with Setcc
221 const vector<Instruction*> Insts(BB->begin(), InsertPos);
223 std::ostringstream OutStr;
224 WriteAsOperand(OutStr, BB, false);
225 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
227 // Insert a print instruction for each value.
229 for (vector<Instruction*>::const_iterator II = Insts.begin(),
230 IE = Insts.end(); II != IE; ++II) {
231 Instruction *I = *II;
232 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
233 assert(valuesStoredInFunction &&
234 "Should not be printing a store instruction at method exit");
235 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
237 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
238 valuesStoredInFunction->push_back(LI);
240 if (ShouldTraceValue(I))
241 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
245 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){
246 // Get an iterator to point to the insertion location
247 BasicBlock *BB = M->getEntryNode();
248 BasicBlock::iterator BBI = BB->begin();
250 std::ostringstream OutStr;
251 WriteAsOperand(OutStr, M, true);
252 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
254 // Now print all the incoming arguments
255 const Function::ArgumentListType &argList = M->getArgumentList();
257 for (Function::ArgumentListType::const_iterator
258 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
259 InsertVerbosePrintInst(*I, BB, BBI,
260 " Arg #" + utostr(ArgNo), Printf);
265 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
267 // Get an iterator to point to the insertion location
268 BasicBlock::iterator BBI = BB->end()-1;
269 ReturnInst *Ret = cast<ReturnInst>(*BBI);
271 std::ostringstream OutStr;
272 WriteAsOperand(OutStr, BB->getParent(), true);
273 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
275 // print the return value, if any
276 if (BB->getParent()->getReturnType() != Type::VoidTy)
277 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
281 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
282 bool traceFunctionEvents, Function *Printf) {
283 if (!traceBasicBlockExits && !traceFunctionEvents)
286 vector<Instruction*> valuesStoredInFunction;
287 vector<BasicBlock*> exitBlocks;
289 if (traceFunctionEvents)
290 InsertCodeToShowFunctionEntry(M, Printf);
292 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
293 BasicBlock *BB = *BI;
294 if (isa<ReturnInst>(BB->getTerminator()))
295 exitBlocks.push_back(BB); // record this as an exit block
297 if (traceBasicBlockExits)
298 TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction);
301 if (traceFunctionEvents)
302 for (unsigned i=0; i < exitBlocks.size(); ++i) {
304 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module,
305 /*indent*/ 0, /*isFunctionExit*/ true,
306 /*valuesStoredInFunction*/ NULL);
308 InsertCodeToShowFunctionExit(exitBlocks[i], Printf);