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