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 basic block BB for each value
322 // computed in BB that is live at the end of BB,
323 // or that is stored to memory in BB.
324 // If the value is stored to memory, we load it back before printing it
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).
330 static void TraceValuesAtBBExit(BasicBlock *BB,
331 Function *Printf, Function* HashPtrToSeqNum,
332 vector<Instruction*> *valuesStoredInFunction) {
333 // Get an iterator to point to the insertion location, which is
334 // just before the terminator instruction.
336 BasicBlock::iterator InsertPos = --BB->end();
337 assert(InsertPos->isTerminator());
339 #undef CANNOT_SAVE_CCR_ACROSS_CALLS
340 #ifdef CANNOT_SAVE_CCR_ACROSS_CALLS
342 // *** DISABLING THIS BECAUSE SAVING %CCR ACROSS CALLS WORKS NOW.
343 // *** DELETE THIS CODE AFTER SOME TESTING.
344 // *** NOTE: THIS CODE IS BROKEN ANYWAY WHEN THE SETCC IS NOT JUST
345 // *** BEFORE THE BRANCH.
346 // -- Vikram Adve, 7/7/02.
348 // If the terminator is a conditional branch, insert the trace code just
349 // before the instruction that computes the branch condition (just to
350 // avoid putting a call between the CC-setting instruction and the branch).
351 // Use laterInstrSet to mark instructions that come after the setCC instr
352 // because those cannot be traced at the location we choose.
354 Instruction *SetCC = 0;
355 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
356 if (!Branch->isUnconditional())
357 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
358 if (I->getParent() == BB) {
359 InsertPos = SetCC = I; // Back up until we can insert before the setcc
361 #endif CANNOT_SAVE_CCR_ACROSS_CALLS
363 std::ostringstream OutStr;
364 WriteAsOperand(OutStr, BB, false);
365 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
366 Printf, HashPtrToSeqNum);
368 // Insert a print instruction for each instruction preceding InsertPos.
369 // The print instructions must go before InsertPos, so we use the
370 // instruction *preceding* InsertPos to check when to terminate the loop.
372 if (InsertPos != BB->begin()) { // there's at least one instr before InsertPos
373 BasicBlock::iterator II = BB->begin(), IEincl = InsertPos;
375 do { // do from II up to IEincl, inclusive
376 if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
377 assert(valuesStoredInFunction &&
378 "Should not be printing a store instruction at function exit");
379 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
380 "reload."+SI->getPointerOperand()->getName());
381 InsertPos = ++BB->getInstList().insert(InsertPos, LI);
382 valuesStoredInFunction->push_back(LI);
384 if (ShouldTraceValue(II))
385 InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf,HashPtrToSeqNum);
386 } while (II++ != IEincl);
390 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
391 Function* HashPtrToSeqNum){
392 // Get an iterator to point to the insertion location
393 BasicBlock &BB = M->getEntryNode();
394 BasicBlock::iterator BBI = BB.begin();
396 std::ostringstream OutStr;
397 WriteAsOperand(OutStr, M, true);
398 InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
399 Printf, HashPtrToSeqNum);
401 // Now print all the incoming arguments
403 for (Function::aiterator I = M->abegin(), E = M->aend(); I != E; ++I,++ArgNo){
404 InsertVerbosePrintInst(I, &BB, BBI,
405 " Arg #" + utostr(ArgNo) + ": ", Printf,
411 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
413 Function* HashPtrToSeqNum) {
414 // Get an iterator to point to the insertion location
415 BasicBlock::iterator BBI = --BB->end();
416 ReturnInst &Ret = cast<ReturnInst>(BB->back());
418 std::ostringstream OutStr;
419 WriteAsOperand(OutStr, BB->getParent(), true);
420 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(),
421 Printf, HashPtrToSeqNum);
423 // print the return value, if any
424 if (BB->getParent()->getReturnType() != Type::VoidTy)
425 InsertPrintInst(Ret.getReturnValue(), BB, BBI, " Returning: ",
426 Printf, HashPtrToSeqNum);
430 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
431 bool traceFunctionEvents,
432 ExternalFuncs& externalFuncs) {
433 if (!traceBasicBlockExits && !traceFunctionEvents)
436 if (!TraceThisFunction(M))
439 vector<Instruction*> valuesStoredInFunction;
440 vector<BasicBlock*> exitBlocks;
442 // Insert code to trace values at function entry
443 if (traceFunctionEvents)
444 InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
445 externalFuncs.HashPtrFunc);
447 // Push a pointer set for recording alloca'd pointers at entry.
448 if (!DisablePtrHashing)
449 InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
451 for (Function::iterator BB = M->begin(); BB != M->end(); ++BB) {
452 if (isa<ReturnInst>(BB->getTerminator()))
453 exitBlocks.push_back(BB); // record this as an exit block
455 if (traceBasicBlockExits)
456 TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
457 externalFuncs.HashPtrFunc, &valuesStoredInFunction);
459 if (!DisablePtrHashing) // release seq. numbers on free/ret
460 ReleasePtrSeqNumbers(BB, externalFuncs);
463 for (unsigned i=0; i < exitBlocks.size(); ++i)
465 // Insert code to trace values at function exit
466 if (traceFunctionEvents)
467 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
468 externalFuncs.HashPtrFunc);
470 // Release all recorded pointers before RETURN. Do this LAST!
471 if (!DisablePtrHashing)
472 InsertReleaseRecordedInst(exitBlocks[i],
473 externalFuncs.ReleaseOnReturnFunc);