ca5087a02073d84c850fe85c353bd2d562197a71
[oota-llvm.git] / lib / Transforms / Instrumentation / TraceValues.cpp
1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
2 //
3 // Support for inserting LLVM code to print values at basic block and function
4 // exits.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Instrumentation.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"
19 #include <algorithm>
20 #include <sstream>
21 using std::vector;
22 using std::string;
23
24 static cl::opt<bool>
25 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
26                   cl::desc("Disable pointer hashing in the -trace or -tracem "
27                            "passes"));
28
29 static cl::list<string>
30 TraceFuncNames("tracefunc", cl::desc("Only trace specific functions in the "
31                                      "-trace or -tracem passes"),
32                cl::value_desc("function"), cl::Hidden);
33
34 static void TraceValuesAtBBExit(BasicBlock *BB,
35                                 Function *Printf, Function* HashPtrToSeqNum,
36                                 vector<Instruction*> *valuesStoredInFunction);
37
38 // We trace a particular function if no functions to trace were specified
39 // or if the function is in the specified list.
40 // 
41 inline static bool
42 TraceThisFunction(Function &F)
43 {
44   if (TraceFuncNames.empty()) return true;
45
46   return std::find(TraceFuncNames.begin(), TraceFuncNames.end(), F.getName())
47                   != TraceFuncNames.end();
48 }
49
50
51 namespace {
52   struct ExternalFuncs {
53     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
54     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
55     void doInitialization(Module &M); // Add prototypes for external functions
56   };
57   
58   class InsertTraceCode : public FunctionPass {
59   protected:
60     ExternalFuncs externalFuncs;
61   public:
62     
63     // Add a prototype for runtime functions not already in the program.
64     //
65     bool doInitialization(Module &M);
66     
67     //--------------------------------------------------------------------------
68     // Function InsertCodeToTraceValues
69     // 
70     // Inserts tracing code for all live values at basic block and/or function
71     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
72     //
73     bool doit(Function *M);
74
75     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
76
77     // runOnFunction - This method does the work.
78     //
79     bool runOnFunction(Function &F);
80
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.setPreservesCFG();
83     }
84   };
85
86   struct FunctionTracer : public InsertTraceCode {
87     // Ignore basic blocks here...
88     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
89   };
90
91   struct BasicBlockTracer : public InsertTraceCode {
92     // Trace basic blocks here...
93     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
94       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
95                           externalFuncs.HashPtrFunc, &VI);
96     }
97   };
98
99   // Register the passes...
100   RegisterOpt<FunctionTracer>  X("tracem","Insert Function trace code only");
101   RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
102 } // end anonymous namespace
103
104
105 Pass *createTraceValuesPassForFunction() {     // Just trace functions
106   return new FunctionTracer();
107 }
108
109 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
110   return new BasicBlockTracer();
111 }
112
113
114 // Add a prototype for external functions used by the tracing code.
115 //
116 void ExternalFuncs::doInitialization(Module &M) {
117   const Type *SBP = PointerType::get(Type::SByteTy);
118   const FunctionType *MTy =
119     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
120   PrintfFunc = M.getOrInsertFunction("printf", MTy);
121
122   // uint (sbyte*)
123   const FunctionType *hashFuncTy =
124     FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
125   HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
126   
127   // void (sbyte*)
128   const FunctionType *voidSBPFuncTy =
129     FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
130   
131   ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
132   RecordPtrFunc  = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
133   
134   const FunctionType *voidvoidFuncTy =
135     FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
136   
137   PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
138   ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
139                                                voidvoidFuncTy);
140 }
141
142
143 // Add a prototype for external functions used by the tracing code.
144 //
145 bool InsertTraceCode::doInitialization(Module &M) {
146   externalFuncs.doInitialization(M);
147   return false;
148 }
149
150
151 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
152   // Create a constant internal string reference...
153   Constant *Init = ConstantArray::get(str);
154
155   // Create the global variable and record it in the module
156   // The GV will be renamed to a unique name if needed.
157   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, 
158                                           GlobalValue::InternalLinkage, Init,
159                                           "trstr");
160   M->getGlobalList().push_back(GV);
161   return GV;
162 }
163
164
165 // 
166 // Check if this instruction has any uses outside its basic block,
167 // or if it used by either a Call or Return instruction (ditto).
168 // (Values stored to memory within this BB are live at end of BB but are
169 // traced at the store instruction, not where they are computed.)
170 // 
171 static inline bool LiveAtBBExit(const Instruction* I) {
172   const BasicBlock *BB = I->getParent();
173   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
174     if (const Instruction *UI = dyn_cast<Instruction>(*U))
175       if (UI->getParent() != BB || isa<ReturnInst>(UI))
176         return true;
177
178   return false;
179 }
180
181
182 static inline bool TraceThisOpCode(unsigned opCode) {
183   // Explicitly test for opCodes *not* to trace so that any new opcodes will
184   // be traced by default (VoidTy's are already excluded)
185   // 
186   return (opCode  < Instruction::OtherOpsBegin &&
187           opCode != Instruction::Alloca &&
188           opCode != Instruction::PHINode &&
189           opCode != Instruction::Cast);
190 }
191
192
193 // Trace a value computed by an instruction if it is non-void, it is computed
194 // by a real computation, not just a copy (see TraceThisOpCode), and
195 // -- it is a load instruction: we want to check values read from memory
196 // -- or it is live at exit from the basic block (i.e., ignore local temps)
197 // 
198 static bool ShouldTraceValue(const Instruction *I) {
199   return
200     I->getType() != Type::VoidTy &&
201     TraceThisOpCode(I->getOpcode()) &&
202     (isa<LoadInst>(I) || LiveAtBBExit(I));
203 }
204
205 static string getPrintfCodeFor(const Value *V) {
206   if (V == 0) return "";
207   if (V->getType()->isFloatingPoint())
208     return "%g";
209   else if (V->getType() == Type::LabelTy)
210     return "0x%p";
211   else if (isa<PointerType>(V->getType()))
212     return DisablePtrHashing ? "0x%p" : "%d";
213   else if (V->getType()->isIntegral())
214     return "%d";
215   
216   assert(0 && "Illegal value to print out...");
217   return "";
218 }
219
220
221 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
222                             string Message,
223                             Function *Printf, Function* HashPtrToSeqNum) {
224   // Escape Message by replacing all % characters with %% chars.
225   string Tmp;
226   std::swap(Tmp, Message);
227   string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
228   while (I != Tmp.end()) {
229     Message.append(Tmp.begin(), I);
230     Message += "%%";
231     ++I; // Make sure to erase the % as well...
232     Tmp.erase(Tmp.begin(), I);
233     I = std::find(Tmp.begin(), Tmp.end(), '%');
234   }
235   Message += Tmp;
236   Module *Mod = BB->getParent()->getParent();
237
238   // Turn the marker string into a global variable...
239   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
240
241   // Turn the format string into an sbyte *
242   Constant *GEP =ConstantExpr::getGetElementPtr(ConstantPointerRef::get(fmtVal),
243                      vector<Constant*>(2,Constant::getNullValue(Type::LongTy)));
244   
245   // Insert a call to the hash function if this is a pointer value
246   if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
247     const Type *SBP = PointerType::get(Type::SByteTy);
248     if (V->getType() != SBP)     // Cast pointer to be sbyte*
249       V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
250
251     vector<Value*> HashArgs(1, V);
252     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
253   }
254   
255   // Insert the first print instruction to print the string flag:
256   vector<Value*> PrintArgs;
257   PrintArgs.push_back(GEP);
258   if (V) PrintArgs.push_back(V);
259   new CallInst(Printf, PrintArgs, "trace", InsertBefore);
260 }
261                             
262
263 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
264                                    Instruction *InsertBefore,
265                                    const string &Message, Function *Printf,
266                                    Function* HashPtrToSeqNum) {
267   std::ostringstream OutStr;
268   if (V) WriteAsOperand(OutStr, V);
269   InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
270                   Printf, HashPtrToSeqNum);
271 }
272
273 static void 
274 InsertReleaseInst(Value *V, BasicBlock *BB,
275                   Instruction *InsertBefore,
276                   Function* ReleasePtrFunc) {
277   
278   const Type *SBP = PointerType::get(Type::SByteTy);
279   if (V->getType() != SBP)    // Cast pointer to be sbyte*
280     V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
281
282   vector<Value*> releaseArgs(1, V);
283   new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
284 }
285
286 static void 
287 InsertRecordInst(Value *V, BasicBlock *BB,
288                  Instruction *InsertBefore,
289                  Function* RecordPtrFunc) {
290     const Type *SBP = PointerType::get(Type::SByteTy);
291   if (V->getType() != SBP)     // Cast pointer to be sbyte*
292     V = new CastInst(V, SBP, "RP_cast", InsertBefore);
293
294   vector<Value*> releaseArgs(1, V);
295   new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
296 }
297
298 // Look for alloca and free instructions. These are the ptrs to release.
299 // Release the free'd pointers immediately.  Record the alloca'd pointers
300 // to be released on return from the current function.
301 // 
302 static void
303 ReleasePtrSeqNumbers(BasicBlock *BB,
304                      ExternalFuncs& externalFuncs) {
305   
306   for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
307     if (FreeInst *FI = dyn_cast<FreeInst>(II))
308       InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
309     else if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
310       InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
311 }  
312
313
314 // Insert print instructions at the end of basic block BB for each value
315 // computed in BB that is live at the end of BB,
316 // or that is stored to memory in BB.
317 // If the value is stored to memory, we load it back before printing it
318 // We also return all such loaded values in the vector valuesStoredInFunction
319 // for printing at the exit from the function.  (Note that in each invocation
320 // of the function, this will only get the last value stored for each static
321 // store instruction).
322 // 
323 static void TraceValuesAtBBExit(BasicBlock *BB,
324                                 Function *Printf, Function* HashPtrToSeqNum,
325                                 vector<Instruction*> *valuesStoredInFunction) {
326   // Get an iterator to point to the insertion location, which is
327   // just before the terminator instruction.
328   // 
329   TerminatorInst *InsertPos = BB->getTerminator();
330   
331   std::ostringstream OutStr;
332   WriteAsOperand(OutStr, BB, false);
333   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
334                   Printf, HashPtrToSeqNum);
335
336   // Insert a print instruction for each instruction preceding InsertPos.
337   // The print instructions must go before InsertPos, so we use the
338   // instruction *preceding* InsertPos to check when to terminate the loop.
339   // 
340   for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
341     if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
342       // Trace the stored value and address
343       InsertVerbosePrintInst(SI->getOperand(0), BB, InsertPos,
344                              "  (store value) ", Printf, HashPtrToSeqNum);
345       InsertVerbosePrintInst(SI->getOperand(1), BB, InsertPos,
346                              "  (store addr ) ", Printf, HashPtrToSeqNum);
347     }
348     else if (ShouldTraceValue(II))
349       InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
350   }
351 }
352
353 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
354                                                  Function* HashPtrToSeqNum){
355   // Get an iterator to point to the insertion location
356   BasicBlock &BB = F.getEntryNode();
357   Instruction *InsertPos = BB.begin();
358
359   std::ostringstream OutStr;
360   WriteAsOperand(OutStr, &F);
361   InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
362                   Printf, HashPtrToSeqNum);
363
364   // Now print all the incoming arguments
365   unsigned ArgNo = 0;
366   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
367     InsertVerbosePrintInst(I, &BB, InsertPos,
368                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
369                            HashPtrToSeqNum);
370   }
371 }
372
373
374 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
375                                                 Function *Printf,
376                                                 Function* HashPtrToSeqNum) {
377   // Get an iterator to point to the insertion location
378   ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
379   
380   std::ostringstream OutStr;
381   WriteAsOperand(OutStr, BB->getParent(), true);
382   InsertPrintInst(0, BB, Ret, "LEAVING  FUNCTION: " + OutStr.str(),
383                   Printf, HashPtrToSeqNum);
384   
385   // print the return value, if any
386   if (BB->getParent()->getReturnType() != Type::VoidTy)
387     InsertPrintInst(Ret->getReturnValue(), BB, Ret, "  Returning: ",
388                     Printf, HashPtrToSeqNum);
389 }
390
391
392 bool InsertTraceCode::runOnFunction(Function &F) {
393   if (!TraceThisFunction(F))
394     return false;
395   
396   vector<Instruction*> valuesStoredInFunction;
397   vector<BasicBlock*>  exitBlocks;
398
399   // Insert code to trace values at function entry
400   InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
401                                 externalFuncs.HashPtrFunc);
402   
403   // Push a pointer set for recording alloca'd pointers at entry.
404   if (!DisablePtrHashing)
405     new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
406                  F.getEntryNode().begin());
407
408   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
409     if (isa<ReturnInst>(BB->getTerminator()))
410       exitBlocks.push_back(BB); // record this as an exit block
411
412     // Insert trace code if this basic block is interesting...
413     handleBasicBlock(BB, valuesStoredInFunction);
414
415     if (!DisablePtrHashing)          // release seq. numbers on free/ret
416       ReleasePtrSeqNumbers(BB, externalFuncs);
417   }
418   
419   for (unsigned i=0; i != exitBlocks.size(); ++i)
420     {
421       // Insert code to trace values at function exit
422       InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
423                                    externalFuncs.HashPtrFunc);
424       
425       // Release all recorded pointers before RETURN.  Do this LAST!
426       if (!DisablePtrHashing)
427         new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
428                      exitBlocks[i]->getTerminator());
429     }
430   
431   return true;
432 }