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);
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);
228 vector<Value*> HashArgs(1, V);
229 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
230 BBI = ++BB->getInstList().insert(BBI, cast<Instruction>(V));
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);
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);
263 vector<Value*> releaseArgs(1, V);
264 Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
265 BBI = ++BB->getInstList().insert(BBI, I);
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);
278 vector<Value*> releaseArgs(1, V);
279 Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
280 BBI = ++BB->getInstList().insert(BBI, I);
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()--;
296 BBI = ++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;
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()--;
339 assert(BB->back().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) {
352 InsertPos = SetCC = I; // Back up until we can insert before the setcc
355 std::ostringstream OutStr;
356 WriteAsOperand(OutStr, BB, false);
357 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
358 Printf, HashPtrToSeqNum);
360 // Insert a print instruction for each value.
362 for (BasicBlock::iterator II = BB->begin(), IE = InsertPos++; II != IE; ++II){
363 if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
364 assert(valuesStoredInFunction &&
365 "Should not be printing a store instruction at function exit");
366 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
367 "reload."+SI->getPointerOperand()->getName());
368 InsertPos = ++BB->getInstList().insert(InsertPos, LI);
369 valuesStoredInFunction->push_back(LI);
371 if (ShouldTraceValue(II))
372 InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
376 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
377 Function* HashPtrToSeqNum){
378 // Get an iterator to point to the insertion location
379 BasicBlock &BB = M->getEntryNode();
380 BasicBlock::iterator BBI = BB.begin();
382 std::ostringstream OutStr;
383 WriteAsOperand(OutStr, M, true);
384 InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
385 Printf, HashPtrToSeqNum);
387 // Now print all the incoming arguments
389 for (Function::aiterator I = M->abegin(), E = M->aend(); I != E; ++I,++ArgNo){
390 InsertVerbosePrintInst(I, &BB, BBI,
391 " Arg #" + utostr(ArgNo) + ": ", Printf,
397 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
399 Function* HashPtrToSeqNum) {
400 // Get an iterator to point to the insertion location
401 BasicBlock::iterator BBI = BB->end()--;
402 ReturnInst &Ret = cast<ReturnInst>(BB->back());
404 std::ostringstream OutStr;
405 WriteAsOperand(OutStr, BB->getParent(), true);
406 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(),
407 Printf, HashPtrToSeqNum);
409 // print the return value, if any
410 if (BB->getParent()->getReturnType() != Type::VoidTy)
411 InsertPrintInst(Ret.getReturnValue(), BB, BBI, " Returning: ",
412 Printf, HashPtrToSeqNum);
416 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
417 bool traceFunctionEvents,
418 ExternalFuncs& externalFuncs) {
419 if (!traceBasicBlockExits && !traceFunctionEvents)
422 if (!TraceThisFunction(M))
425 vector<Instruction*> valuesStoredInFunction;
426 vector<BasicBlock*> exitBlocks;
428 // Insert code to trace values at function entry
429 if (traceFunctionEvents)
430 InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
431 externalFuncs.HashPtrFunc);
433 // Push a pointer set for recording alloca'd pointers at entry.
434 if (!DisablePtrHashing)
435 InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
437 for (Function::iterator BB = M->begin(); BB != M->end(); ++BB) {
438 if (isa<ReturnInst>(BB->getTerminator()))
439 exitBlocks.push_back(BB); // record this as an exit block
441 if (traceBasicBlockExits)
442 TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
443 externalFuncs.HashPtrFunc, &valuesStoredInFunction);
445 if (!DisablePtrHashing) // release seq. numbers on free/ret
446 ReleasePtrSeqNumbers(BB, externalFuncs);
449 for (unsigned i=0; i < exitBlocks.size(); ++i)
451 // Insert code to trace values at function exit
452 if (traceFunctionEvents)
453 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
454 externalFuncs.HashPtrFunc);
456 // Release all recorded pointers before RETURN. Do this LAST!
457 if (!DisablePtrHashing)
458 InsertReleaseRecordedInst(exitBlocks[i],
459 externalFuncs.ReleaseOnReturnFunc);