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