Added functionality to instrmentation pass
[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.
168 // 
169 static inline bool LiveAtBBExit(const Instruction* I) {
170   const BasicBlock *BB = I->getParent();
171   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
172     if (const Instruction *UI = dyn_cast<Instruction>(*U))
173       if (UI->getParent() != BB || isa<ReturnInst>(UI))
174         return true;
175
176   return false;
177 }
178
179
180 static inline bool TraceThisOpCode(unsigned opCode) {
181   // Explicitly test for opCodes *not* to trace so that any new opcodes will
182   // be traced by default (VoidTy's are already excluded)
183   // 
184   return (opCode  < Instruction::OtherOpsBegin &&
185           opCode != Instruction::Alloca &&
186           opCode != Instruction::PHINode &&
187           opCode != Instruction::Cast);
188 }
189
190
191 static bool ShouldTraceValue(const Instruction *I) {
192   return
193     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
194     TraceThisOpCode(I->getOpcode());
195 }
196
197 static string getPrintfCodeFor(const Value *V) {
198   if (V == 0) return "";
199   if (V->getType()->isFloatingPoint())
200     return "%g";
201   else if (V->getType() == Type::LabelTy)
202     return "0x%p";
203   else if (isa<PointerType>(V->getType()))
204     return DisablePtrHashing ? "0x%p" : "%d";
205   else if (V->getType()->isIntegral())
206     return "%d";
207   
208   assert(0 && "Illegal value to print out...");
209   return "";
210 }
211
212
213 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
214                             string Message,
215                             Function *Printf, Function* HashPtrToSeqNum) {
216   // Escape Message by replacing all % characters with %% chars.
217   string Tmp;
218   std::swap(Tmp, Message);
219   string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
220   while (I != Tmp.end()) {
221     Message.append(Tmp.begin(), I);
222     Message += "%%";
223     ++I; // Make sure to erase the % as well...
224     Tmp.erase(Tmp.begin(), I);
225     I = std::find(Tmp.begin(), Tmp.end(), '%');
226   }
227   Message += Tmp;
228   Module *Mod = BB->getParent()->getParent();
229
230   // Turn the marker string into a global variable...
231   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
232
233   // Turn the format string into an sbyte *
234   Constant *GEP =ConstantExpr::getGetElementPtr(ConstantPointerRef::get(fmtVal),
235                      vector<Constant*>(2,Constant::getNullValue(Type::LongTy)));
236   
237   // Insert a call to the hash function if this is a pointer value
238   if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
239     const Type *SBP = PointerType::get(Type::SByteTy);
240     if (V->getType() != SBP)     // Cast pointer to be sbyte*
241       V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
242
243     vector<Value*> HashArgs(1, V);
244     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
245   }
246   
247   // Insert the first print instruction to print the string flag:
248   vector<Value*> PrintArgs;
249   PrintArgs.push_back(GEP);
250   if (V) PrintArgs.push_back(V);
251   new CallInst(Printf, PrintArgs, "trace", InsertBefore);
252 }
253                             
254
255 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
256                                    Instruction *InsertBefore,
257                                    const string &Message, Function *Printf,
258                                    Function* HashPtrToSeqNum) {
259   std::ostringstream OutStr;
260   if (V) WriteAsOperand(OutStr, V);
261   InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
262                   Printf, HashPtrToSeqNum);
263 }
264
265 static void 
266 InsertReleaseInst(Value *V, BasicBlock *BB,
267                   Instruction *InsertBefore,
268                   Function* ReleasePtrFunc) {
269   
270   const Type *SBP = PointerType::get(Type::SByteTy);
271   if (V->getType() != SBP)    // Cast pointer to be sbyte*
272     V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
273
274   vector<Value*> releaseArgs(1, V);
275   new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
276 }
277
278 static void 
279 InsertRecordInst(Value *V, BasicBlock *BB,
280                  Instruction *InsertBefore,
281                  Function* RecordPtrFunc) {
282     const Type *SBP = PointerType::get(Type::SByteTy);
283   if (V->getType() != SBP)     // Cast pointer to be sbyte*
284     V = new CastInst(V, SBP, "RP_cast", InsertBefore);
285
286   vector<Value*> releaseArgs(1, V);
287   new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
288 }
289
290 // Look for alloca and free instructions. These are the ptrs to release.
291 // Release the free'd pointers immediately.  Record the alloca'd pointers
292 // to be released on return from the current function.
293 // 
294 static void
295 ReleasePtrSeqNumbers(BasicBlock *BB,
296                      ExternalFuncs& externalFuncs) {
297   
298   for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
299     if (FreeInst *FI = dyn_cast<FreeInst>(II))
300       InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
301     else if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
302       InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
303 }  
304
305
306 // Insert print instructions at the end of basic block BB for each value
307 // computed in BB that is live at the end of BB,
308 // or that is stored to memory in BB.
309 // If the value is stored to memory, we load it back before printing it
310 // We also return all such loaded values in the vector valuesStoredInFunction
311 // for printing at the exit from the function.  (Note that in each invocation
312 // of the function, this will only get the last value stored for each static
313 // store instruction).
314 // 
315 static void TraceValuesAtBBExit(BasicBlock *BB,
316                                 Function *Printf, Function* HashPtrToSeqNum,
317                                 vector<Instruction*> *valuesStoredInFunction) {
318   // Get an iterator to point to the insertion location, which is
319   // just before the terminator instruction.
320   // 
321   TerminatorInst *InsertPos = BB->getTerminator();
322   
323   std::ostringstream OutStr;
324   WriteAsOperand(OutStr, BB, false);
325   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
326                   Printf, HashPtrToSeqNum);
327
328   // Insert a print instruction for each instruction preceding InsertPos.
329   // The print instructions must go before InsertPos, so we use the
330   // instruction *preceding* InsertPos to check when to terminate the loop.
331   // 
332   for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
333     if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
334       assert(valuesStoredInFunction &&
335              "Should not be printing a store instruction at function exit");
336       LoadInst *LI = new LoadInst(SI->getPointerOperand(), "reload." +
337                                   SI->getPointerOperand()->getName(),
338                                   InsertPos);
339       valuesStoredInFunction->push_back(LI);
340     }
341     if (ShouldTraceValue(II))
342       InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
343   }
344 }
345
346 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
347                                                  Function* HashPtrToSeqNum){
348   // Get an iterator to point to the insertion location
349   BasicBlock &BB = F.getEntryNode();
350   Instruction *InsertPos = BB.begin();
351
352   std::ostringstream OutStr;
353   WriteAsOperand(OutStr, &F);
354   InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
355                   Printf, HashPtrToSeqNum);
356
357   // Now print all the incoming arguments
358   unsigned ArgNo = 0;
359   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
360     InsertVerbosePrintInst(I, &BB, InsertPos,
361                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
362                            HashPtrToSeqNum);
363   }
364 }
365
366
367 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
368                                                 Function *Printf,
369                                                 Function* HashPtrToSeqNum) {
370   // Get an iterator to point to the insertion location
371   ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
372   
373   std::ostringstream OutStr;
374   WriteAsOperand(OutStr, BB->getParent(), true);
375   InsertPrintInst(0, BB, Ret, "LEAVING  FUNCTION: " + OutStr.str(),
376                   Printf, HashPtrToSeqNum);
377   
378   // print the return value, if any
379   if (BB->getParent()->getReturnType() != Type::VoidTy)
380     InsertPrintInst(Ret->getReturnValue(), BB, Ret, "  Returning: ",
381                     Printf, HashPtrToSeqNum);
382 }
383
384
385 bool InsertTraceCode::runOnFunction(Function &F) {
386   if (!TraceThisFunction(F))
387     return false;
388   
389   vector<Instruction*> valuesStoredInFunction;
390   vector<BasicBlock*>  exitBlocks;
391
392   // Insert code to trace values at function entry
393   InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
394                                 externalFuncs.HashPtrFunc);
395   
396   // Push a pointer set for recording alloca'd pointers at entry.
397   if (!DisablePtrHashing)
398     new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
399                  F.getEntryNode().begin());
400
401   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
402     if (isa<ReturnInst>(BB->getTerminator()))
403       exitBlocks.push_back(BB); // record this as an exit block
404
405     // Insert trace code if this basic block is interesting...
406     handleBasicBlock(BB, valuesStoredInFunction);
407
408     if (!DisablePtrHashing)          // release seq. numbers on free/ret
409       ReleasePtrSeqNumbers(BB, externalFuncs);
410   }
411   
412   for (unsigned i=0; i != exitBlocks.size(); ++i)
413     {
414       // Insert code to trace values at function exit
415       InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
416                                    externalFuncs.HashPtrFunc);
417       
418       // Release all recorded pointers before RETURN.  Do this LAST!
419       if (!DisablePtrHashing)
420         new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
421                      exitBlocks[i]->getTerminator());
422     }
423   
424   return true;
425 }