Hash pointer values to a sequence number to get identical results from
[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 <sstream>
23 using std::vector;
24 using std::string;
25
26
27 enum TraceHashPtrOpt {
28    HashToSeqNum, NoHash
29 };
30
31 static cl::Enum<enum TraceHashPtrOpt> TraceHashPtrs("tracehash", cl::NoFlags,
32   "Hash pointer values when tracing",
33   clEnumValN(HashToSeqNum, "on", "Hash pointers to sequence number"),
34   clEnumValN(NoHash ,      "off","Disable hashing of pointers"), 0);
35
36
37 static cl::StringList TraceFuncName ("tracefunc", "trace these functions", cl::NoFlags);
38
39
40 // We trace a particular function if no functions to trace were specified
41 // or if the function is in the specified list.
42 // 
43 inline bool
44 TraceThisFunction(Function* func)
45 {
46   if (TraceFuncName.getNumOccurances() == 0)
47     return true;
48   
49   for (std::vector<std::string>::const_iterator SI=TraceFuncName.begin(),
50          SE=TraceFuncName.end(); SI != SE; ++SI)
51     if (func->getName() == *SI)
52       return true;
53   
54   return false;
55 }
56
57
58 namespace {
59   class ExternalFuncs {
60   public:
61     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
62     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
63     void doInitialization(Module *M); // Add prototypes for external functions
64   };
65   
66   class InsertTraceCode : public FunctionPass {
67     bool TraceBasicBlockExits, TraceFunctionExits;
68     ExternalFuncs externalFuncs;
69   public:
70     InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
71       : TraceBasicBlockExits(traceBasicBlockExits), 
72         TraceFunctionExits(traceFunctionExits) {}
73
74     const char *getPassName() const { return "Trace Code Insertion"; }
75     
76     // Add a prototype for runtime functions not already in the program.
77     //
78     bool doInitialization(Module *M);
79     
80     //--------------------------------------------------------------------------
81     // Function InsertCodeToTraceValues
82     // 
83     // Inserts tracing code for all live values at basic block and/or function
84     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
85     //
86     static bool doit(Function *M, bool traceBasicBlockExits,
87                      bool traceFunctionExits, ExternalFuncs& externalFuncs);
88
89     // runOnFunction - This method does the work.
90     //
91     bool runOnFunction(Function *F) {
92       return doit(F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
93     }
94
95     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96       AU.preservesCFG();
97     }
98   };
99 } // end anonymous namespace
100
101
102 Pass *createTraceValuesPassForFunction() {     // Just trace functions
103   return new InsertTraceCode(false, true);
104 }
105
106 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
107   return new InsertTraceCode(true, true);
108 }
109
110 // Add a prototype for external functions used by the tracing code.
111 //
112 void ExternalFuncs::doInitialization(Module *M) {
113   const Type *SBP = PointerType::get(Type::SByteTy);
114   const FunctionType *MTy =
115     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
116   PrintfFunc = M->getOrInsertFunction("printf", MTy);
117   
118   // Use varargs functions with no args instead of func(sbyte*) so that
119   // we don't have to generate cast instructions below :-)
120   // 
121   const FunctionType *hashFuncTy =
122     FunctionType::get(Type::UIntTy, vector<const Type*>(), true);
123   HashPtrFunc = M->getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
124   
125   // varargs again, same reason.
126   const FunctionType *voidVAFuncTy =
127     FunctionType::get(Type::VoidTy, vector<const Type*>(), true);
128   
129   ReleasePtrFunc =M->getOrInsertFunction("ReleasePointerSeqNum", voidVAFuncTy);
130   RecordPtrFunc = M->getOrInsertFunction("RecordPointer", voidVAFuncTy);
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::FirstOtherOp &&
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 (TraceHashPtrs == NoHash)? "0x%p" : "%d";
202   else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
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, BasicBlock::iterator &BBI,
211                             string Message,
212                             Function *Printf, Function* HashPtrToSeqNum) {
213   // Escape Message by replacing all % characters with %% chars.
214   unsigned Offset = 0;
215   while ((Offset = Message.find('%', Offset)) != string::npos) {
216     Message.replace(Offset, 1, "%%");
217     Offset += 2;  // Skip over the new %'s
218   }
219
220   Module *Mod = BB->getParent()->getParent();
221
222   // Turn the marker string into a global variable...
223   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
224
225   // Turn the format string into an sbyte *
226   Instruction *GEP = 
227     new GetElementPtrInst(fmtVal,
228                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
229                           "trstr");
230   BBI = BB->getInstList().insert(BBI, GEP)+1;
231   
232   // Insert a call to the hash function if this is a pointer value
233   if (V && isa<PointerType>(V->getType()) && TraceHashPtrs == HashToSeqNum) {
234     vector<Value*> HashArgs;
235     HashArgs.push_back(V);
236     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
237     BBI = BB->getInstList().insert(BBI, cast<Instruction>(V))+1;
238   }
239   
240   // Insert the first print instruction to print the string flag:
241   vector<Value*> PrintArgs;
242   PrintArgs.push_back(GEP);
243   if (V) PrintArgs.push_back(V);
244   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
245   BBI = BB->getInstList().insert(BBI, I)+1;
246 }
247                             
248
249 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
250                                    BasicBlock::iterator &BBI,
251                                    const string &Message, Function *Printf,
252                                    Function* HashPtrToSeqNum) {
253   std::ostringstream OutStr;
254   if (V) WriteAsOperand(OutStr, V);
255   InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ",
256                   Printf, HashPtrToSeqNum);
257 }
258
259 static void 
260 InsertReleaseInst(Value *V, BasicBlock *BB,
261                   BasicBlock::iterator &BBI,
262                   Function* ReleasePtrFunc) {
263   vector<Value*> releaseArgs;
264   releaseArgs.push_back(V);
265   Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
266   BBI = BB->getInstList().insert(BBI, I)+1;
267 }
268
269 static void 
270 InsertRecordInst(Value *V, BasicBlock *BB,
271                  BasicBlock::iterator &BBI,
272                  Function* RecordPtrFunc) {
273   vector<Value*> releaseArgs;
274   releaseArgs.push_back(V);
275   Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
276   BBI = BB->getInstList().insert(BBI, I)+1;
277 }
278
279 static void
280 InsertPushOnEntryFunc(Function *M,
281                       Function* PushOnEntryFunc) {
282   // Get an iterator to point to the insertion location
283   BasicBlock *BB = M->getEntryNode();
284   BB->getInstList().insert(BB->begin(), new CallInst(PushOnEntryFunc,
285                                                      vector<Value*> ()));
286 }
287
288 static void 
289 InsertReleaseRecordedInst(BasicBlock *BB,
290                           Function* ReleaseOnReturnFunc) {
291   BasicBlock::iterator BBI = BB->end()-1;
292   BBI = 1 + BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
293                                                        vector<Value*>()));
294 }
295
296 // Look for alloca and free instructions. These are the ptrs to release.
297 // Release the free'd pointers immediately.  Record the alloca'd pointers
298 // to be released on return from the current function.
299 // 
300 static void
301 ReleasePtrSeqNumbers(BasicBlock *BB,
302                      ExternalFuncs& externalFuncs) {
303   
304   for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
305     if (FreeInst *FI = dyn_cast<FreeInst>(*II))
306       InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
307     else if (AllocaInst *AI = dyn_cast<AllocaInst>(*II))
308       {
309         BasicBlock::iterator nextI = II+1;
310         InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);     
311         II = nextI - 1;
312       }
313   }
314 }  
315
316
317 // Insert print instructions at the end of the basic block *bb
318 // for each value in valueVec[] that is live at the end of that basic block,
319 // or that is stored to memory in this basic block.
320 // If the value is stored to memory, we load it back before printing
321 // We also return all such loaded values in the vector valuesStoredInFunction
322 // for printing at the exit from the function.  (Note that in each invocation
323 // of the function, this will only get the last value stored for each static
324 // store instruction).
325 // *bb must be the block in which the value is computed;
326 // this is not checked here.
327 // 
328 static void TraceValuesAtBBExit(BasicBlock *BB,
329                                 Function *Printf, Function* HashPtrToSeqNum,
330                                 vector<Instruction*> *valuesStoredInFunction) {
331   // Get an iterator to point to the insertion location, which is
332   // just before the terminator instruction.
333   // 
334   BasicBlock::iterator InsertPos = BB->end()-1;
335   assert((*InsertPos)->isTerminator());
336   
337   // If the terminator is a conditional branch, insert the trace code just
338   // before the instruction that computes the branch condition (just to
339   // avoid putting a call between the CC-setting instruction and the branch).
340   // Use laterInstrSet to mark instructions that come after the setCC instr
341   // because those cannot be traced at the location we choose.
342   // 
343   Instruction *SetCC = 0;
344   if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
345     if (!Branch->isUnconditional())
346       if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
347         if (I->getParent() == BB) {
348           SetCC = I;
349           while (*InsertPos != SetCC)
350             --InsertPos;        // Back up until we can insert before the setcc
351         }
352
353   // Copy all of the instructions into a vector to avoid problems with Setcc
354   const vector<Instruction*> Insts(BB->begin(), InsertPos);
355
356   std::ostringstream OutStr;
357   WriteAsOperand(OutStr, BB, false);
358   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
359                   Printf, HashPtrToSeqNum);
360
361   // Insert a print instruction for each value.
362   // 
363   for (vector<Instruction*>::const_iterator II = Insts.begin(),
364          IE = Insts.end(); II != IE; ++II) {
365     Instruction *I = *II;
366     if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
367       assert(valuesStoredInFunction &&
368              "Should not be printing a store instruction at function exit");
369       LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
370                                   "reload");
371       InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
372       valuesStoredInFunction->push_back(LI);
373     }
374     if (ShouldTraceValue(I))
375       InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
376   }
377 }
378
379 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
380                                                  Function* HashPtrToSeqNum){
381   // Get an iterator to point to the insertion location
382   BasicBlock *BB = M->getEntryNode();
383   BasicBlock::iterator BBI = BB->begin();
384
385   std::ostringstream OutStr;
386   WriteAsOperand(OutStr, M, true);
387   InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
388                   Printf, HashPtrToSeqNum);
389
390   // Now print all the incoming arguments
391   const Function::ArgumentListType &argList = M->getArgumentList();
392   unsigned ArgNo = 0;
393   for (Function::ArgumentListType::const_iterator
394          I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
395     InsertVerbosePrintInst((Value*)*I, BB, BBI,
396                            "  Arg #" + utostr(ArgNo), Printf, HashPtrToSeqNum);
397   }
398 }
399
400
401 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
402                                                 Function *Printf,
403                                                 Function* HashPtrToSeqNum) {
404   // Get an iterator to point to the insertion location
405   BasicBlock::iterator BBI = BB->end()-1;
406   ReturnInst *Ret = cast<ReturnInst>(*BBI);
407   
408   std::ostringstream OutStr;
409   WriteAsOperand(OutStr, BB->getParent(), true);
410   InsertPrintInst(0, BB, BBI, "LEAVING  FUNCTION: " + OutStr.str(),
411                   Printf, HashPtrToSeqNum);
412   
413   // print the return value, if any
414   if (BB->getParent()->getReturnType() != Type::VoidTy)
415     InsertPrintInst(Ret->getReturnValue(), BB, BBI, "  Returning: ",
416                     Printf, HashPtrToSeqNum);
417 }
418
419
420 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
421                            bool traceFunctionEvents,
422                            ExternalFuncs& externalFuncs) {
423   if (!traceBasicBlockExits && !traceFunctionEvents)
424     return false;
425
426   if (!TraceThisFunction(M))
427     return false;
428   
429   vector<Instruction*> valuesStoredInFunction;
430   vector<BasicBlock*>  exitBlocks;
431
432   // Insert code to trace values at function entry
433   if (traceFunctionEvents)
434     InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
435                                   externalFuncs.HashPtrFunc);
436   
437   // Push a pointer set for recording alloca'd pointers at entry.
438   if (TraceHashPtrs == HashToSeqNum)
439     InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
440   
441   for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
442     BasicBlock *BB = *BI;
443     if (isa<ReturnInst>(BB->getTerminator()))
444       exitBlocks.push_back(BB); // record this as an exit block
445     
446     if (traceBasicBlockExits)
447       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
448                           externalFuncs.HashPtrFunc, &valuesStoredInFunction);
449     
450     if (TraceHashPtrs == HashToSeqNum)  // release seq. numbers on free/ret
451       ReleasePtrSeqNumbers(BB, externalFuncs);
452   }
453   
454   for (unsigned i=0; i < exitBlocks.size(); ++i)
455     {
456       // Insert code to trace values at function exit
457       if (traceFunctionEvents)
458         InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
459                                      externalFuncs.HashPtrFunc);
460       
461       // Release all recorded pointers before RETURN.  Do this LAST!
462       if (TraceHashPtrs == HashToSeqNum)
463         InsertReleaseRecordedInst(exitBlocks[i],
464                                   externalFuncs.ReleaseOnReturnFunc);
465     }
466   
467   return true;
468 }