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/CommandLine.h"
21 #include "Support/StringExtras.h"
27 static cl::Flag DisablePtrHashing("tracedisablehashdisable",
28 "Disable pointer hashing", cl::NoFlags);
30 static cl::StringList TraceFuncName ("tracefunc", "trace only specific funct"
34 // We trace a particular function if no functions to trace were specified
35 // or if the function is in the specified list.
38 TraceThisFunction(Function* func)
40 if (TraceFuncName.getNumOccurances() == 0)
43 return std::find(TraceFuncName.begin(), TraceFuncName.end(), func->getName())
44 != TraceFuncName.end();
49 struct ExternalFuncs {
50 Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
51 Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
52 void doInitialization(Module *M); // Add prototypes for external functions
55 class InsertTraceCode : public FunctionPass {
56 bool TraceBasicBlockExits, TraceFunctionExits;
57 ExternalFuncs externalFuncs;
59 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
60 : TraceBasicBlockExits(traceBasicBlockExits),
61 TraceFunctionExits(traceFunctionExits) {}
63 const char *getPassName() const { return "Trace Code Insertion"; }
65 // Add a prototype for runtime functions not already in the program.
67 bool doInitialization(Module *M);
69 //--------------------------------------------------------------------------
70 // Function InsertCodeToTraceValues
72 // Inserts tracing code for all live values at basic block and/or function
73 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
75 static bool doit(Function *M, bool traceBasicBlockExits,
76 bool traceFunctionExits, ExternalFuncs& externalFuncs);
78 // runOnFunction - This method does the work.
80 bool runOnFunction(Function *F) {
81 return doit(F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 } // end anonymous namespace
91 Pass *createTraceValuesPassForFunction() { // Just trace functions
92 return new InsertTraceCode(false, true);
95 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
96 return new InsertTraceCode(true, true);
99 // Add a prototype for external functions used by the tracing code.
101 void ExternalFuncs::doInitialization(Module *M) {
102 const Type *SBP = PointerType::get(Type::SByteTy);
103 const FunctionType *MTy =
104 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
105 PrintfFunc = M->getOrInsertFunction("printf", MTy);
108 const FunctionType *hashFuncTy =
109 FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
110 HashPtrFunc = M->getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
113 const FunctionType *voidSBPFuncTy =
114 FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
116 ReleasePtrFunc =M->getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
117 RecordPtrFunc = M->getOrInsertFunction("RecordPointer", voidSBPFuncTy);
119 const FunctionType *voidvoidFuncTy =
120 FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
122 PushOnEntryFunc = M->getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
123 ReleaseOnReturnFunc = M->getOrInsertFunction("ReleasePointersPopSet",
128 // Add a prototype for external functions used by the tracing code.
130 bool InsertTraceCode::doInitialization(Module *M) {
131 externalFuncs.doInitialization(M);
136 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
137 // Create a constant internal string reference...
138 Constant *Init = ConstantArray::get(str);
140 // Create the global variable and record it in the module
141 // The GV will be renamed to a unique name if needed.
142 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
144 M->getGlobalList().push_back(GV);
150 // Check if this instruction has any uses outside its basic block,
151 // or if it used by either a Call or Return instruction.
153 static inline bool LiveAtBBExit(const Instruction* I) {
154 const BasicBlock *BB = I->getParent();
155 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
156 if (const Instruction *UI = dyn_cast<Instruction>(*U))
157 if (UI->getParent() != BB || isa<ReturnInst>(UI))
164 static inline bool TraceThisOpCode(unsigned opCode) {
165 // Explicitly test for opCodes *not* to trace so that any new opcodes will
166 // be traced by default (VoidTy's are already excluded)
168 return (opCode < Instruction::FirstOtherOp &&
169 opCode != Instruction::Alloca &&
170 opCode != Instruction::PHINode &&
171 opCode != Instruction::Cast);
175 static bool ShouldTraceValue(const Instruction *I) {
177 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
178 TraceThisOpCode(I->getOpcode());
181 static string getPrintfCodeFor(const Value *V) {
182 if (V == 0) return "";
183 if (V->getType()->isFloatingPoint())
185 else if (V->getType() == Type::LabelTy)
187 else if (isa<PointerType>(V->getType()))
188 return DisablePtrHashing ? "0x%p" : "%d";
189 else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
192 assert(0 && "Illegal value to print out...");
197 static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
199 Function *Printf, Function* HashPtrToSeqNum) {
200 // Escape Message by replacing all % characters with %% chars.
202 while ((Offset = Message.find('%', Offset)) != string::npos) {
203 Message.replace(Offset, 1, "%%");
204 Offset += 2; // Skip over the new %'s
207 Module *Mod = BB->getParent()->getParent();
209 // Turn the marker string into a global variable...
210 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
212 // Turn the format string into an sbyte *
214 new GetElementPtrInst(fmtVal,
215 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
217 BBI = BB->getInstList().insert(BBI, GEP)+1;
219 // Insert a call to the hash function if this is a pointer value
220 if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
221 const Type *SBP = PointerType::get(Type::SByteTy);
222 if (V->getType() != SBP) { // Cast pointer to be sbyte*
223 Instruction *I = new CastInst(V, SBP, "Hash_cast");
224 BBI = BB->getInstList().insert(BBI, I)+1;
228 vector<Value*> HashArgs(1, V);
229 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
230 BBI = BB->getInstList().insert(BBI, cast<Instruction>(V))+1;
233 // Insert the first print instruction to print the string flag:
234 vector<Value*> PrintArgs;
235 PrintArgs.push_back(GEP);
236 if (V) PrintArgs.push_back(V);
237 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
238 BBI = BB->getInstList().insert(BBI, I)+1;
242 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
243 BasicBlock::iterator &BBI,
244 const string &Message, Function *Printf,
245 Function* HashPtrToSeqNum) {
246 std::ostringstream OutStr;
247 if (V) WriteAsOperand(OutStr, V);
248 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ",
249 Printf, HashPtrToSeqNum);
253 InsertReleaseInst(Value *V, BasicBlock *BB,
254 BasicBlock::iterator &BBI,
255 Function* ReleasePtrFunc) {
257 const Type *SBP = PointerType::get(Type::SByteTy);
258 if (V->getType() != SBP) { // Cast pointer to be sbyte*
259 Instruction *I = new CastInst(V, SBP, "RPSN_cast");
260 BBI = BB->getInstList().insert(BBI, I)+1;
263 vector<Value*> releaseArgs(1, V);
264 Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
265 BBI = BB->getInstList().insert(BBI, I)+1;
269 InsertRecordInst(Value *V, BasicBlock *BB,
270 BasicBlock::iterator &BBI,
271 Function* RecordPtrFunc) {
272 const Type *SBP = PointerType::get(Type::SByteTy);
273 if (V->getType() != SBP) { // Cast pointer to be sbyte*
274 Instruction *I = new CastInst(V, SBP, "RP_cast");
275 BBI = BB->getInstList().insert(BBI, I)+1;
278 vector<Value*> releaseArgs(1, V);
279 Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
280 BBI = BB->getInstList().insert(BBI, I)+1;
284 InsertPushOnEntryFunc(Function *M,
285 Function* PushOnEntryFunc) {
286 // Get an iterator to point to the insertion location
287 BasicBlock *BB = M->getEntryNode();
288 BB->getInstList().insert(BB->begin(), new CallInst(PushOnEntryFunc,
293 InsertReleaseRecordedInst(BasicBlock *BB,
294 Function* ReleaseOnReturnFunc) {
295 BasicBlock::iterator BBI = BB->end()-1;
296 BBI = 1 + BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
300 // Look for alloca and free instructions. These are the ptrs to release.
301 // Release the free'd pointers immediately. Record the alloca'd pointers
302 // to be released on return from the current function.
305 ReleasePtrSeqNumbers(BasicBlock *BB,
306 ExternalFuncs& externalFuncs) {
308 for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
309 if (FreeInst *FI = dyn_cast<FreeInst>(*II))
310 InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
311 else if (AllocaInst *AI = dyn_cast<AllocaInst>(*II))
313 BasicBlock::iterator nextI = II+1;
314 InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);
321 // Insert print instructions at the end of the basic block *bb
322 // for each value in valueVec[] that is live at the end of that basic block,
323 // or that is stored to memory in this basic block.
324 // If the value is stored to memory, we load it back before printing
325 // We also return all such loaded values in the vector valuesStoredInFunction
326 // for printing at the exit from the function. (Note that in each invocation
327 // of the function, this will only get the last value stored for each static
328 // store instruction).
329 // *bb must be the block in which the value is computed;
330 // this is not checked here.
332 static void TraceValuesAtBBExit(BasicBlock *BB,
333 Function *Printf, Function* HashPtrToSeqNum,
334 vector<Instruction*> *valuesStoredInFunction) {
335 // Get an iterator to point to the insertion location, which is
336 // just before the terminator instruction.
338 BasicBlock::iterator InsertPos = BB->end()-1;
339 assert((*InsertPos)->isTerminator());
341 // If the terminator is a conditional branch, insert the trace code just
342 // before the instruction that computes the branch condition (just to
343 // avoid putting a call between the CC-setting instruction and the branch).
344 // Use laterInstrSet to mark instructions that come after the setCC instr
345 // because those cannot be traced at the location we choose.
347 Instruction *SetCC = 0;
348 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
349 if (!Branch->isUnconditional())
350 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
351 if (I->getParent() == BB) {
353 while (*InsertPos != SetCC)
354 --InsertPos; // Back up until we can insert before the setcc
357 // Copy all of the instructions into a vector to avoid problems with Setcc
358 const vector<Instruction*> Insts(BB->begin(), InsertPos);
360 std::ostringstream OutStr;
361 WriteAsOperand(OutStr, BB, false);
362 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
363 Printf, HashPtrToSeqNum);
365 // Insert a print instruction for each value.
367 for (vector<Instruction*>::const_iterator II = Insts.begin(),
368 IE = Insts.end(); II != IE; ++II) {
369 Instruction *I = *II;
370 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
371 assert(valuesStoredInFunction &&
372 "Should not be printing a store instruction at function exit");
373 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
375 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
376 valuesStoredInFunction->push_back(LI);
378 if (ShouldTraceValue(I))
379 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
383 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
384 Function* HashPtrToSeqNum){
385 // Get an iterator to point to the insertion location
386 BasicBlock *BB = M->getEntryNode();
387 BasicBlock::iterator BBI = BB->begin();
389 std::ostringstream OutStr;
390 WriteAsOperand(OutStr, M, true);
391 InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
392 Printf, HashPtrToSeqNum);
394 // Now print all the incoming arguments
395 const Function::ArgumentListType &argList = M->getArgumentList();
397 for (Function::ArgumentListType::const_iterator
398 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
399 InsertVerbosePrintInst((Value*)*I, BB, BBI,
400 " Arg #" + utostr(ArgNo) + ": ", Printf,
406 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
408 Function* HashPtrToSeqNum) {
409 // Get an iterator to point to the insertion location
410 BasicBlock::iterator BBI = BB->end()-1;
411 ReturnInst *Ret = cast<ReturnInst>(*BBI);
413 std::ostringstream OutStr;
414 WriteAsOperand(OutStr, BB->getParent(), true);
415 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(),
416 Printf, HashPtrToSeqNum);
418 // print the return value, if any
419 if (BB->getParent()->getReturnType() != Type::VoidTy)
420 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ",
421 Printf, HashPtrToSeqNum);
425 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
426 bool traceFunctionEvents,
427 ExternalFuncs& externalFuncs) {
428 if (!traceBasicBlockExits && !traceFunctionEvents)
431 if (!TraceThisFunction(M))
434 vector<Instruction*> valuesStoredInFunction;
435 vector<BasicBlock*> exitBlocks;
437 // Insert code to trace values at function entry
438 if (traceFunctionEvents)
439 InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
440 externalFuncs.HashPtrFunc);
442 // Push a pointer set for recording alloca'd pointers at entry.
443 if (!DisablePtrHashing)
444 InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
446 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
447 BasicBlock *BB = *BI;
448 if (isa<ReturnInst>(BB->getTerminator()))
449 exitBlocks.push_back(BB); // record this as an exit block
451 if (traceBasicBlockExits)
452 TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
453 externalFuncs.HashPtrFunc, &valuesStoredInFunction);
455 if (!DisablePtrHashing) // release seq. numbers on free/ret
456 ReleasePtrSeqNumbers(BB, externalFuncs);
459 for (unsigned i=0; i < exitBlocks.size(); ++i)
461 // Insert code to trace values at function exit
462 if (traceFunctionEvents)
463 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
464 externalFuncs.HashPtrFunc);
466 // Release all recorded pointers before RETURN. Do this LAST!
467 if (!DisablePtrHashing)
468 InsertReleaseRecordedInst(exitBlocks[i],
469 externalFuncs.ReleaseOnReturnFunc);