changed function numbering
[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/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"
22 #include <algorithm>
23 #include <sstream>
24 using std::vector;
25 using std::string;
26
27 static cl::Flag DisablePtrHashing("tracedisablehashdisable",
28                                   "Disable pointer hashing", cl::NoFlags);
29
30 static cl::StringList TraceFuncName ("tracefunc", "trace only specific funct"
31                                      "ions", cl::NoFlags);
32
33
34 // We trace a particular function if no functions to trace were specified
35 // or if the function is in the specified list.
36 // 
37 inline bool
38 TraceThisFunction(Function* func)
39 {
40   if (TraceFuncName.getNumOccurances() == 0)
41     return true;
42
43   return std::find(TraceFuncName.begin(), TraceFuncName.end(), func->getName())
44                   != TraceFuncName.end();
45 }
46
47
48 namespace {
49   struct ExternalFuncs {
50     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
51     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
52     void doInitialization(Module &M); // Add prototypes for external functions
53   };
54   
55   class InsertTraceCode : public FunctionPass {
56     bool TraceBasicBlockExits, TraceFunctionExits;
57     ExternalFuncs externalFuncs;
58   public:
59     InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
60       : TraceBasicBlockExits(traceBasicBlockExits), 
61         TraceFunctionExits(traceFunctionExits) {}
62
63     const char *getPassName() const { return "Trace Code Insertion"; }
64     
65     // Add a prototype for runtime functions not already in the program.
66     //
67     bool doInitialization(Module &M);
68     
69     //--------------------------------------------------------------------------
70     // Function InsertCodeToTraceValues
71     // 
72     // Inserts tracing code for all live values at basic block and/or function
73     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
74     //
75     static bool doit(Function *M, bool traceBasicBlockExits,
76                      bool traceFunctionExits, ExternalFuncs& externalFuncs);
77
78     // runOnFunction - This method does the work.
79     //
80     bool runOnFunction(Function &F) {
81       return doit(&F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
82     }
83
84     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.preservesCFG();
86     }
87   };
88 } // end anonymous namespace
89
90
91 Pass *createTraceValuesPassForFunction() {     // Just trace functions
92   return new InsertTraceCode(false, true);
93 }
94
95 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
96   return new InsertTraceCode(true, true);
97 }
98
99 // Add a prototype for external functions used by the tracing code.
100 //
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);
106
107   // uint (sbyte*)
108   const FunctionType *hashFuncTy =
109     FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
110   HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
111   
112   // void (sbyte*)
113   const FunctionType *voidSBPFuncTy =
114     FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
115   
116   ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
117   RecordPtrFunc  = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
118   
119   const FunctionType *voidvoidFuncTy =
120     FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
121   
122   PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
123   ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
124                                                voidvoidFuncTy);
125 }
126
127
128 // Add a prototype for external functions used by the tracing code.
129 //
130 bool InsertTraceCode::doInitialization(Module &M) {
131   externalFuncs.doInitialization(M);
132   return false;
133 }
134
135
136 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
137   // Create a constant internal string reference...
138   Constant *Init = ConstantArray::get(str);
139
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,
143                                           "trstr");
144   M->getGlobalList().push_back(GV);
145   return GV;
146 }
147
148
149 // 
150 // Check if this instruction has any uses outside its basic block,
151 // or if it used by either a Call or Return instruction.
152 // 
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))
158         return true;
159
160   return false;
161 }
162
163
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)
167   // 
168   return (opCode  < Instruction::FirstOtherOp &&
169           opCode != Instruction::Alloca &&
170           opCode != Instruction::PHINode &&
171           opCode != Instruction::Cast);
172 }
173
174
175 static bool ShouldTraceValue(const Instruction *I) {
176   return
177     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
178     TraceThisOpCode(I->getOpcode());
179 }
180
181 static string getPrintfCodeFor(const Value *V) {
182   if (V == 0) return "";
183   if (V->getType()->isFloatingPoint())
184     return "%g";
185   else if (V->getType() == Type::LabelTy)
186     return "0x%p";
187   else if (isa<PointerType>(V->getType()))
188     return DisablePtrHashing ? "0x%p" : "%d";
189   else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
190     return "%d";
191   
192   assert(0 && "Illegal value to print out...");
193   return "";
194 }
195
196
197 static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
198                             string Message,
199                             Function *Printf, Function* HashPtrToSeqNum) {
200   // Escape Message by replacing all % characters with %% chars.
201   unsigned Offset = 0;
202   while ((Offset = Message.find('%', Offset)) != string::npos) {
203     Message.replace(Offset, 1, "%%");
204     Offset += 2;  // Skip over the new %'s
205   }
206
207   Module *Mod = BB->getParent()->getParent();
208
209   // Turn the marker string into a global variable...
210   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
211
212   // Turn the format string into an sbyte *
213   Instruction *GEP = 
214     new GetElementPtrInst(fmtVal,
215                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
216                           "trstr");
217   BBI = ++BB->getInstList().insert(BBI, GEP);
218   
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);
225       V = I;
226     }
227
228     vector<Value*> HashArgs(1, V);
229     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
230     BBI = ++BB->getInstList().insert(BBI, cast<Instruction>(V));
231   }
232   
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);
239 }
240                             
241
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);
250 }
251
252 static void 
253 InsertReleaseInst(Value *V, BasicBlock *BB,
254                   BasicBlock::iterator &BBI,
255                   Function* ReleasePtrFunc) {
256   
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);
261     V = I;
262   }
263   vector<Value*> releaseArgs(1, V);
264   Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
265   BBI = ++BB->getInstList().insert(BBI, I);
266 }
267
268 static void 
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);
276     V = I;
277   }
278   vector<Value*> releaseArgs(1, V);
279   Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
280   BBI = ++BB->getInstList().insert(BBI, I);
281 }
282
283 static void
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,
289                                                    vector<Value*>()));
290 }
291
292 static void 
293 InsertReleaseRecordedInst(BasicBlock *BB,
294                           Function* ReleaseOnReturnFunc) {
295   BasicBlock::iterator BBI = BB->end()--;
296   BBI = ++BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
297                                                      vector<Value*>()));
298 }
299
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.
303 // 
304 static void
305 ReleasePtrSeqNumbers(BasicBlock *BB,
306                      ExternalFuncs& externalFuncs) {
307   
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))
312       {
313         BasicBlock::iterator nextI = ++II;
314         InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);     
315         II = --nextI;
316       }
317   }
318 }  
319
320
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.
331 // 
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.
337   // 
338   BasicBlock::iterator InsertPos = BB->end()--;
339   assert(BB->back().isTerminator());
340   
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.
346   // 
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
353         }
354
355   std::ostringstream OutStr;
356   WriteAsOperand(OutStr, BB, false);
357   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
358                   Printf, HashPtrToSeqNum);
359
360   // Insert a print instruction for each value.
361   // 
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);
370     }
371     if (ShouldTraceValue(II))
372       InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
373   }
374 }
375
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();
381
382   std::ostringstream OutStr;
383   WriteAsOperand(OutStr, M, true);
384   InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
385                   Printf, HashPtrToSeqNum);
386
387   // Now print all the incoming arguments
388   unsigned ArgNo = 0;
389   for (Function::aiterator I = M->abegin(), E = M->aend(); I != E; ++I,++ArgNo){
390     InsertVerbosePrintInst(I, &BB, BBI,
391                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
392                            HashPtrToSeqNum);
393   }
394 }
395
396
397 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
398                                                 Function *Printf,
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());
403   
404   std::ostringstream OutStr;
405   WriteAsOperand(OutStr, BB->getParent(), true);
406   InsertPrintInst(0, BB, BBI, "LEAVING  FUNCTION: " + OutStr.str(),
407                   Printf, HashPtrToSeqNum);
408   
409   // print the return value, if any
410   if (BB->getParent()->getReturnType() != Type::VoidTy)
411     InsertPrintInst(Ret.getReturnValue(), BB, BBI, "  Returning: ",
412                     Printf, HashPtrToSeqNum);
413 }
414
415
416 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
417                            bool traceFunctionEvents,
418                            ExternalFuncs& externalFuncs) {
419   if (!traceBasicBlockExits && !traceFunctionEvents)
420     return false;
421
422   if (!TraceThisFunction(M))
423     return false;
424   
425   vector<Instruction*> valuesStoredInFunction;
426   vector<BasicBlock*>  exitBlocks;
427
428   // Insert code to trace values at function entry
429   if (traceFunctionEvents)
430     InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
431                                   externalFuncs.HashPtrFunc);
432   
433   // Push a pointer set for recording alloca'd pointers at entry.
434   if (!DisablePtrHashing)
435     InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
436   
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
440     
441     if (traceBasicBlockExits)
442       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
443                           externalFuncs.HashPtrFunc, &valuesStoredInFunction);
444     
445     if (!DisablePtrHashing)          // release seq. numbers on free/ret
446       ReleasePtrSeqNumbers(BB, externalFuncs);
447   }
448   
449   for (unsigned i=0; i < exitBlocks.size(); ++i)
450     {
451       // Insert code to trace values at function exit
452       if (traceFunctionEvents)
453         InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
454                                      externalFuncs.HashPtrFunc);
455       
456       // Release all recorded pointers before RETURN.  Do this LAST!
457       if (!DisablePtrHashing)
458         InsertReleaseRecordedInst(exitBlocks[i],
459                                   externalFuncs.ReleaseOnReturnFunc);
460     }
461   
462   return true;
463 }