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/Constants.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Module.h"
15 #include "llvm/Pass.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "Support/CommandLine.h"
18 #include "Support/StringExtras.h"
25 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
26 cl::desc("Disable pointer hashing"));
28 static cl::list<string>
29 TraceFuncName("tracefunc", cl::desc("trace only specific functions"),
30 cl::value_desc("function"), cl::Hidden);
32 static void TraceValuesAtBBExit(BasicBlock *BB,
33 Function *Printf, Function* HashPtrToSeqNum,
34 vector<Instruction*> *valuesStoredInFunction);
36 // We trace a particular function if no functions to trace were specified
37 // or if the function is in the specified list.
40 TraceThisFunction(Function &func)
42 if (TraceFuncName.size() == 0)
45 return std::find(TraceFuncName.begin(), TraceFuncName.end(), func.getName())
46 != TraceFuncName.end();
51 struct ExternalFuncs {
52 Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
53 Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
54 void doInitialization(Module &M); // Add prototypes for external functions
57 class InsertTraceCode : public FunctionPass {
59 ExternalFuncs externalFuncs;
62 // Add a prototype for runtime functions not already in the program.
64 bool doInitialization(Module &M);
66 //--------------------------------------------------------------------------
67 // Function InsertCodeToTraceValues
69 // Inserts tracing code for all live values at basic block and/or function
70 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
72 bool doit(Function *M);
74 virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
76 // runOnFunction - This method does the work.
78 bool runOnFunction(Function &F);
80 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 struct FunctionTracer : public InsertTraceCode {
86 // Ignore basic blocks here...
87 virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
90 struct BasicBlockTracer : public InsertTraceCode {
91 // Trace basic blocks here...
92 virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
93 TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
94 externalFuncs.HashPtrFunc, &VI);
98 // Register the passes...
99 RegisterOpt<FunctionTracer> X("tracem","Insert Function trace code only");
100 RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
101 } // end anonymous namespace
104 Pass *createTraceValuesPassForFunction() { // Just trace functions
105 return new FunctionTracer();
108 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
109 return new BasicBlockTracer();
113 // Add a prototype for external functions used by the tracing code.
115 void ExternalFuncs::doInitialization(Module &M) {
116 const Type *SBP = PointerType::get(Type::SByteTy);
117 const FunctionType *MTy =
118 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
119 PrintfFunc = M.getOrInsertFunction("printf", MTy);
122 const FunctionType *hashFuncTy =
123 FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
124 HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
127 const FunctionType *voidSBPFuncTy =
128 FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
130 ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
131 RecordPtrFunc = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
133 const FunctionType *voidvoidFuncTy =
134 FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
136 PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
137 ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
142 // Add a prototype for external functions used by the tracing code.
144 bool InsertTraceCode::doInitialization(Module &M) {
145 externalFuncs.doInitialization(M);
150 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
151 // Create a constant internal string reference...
152 Constant *Init = ConstantArray::get(str);
154 // Create the global variable and record it in the module
155 // The GV will be renamed to a unique name if needed.
156 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
158 M->getGlobalList().push_back(GV);
164 // Check if this instruction has any uses outside its basic block,
165 // or if it used by either a Call or Return instruction.
167 static inline bool LiveAtBBExit(const Instruction* I) {
168 const BasicBlock *BB = I->getParent();
169 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
170 if (const Instruction *UI = dyn_cast<Instruction>(*U))
171 if (UI->getParent() != BB || isa<ReturnInst>(UI))
178 static inline bool TraceThisOpCode(unsigned opCode) {
179 // Explicitly test for opCodes *not* to trace so that any new opcodes will
180 // be traced by default (VoidTy's are already excluded)
182 return (opCode < Instruction::FirstOtherOp &&
183 opCode != Instruction::Alloca &&
184 opCode != Instruction::PHINode &&
185 opCode != Instruction::Cast);
189 static bool ShouldTraceValue(const Instruction *I) {
191 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
192 TraceThisOpCode(I->getOpcode());
195 static string getPrintfCodeFor(const Value *V) {
196 if (V == 0) return "";
197 if (V->getType()->isFloatingPoint())
199 else if (V->getType() == Type::LabelTy)
201 else if (isa<PointerType>(V->getType()))
202 return DisablePtrHashing ? "0x%p" : "%d";
203 else if (V->getType()->isIntegral())
206 assert(0 && "Illegal value to print out...");
211 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
213 Function *Printf, Function* HashPtrToSeqNum) {
214 // Escape Message by replacing all % characters with %% chars.
216 while ((Offset = Message.find('%', Offset)) != string::npos) {
217 Message.replace(Offset, 1, "%%");
218 Offset += 2; // Skip over the new %'s
221 Module *Mod = BB->getParent()->getParent();
223 // Turn the marker string into a global variable...
224 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
226 // Turn the format string into an sbyte *
228 new GetElementPtrInst(fmtVal,
229 vector<Value*>(2,ConstantSInt::get(Type::LongTy, 0)),
230 "trstr", InsertBefore);
232 // Insert a call to the hash function if this is a pointer value
233 if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
234 const Type *SBP = PointerType::get(Type::SByteTy);
235 if (V->getType() != SBP) // Cast pointer to be sbyte*
236 V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
238 vector<Value*> HashArgs(1, V);
239 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
242 // Insert the first print instruction to print the string flag:
243 vector<Value*> PrintArgs;
244 PrintArgs.push_back(GEP);
245 if (V) PrintArgs.push_back(V);
246 new CallInst(Printf, PrintArgs, "trace", InsertBefore);
250 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
251 Instruction *InsertBefore,
252 const string &Message, Function *Printf,
253 Function* HashPtrToSeqNum) {
254 std::ostringstream OutStr;
255 if (V) WriteAsOperand(OutStr, V);
256 InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
257 Printf, HashPtrToSeqNum);
261 InsertReleaseInst(Value *V, BasicBlock *BB,
262 Instruction *InsertBefore,
263 Function* ReleasePtrFunc) {
265 const Type *SBP = PointerType::get(Type::SByteTy);
266 if (V->getType() != SBP) // Cast pointer to be sbyte*
267 V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
269 vector<Value*> releaseArgs(1, V);
270 new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
274 InsertRecordInst(Value *V, BasicBlock *BB,
275 Instruction *InsertBefore,
276 Function* RecordPtrFunc) {
277 const Type *SBP = PointerType::get(Type::SByteTy);
278 if (V->getType() != SBP) // Cast pointer to be sbyte*
279 V = new CastInst(V, SBP, "RP_cast", InsertBefore);
281 vector<Value*> releaseArgs(1, V);
282 new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
285 // Look for alloca and free instructions. These are the ptrs to release.
286 // Release the free'd pointers immediately. Record the alloca'd pointers
287 // to be released on return from the current function.
290 ReleasePtrSeqNumbers(BasicBlock *BB,
291 ExternalFuncs& externalFuncs) {
293 for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
294 if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
295 InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
296 else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
297 InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
301 // Insert print instructions at the end of basic block BB for each value
302 // computed in BB that is live at the end of BB,
303 // or that is stored to memory in BB.
304 // If the value is stored to memory, we load it back before printing it
305 // We also return all such loaded values in the vector valuesStoredInFunction
306 // for printing at the exit from the function. (Note that in each invocation
307 // of the function, this will only get the last value stored for each static
308 // store instruction).
310 static void TraceValuesAtBBExit(BasicBlock *BB,
311 Function *Printf, Function* HashPtrToSeqNum,
312 vector<Instruction*> *valuesStoredInFunction) {
313 // Get an iterator to point to the insertion location, which is
314 // just before the terminator instruction.
316 TerminatorInst *InsertPos = BB->getTerminator();
318 std::ostringstream OutStr;
319 WriteAsOperand(OutStr, BB, false);
320 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
321 Printf, HashPtrToSeqNum);
323 // Insert a print instruction for each instruction preceding InsertPos.
324 // The print instructions must go before InsertPos, so we use the
325 // instruction *preceding* InsertPos to check when to terminate the loop.
327 for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
328 if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
329 assert(valuesStoredInFunction &&
330 "Should not be printing a store instruction at function exit");
331 LoadInst *LI = new LoadInst(SI->getPointerOperand(), "reload." +
332 SI->getPointerOperand()->getName(),
334 valuesStoredInFunction->push_back(LI);
336 if (ShouldTraceValue(II))
337 InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
341 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
342 Function* HashPtrToSeqNum){
343 // Get an iterator to point to the insertion location
344 BasicBlock &BB = F.getEntryNode();
345 Instruction *InsertPos = BB.begin();
347 std::ostringstream OutStr;
348 WriteAsOperand(OutStr, &F, true);
349 InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
350 Printf, HashPtrToSeqNum);
352 // Now print all the incoming arguments
354 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
355 InsertVerbosePrintInst(I, &BB, InsertPos,
356 " Arg #" + utostr(ArgNo) + ": ", Printf,
362 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
364 Function* HashPtrToSeqNum) {
365 // Get an iterator to point to the insertion location
366 ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
368 std::ostringstream OutStr;
369 WriteAsOperand(OutStr, BB->getParent(), true);
370 InsertPrintInst(0, BB, Ret, "LEAVING FUNCTION: " + OutStr.str(),
371 Printf, HashPtrToSeqNum);
373 // print the return value, if any
374 if (BB->getParent()->getReturnType() != Type::VoidTy)
375 InsertPrintInst(Ret->getReturnValue(), BB, Ret, " Returning: ",
376 Printf, HashPtrToSeqNum);
380 bool InsertTraceCode::runOnFunction(Function &F) {
381 if (!TraceThisFunction(F))
384 vector<Instruction*> valuesStoredInFunction;
385 vector<BasicBlock*> exitBlocks;
387 // Insert code to trace values at function entry
388 InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
389 externalFuncs.HashPtrFunc);
391 // Push a pointer set for recording alloca'd pointers at entry.
392 if (!DisablePtrHashing)
393 new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
394 F.getEntryNode().begin());
396 for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
397 if (isa<ReturnInst>(BB->getTerminator()))
398 exitBlocks.push_back(BB); // record this as an exit block
400 // Insert trace code if this basic block is interesting...
401 handleBasicBlock(BB, valuesStoredInFunction);
403 if (!DisablePtrHashing) // release seq. numbers on free/ret
404 ReleasePtrSeqNumbers(BB, externalFuncs);
407 for (unsigned i=0; i != exitBlocks.size(); ++i)
409 // Insert code to trace values at function exit
410 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
411 externalFuncs.HashPtrFunc);
413 // Release all recorded pointers before RETURN. Do this LAST!
414 if (!DisablePtrHashing)
415 new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
416 exitBlocks[i]->getTerminator());