9838ea101ac499989728152cde2d770764753158
[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 "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/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 /// Just trace functions
112 FunctionPass *llvm::createTraceValuesPassForFunction() {
113   return new FunctionTracer();
114 }
115
116 /// Trace BB's and functions
117 FunctionPass *llvm::createTraceValuesPassForBasicBlocks() {
118   return new BasicBlockTracer();
119 }
120
121 // Add a prototype for external functions used by the tracing code and require
122 // the trace library for this module.
123 //
124 void ExternalFuncs::doInitialization(Module &M) {
125   M.addLibrary("trace");
126   const Type *SBP = PointerType::get(Type::SByteTy);
127   const FunctionType *MTy =
128     FunctionType::get(Type::IntTy, std::vector<const Type*>(1, SBP), true);
129   PrintfFunc = M.getOrInsertFunction("printf", MTy);
130
131   // uint (sbyte*)
132   HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", Type::UIntTy, SBP,
133                                       0);
134
135   // void (sbyte*)
136   ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum",
137                                          Type::VoidTy, SBP, 0);
138   RecordPtrFunc  = M.getOrInsertFunction("RecordPointer",
139                                          Type::VoidTy, SBP, 0);
140
141   PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", Type::VoidTy, 0);
142   ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
143                                               Type::VoidTy, 0);
144 }
145
146
147 // Add a prototype for external functions used by the tracing code.
148 //
149 bool InsertTraceCode::doInitialization(Module &M) {
150   externalFuncs.doInitialization(M);
151   return false;
152 }
153
154
155 static inline GlobalVariable *getStringRef(Module *M, const std::string &str) {
156   // Create a constant internal string reference...
157   Constant *Init = ConstantArray::get(str);
158
159   // Create the global variable and record it in the module
160   // The GV will be renamed to a unique name if needed.
161   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
162                                           GlobalValue::InternalLinkage, Init,
163                                           "trstr");
164   M->getGlobalList().push_back(GV);
165   return GV;
166 }
167
168
169 //
170 // Check if this instruction has any uses outside its basic block,
171 // or if it used by either a Call or Return instruction (ditto).
172 // (Values stored to memory within this BB are live at end of BB but are
173 // traced at the store instruction, not where they are computed.)
174 //
175 static inline bool LiveAtBBExit(const Instruction* I) {
176   const BasicBlock *BB = I->getParent();
177   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
178     if (const Instruction *UI = dyn_cast<Instruction>(*U))
179       if (UI->getParent() != BB || isa<ReturnInst>(UI))
180         return true;
181
182   return false;
183 }
184
185
186 static inline bool TraceThisOpCode(unsigned opCode) {
187   // Explicitly test for opCodes *not* to trace so that any new opcodes will
188   // be traced by default (VoidTy's are already excluded)
189   //
190   return (opCode  < Instruction::OtherOpsBegin &&
191           opCode != Instruction::Alloca &&
192           opCode != Instruction::PHI &&
193           opCode != Instruction::Cast);
194 }
195
196
197 // Trace a value computed by an instruction if it is non-void, it is computed
198 // by a real computation, not just a copy (see TraceThisOpCode), and
199 // -- it is a load instruction: we want to check values read from memory
200 // -- or it is live at exit from the basic block (i.e., ignore local temps)
201 //
202 static bool ShouldTraceValue(const Instruction *I) {
203   return
204     I->getType() != Type::VoidTy &&
205     TraceThisOpCode(I->getOpcode()) &&
206     (isa<LoadInst>(I) || LiveAtBBExit(I));
207 }
208
209 static std::string getPrintfCodeFor(const Value *V) {
210   if (V == 0) return "";
211   if (V->getType()->isFloatingPoint())
212     return "%g";
213   else if (V->getType() == Type::LabelTy)
214     return "0x%p";
215   else if (isa<PointerType>(V->getType()))
216     return DisablePtrHashing ? "0x%p" : "%d";
217   else if (V->getType()->isIntegral())
218     return "%d";
219
220   assert(0 && "Illegal value to print out...");
221   return "";
222 }
223
224
225 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
226                             std::string Message,
227                             Function *Printf, Function* HashPtrToSeqNum) {
228   // Escape Message by replacing all % characters with %% chars.
229   std::string Tmp;
230   std::swap(Tmp, Message);
231   std::string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
232   while (I != Tmp.end()) {
233     Message.append(Tmp.begin(), I);
234     Message += "%%";
235     ++I; // Make sure to erase the % as well...
236     Tmp.erase(Tmp.begin(), I);
237     I = std::find(Tmp.begin(), Tmp.end(), '%');
238   }
239   Message += Tmp;
240   Module *Mod = BB->getParent()->getParent();
241
242   // Turn the marker string into a global variable...
243   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
244
245   // Turn the format string into an sbyte *
246   Constant *GEP=ConstantExpr::getGetElementPtr(fmtVal,
247                 std::vector<Constant*>(2,Constant::getNullValue(Type::LongTy)));
248
249   // Insert a call to the hash function if this is a pointer value
250   if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
251     const Type *SBP = PointerType::get(Type::SByteTy);
252     if (V->getType() != SBP)     // Cast pointer to be sbyte*
253       V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
254
255     std::vector<Value*> HashArgs(1, V);
256     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
257   }
258
259   // Insert the first print instruction to print the string flag:
260   std::vector<Value*> PrintArgs;
261   PrintArgs.push_back(GEP);
262   if (V) PrintArgs.push_back(V);
263   new CallInst(Printf, PrintArgs, "trace", InsertBefore);
264 }
265
266
267 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
268                                    Instruction *InsertBefore,
269                                    const std::string &Message, Function *Printf,
270                                    Function* HashPtrToSeqNum) {
271   std::ostringstream OutStr;
272   if (V) WriteAsOperand(OutStr, V);
273   InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
274                   Printf, HashPtrToSeqNum);
275 }
276
277 static void
278 InsertReleaseInst(Value *V, BasicBlock *BB,
279                   Instruction *InsertBefore,
280                   Function* ReleasePtrFunc) {
281
282   const Type *SBP = PointerType::get(Type::SByteTy);
283   if (V->getType() != SBP)    // Cast pointer to be sbyte*
284     V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
285
286   std::vector<Value*> releaseArgs(1, V);
287   new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
288 }
289
290 static void
291 InsertRecordInst(Value *V, BasicBlock *BB,
292                  Instruction *InsertBefore,
293                  Function* RecordPtrFunc) {
294     const Type *SBP = PointerType::get(Type::SByteTy);
295   if (V->getType() != SBP)     // Cast pointer to be sbyte*
296     V = new CastInst(V, SBP, "RP_cast", InsertBefore);
297
298   std::vector<Value*> releaseArgs(1, V);
299   new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
300 }
301
302 // Look for alloca and free instructions. These are the ptrs to release.
303 // Release the free'd pointers immediately.  Record the alloca'd pointers
304 // to be released on return from the current function.
305 //
306 static void
307 ReleasePtrSeqNumbers(BasicBlock *BB,
308                      ExternalFuncs& externalFuncs) {
309
310   for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
311     if (FreeInst *FI = dyn_cast<FreeInst>(II))
312       InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
313     else if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
314       InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
315 }
316
317
318 // Insert print instructions at the end of basic block BB for each value
319 // computed in BB that is live at the end of BB,
320 // or that is stored to memory in BB.
321 // If the value is stored to memory, we load it back before printing it
322 // We also return all such loaded values in the vector valuesStoredInFunction
323 // for printing at the exit from the function.  (Note that in each invocation
324 // of the function, this will only get the last value stored for each static
325 // store instruction).
326 //
327 static void TraceValuesAtBBExit(BasicBlock *BB,
328                                 Function *Printf, Function* HashPtrToSeqNum,
329                             std::vector<Instruction*> *valuesStoredInFunction) {
330   // Get an iterator to point to the insertion location, which is
331   // just before the terminator instruction.
332   //
333   TerminatorInst *InsertPos = BB->getTerminator();
334
335   std::ostringstream OutStr;
336   WriteAsOperand(OutStr, BB, false);
337   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
338                   Printf, HashPtrToSeqNum);
339
340   // Insert a print instruction for each instruction preceding InsertPos.
341   // The print instructions must go before InsertPos, so we use the
342   // instruction *preceding* InsertPos to check when to terminate the loop.
343   //
344   for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
345     if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
346       // Trace the stored value and address
347       InsertVerbosePrintInst(SI->getOperand(0), BB, InsertPos,
348                              "  (store value) ", Printf, HashPtrToSeqNum);
349       InsertVerbosePrintInst(SI->getOperand(1), BB, InsertPos,
350                              "  (store addr ) ", Printf, HashPtrToSeqNum);
351     }
352     else if (ShouldTraceValue(II))
353       InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
354   }
355 }
356
357 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
358                                                  Function* HashPtrToSeqNum){
359   // Get an iterator to point to the insertion location
360   BasicBlock &BB = F.getEntryBlock();
361   Instruction *InsertPos = BB.begin();
362
363   std::ostringstream OutStr;
364   WriteAsOperand(OutStr, &F);
365   InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
366                   Printf, HashPtrToSeqNum);
367
368   // Now print all the incoming arguments
369   unsigned ArgNo = 0;
370   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++ArgNo){
371     InsertVerbosePrintInst(I, &BB, InsertPos,
372                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
373                            HashPtrToSeqNum);
374   }
375 }
376
377
378 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
379                                                 Function *Printf,
380                                                 Function* HashPtrToSeqNum) {
381   // Get an iterator to point to the insertion location
382   ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
383
384   std::ostringstream OutStr;
385   WriteAsOperand(OutStr, BB->getParent(), true);
386   InsertPrintInst(0, BB, Ret, "LEAVING  FUNCTION: " + OutStr.str(),
387                   Printf, HashPtrToSeqNum);
388
389   // print the return value, if any
390   if (BB->getParent()->getReturnType() != Type::VoidTy)
391     InsertPrintInst(Ret->getReturnValue(), BB, Ret, "  Returning: ",
392                     Printf, HashPtrToSeqNum);
393 }
394
395
396 bool InsertTraceCode::runOnFunction(Function &F) {
397   if (!TraceThisFunction(F))
398     return false;
399
400   std::vector<Instruction*> valuesStoredInFunction;
401   std::vector<BasicBlock*>  exitBlocks;
402
403   // Insert code to trace values at function entry
404   InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
405                                 externalFuncs.HashPtrFunc);
406
407   // Push a pointer set for recording alloca'd pointers at entry.
408   if (!DisablePtrHashing)
409     new CallInst(externalFuncs.PushOnEntryFunc, std::vector<Value*>(), "",
410                  F.getEntryBlock().begin());
411
412   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
413     if (isa<ReturnInst>(BB->getTerminator()))
414       exitBlocks.push_back(BB); // record this as an exit block
415
416     // Insert trace code if this basic block is interesting...
417     handleBasicBlock(BB, valuesStoredInFunction);
418
419     if (!DisablePtrHashing)          // release seq. numbers on free/ret
420       ReleasePtrSeqNumbers(BB, externalFuncs);
421   }
422
423   for (unsigned i=0; i != exitBlocks.size(); ++i)
424     {
425       // Insert code to trace values at function exit
426       InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
427                                    externalFuncs.HashPtrFunc);
428
429       // Release all recorded pointers before RETURN.  Do this LAST!
430       if (!DisablePtrHashing)
431         new CallInst(externalFuncs.ReleaseOnReturnFunc, std::vector<Value*>(),
432                      "", exitBlocks[i]->getTerminator());
433     }
434
435   return true;
436 }