1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and function
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Instrumentation/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Function.h"
17 #include "llvm/Module.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/StringExtras.h"
26 class InsertTraceCode : public FunctionPass {
27 bool TraceBasicBlockExits, TraceFunctionExits;
30 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
31 : TraceBasicBlockExits(traceBasicBlockExits),
32 TraceFunctionExits(traceFunctionExits) {}
34 // Add a prototype for printf if it is not already in the program.
36 bool doInitialization(Module *M);
38 //--------------------------------------------------------------------------
39 // Function InsertCodeToTraceValues
41 // Inserts tracing code for all live values at basic block and/or function
42 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
44 static bool doit(Function *M, bool traceBasicBlockExits,
45 bool traceFunctionExits, Function *Printf);
47 // runOnFunction - This method does the work.
49 bool runOnFunction(Function *F) {
50 return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc);
53 } // end anonymous namespace
56 Pass *createTraceValuesPassForFunction() { // Just trace functions
57 return new InsertTraceCode(false, true);
60 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
61 return new InsertTraceCode(true, true);
67 // Add a prototype for printf if it is not already in the program.
69 bool InsertTraceCode::doInitialization(Module *M) {
70 const Type *SBP = PointerType::get(Type::SByteTy);
71 const FunctionType *MTy =
72 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
74 PrintfFunc = M->getOrInsertFunction("printf", MTy);
79 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
80 // Create a constant internal string reference...
81 Constant *Init = ConstantArray::get(str);
83 // Create the global variable and record it in the module
84 // The GV will be renamed to a unique name if needed.
85 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
87 M->getGlobalList().push_back(GV);
93 // Check if this instruction has any uses outside its basic block,
94 // or if it used by either a Call or Return instruction.
96 static inline bool LiveAtBBExit(const Instruction* I) {
97 const BasicBlock *BB = I->getParent();
98 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
99 if (const Instruction *UI = dyn_cast<Instruction>(*U))
100 if (UI->getParent() != BB || isa<ReturnInst>(UI))
107 static inline bool TraceThisOpCode(unsigned opCode) {
108 // Explicitly test for opCodes *not* to trace so that any new opcodes will
109 // be traced by default (VoidTy's are already excluded)
111 return (opCode < Instruction::FirstOtherOp &&
112 opCode != Instruction::Alloca &&
113 opCode != Instruction::PHINode &&
114 opCode != Instruction::Cast);
118 static bool ShouldTraceValue(const Instruction *I) {
120 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
121 TraceThisOpCode(I->getOpcode());
124 static string getPrintfCodeFor(const Value *V) {
125 if (V == 0) return "";
126 if (V->getType()->isFloatingPoint())
128 else if (V->getType() == Type::LabelTy || isa<PointerType>(V->getType()))
130 else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
133 assert(0 && "Illegal value to print out...");
138 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
139 string Message, Function *Printf) {
140 // Escape Message by replacing all % characters with %% chars.
142 while ((Offset = Message.find('%', Offset)) != string::npos) {
143 Message.replace(Offset, 1, "%%");
144 Offset += 2; // Skip over the new %'s
147 Module *Mod = BB->getParent()->getParent();
149 // Turn the marker string into a global variable...
150 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
152 // Turn the format string into an sbyte *
154 new GetElementPtrInst(fmtVal,
155 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
157 BBI = BB->getInstList().insert(BBI, GEP)+1;
159 // Insert the first print instruction to print the string flag:
160 vector<Value*> PrintArgs;
161 PrintArgs.push_back(GEP);
162 if (V) PrintArgs.push_back(V);
163 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
164 BBI = BB->getInstList().insert(BBI, I)+1;
168 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
169 BasicBlock::iterator &BBI,
170 const string &Message, Function *Printf) {
171 std::ostringstream OutStr;
172 if (V) WriteAsOperand(OutStr, V);
173 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
177 // Insert print instructions at the end of the basic block *bb
178 // for each value in valueVec[] that is live at the end of that basic block,
179 // or that is stored to memory in this basic block.
180 // If the value is stored to memory, we load it back before printing
181 // We also return all such loaded values in the vector valuesStoredInFunction
182 // for printing at the exit from the function. (Note that in each invocation
183 // of the function, this will only get the last value stored for each static
184 // store instruction).
185 // *bb must be the block in which the value is computed;
186 // this is not checked here.
188 static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf,
189 vector<Instruction*> *valuesStoredInFunction) {
190 // Get an iterator to point to the insertion location, which is
191 // just before the terminator instruction.
193 BasicBlock::iterator InsertPos = BB->end()-1;
194 assert((*InsertPos)->isTerminator());
196 // If the terminator is a conditional branch, insert the trace code just
197 // before the instruction that computes the branch condition (just to
198 // avoid putting a call between the CC-setting instruction and the branch).
199 // Use laterInstrSet to mark instructions that come after the setCC instr
200 // because those cannot be traced at the location we choose.
202 Instruction *SetCC = 0;
203 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
204 if (!Branch->isUnconditional())
205 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
206 if (I->getParent() == BB) {
208 while (*InsertPos != SetCC)
209 --InsertPos; // Back up until we can insert before the setcc
212 // Copy all of the instructions into a vector to avoid problems with Setcc
213 const vector<Instruction*> Insts(BB->begin(), InsertPos);
215 std::ostringstream OutStr;
216 WriteAsOperand(OutStr, BB, false);
217 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
219 // Insert a print instruction for each value.
221 for (vector<Instruction*>::const_iterator II = Insts.begin(),
222 IE = Insts.end(); II != IE; ++II) {
223 Instruction *I = *II;
224 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
225 assert(valuesStoredInFunction &&
226 "Should not be printing a store instruction at function exit");
227 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
229 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
230 valuesStoredInFunction->push_back(LI);
232 if (ShouldTraceValue(I))
233 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
237 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){
238 // Get an iterator to point to the insertion location
239 BasicBlock *BB = M->getEntryNode();
240 BasicBlock::iterator BBI = BB->begin();
242 std::ostringstream OutStr;
243 WriteAsOperand(OutStr, M, true);
244 InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(), Printf);
246 // Now print all the incoming arguments
247 const Function::ArgumentListType &argList = M->getArgumentList();
249 for (Function::ArgumentListType::const_iterator
250 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
251 InsertVerbosePrintInst((Value*)*I, BB, BBI,
252 " Arg #" + utostr(ArgNo), Printf);
257 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
259 // Get an iterator to point to the insertion location
260 BasicBlock::iterator BBI = BB->end()-1;
261 ReturnInst *Ret = cast<ReturnInst>(*BBI);
263 std::ostringstream OutStr;
264 WriteAsOperand(OutStr, BB->getParent(), true);
265 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(), Printf);
267 // print the return value, if any
268 if (BB->getParent()->getReturnType() != Type::VoidTy)
269 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
273 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
274 bool traceFunctionEvents, Function *Printf) {
275 if (!traceBasicBlockExits && !traceFunctionEvents)
278 vector<Instruction*> valuesStoredInFunction;
279 vector<BasicBlock*> exitBlocks;
281 if (traceFunctionEvents)
282 InsertCodeToShowFunctionEntry(M, Printf);
284 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
285 BasicBlock *BB = *BI;
286 if (isa<ReturnInst>(BB->getTerminator()))
287 exitBlocks.push_back(BB); // record this as an exit block
289 if (traceBasicBlockExits)
290 TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction);
293 if (traceFunctionEvents)
294 for (unsigned i=0; i < exitBlocks.size(); ++i) {
296 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module,
297 /*indent*/ 0, /*isFunctionExit*/ true,
298 /*valuesStoredInFunction*/ NULL);
300 InsertCodeToShowFunctionExit(exitBlocks[i], Printf);