Add new optional getPassName() virtual function that a Pass can override
[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/StringExtras.h"
21 #include <sstream>
22 using std::vector;
23 using std::string;
24
25 namespace {
26   class InsertTraceCode : public FunctionPass {
27     bool TraceBasicBlockExits, TraceFunctionExits;
28     Function *PrintfFunc;
29   public:
30     InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
31       : TraceBasicBlockExits(traceBasicBlockExits), 
32         TraceFunctionExits(traceFunctionExits) {}
33
34     const char *getPassName() const { return "Trace Code Insertion"; }
35     
36     // Add a prototype for printf if it is not already in the program.
37     //
38     bool doInitialization(Module *M);
39     
40     //--------------------------------------------------------------------------
41     // Function InsertCodeToTraceValues
42     // 
43     // Inserts tracing code for all live values at basic block and/or function
44     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
45     //
46     static bool doit(Function *M, bool traceBasicBlockExits,
47                      bool traceFunctionExits, Function *Printf);
48     
49     // runOnFunction - This method does the work.
50     //
51     bool runOnFunction(Function *F) {
52       return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc);
53     }
54
55     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.preservesCFG();
57     }
58   };
59 } // end anonymous namespace
60
61
62 Pass *createTraceValuesPassForFunction() {     // Just trace functions
63   return new InsertTraceCode(false, true);
64 }
65
66 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
67   return new InsertTraceCode(true, true);
68 }
69
70
71
72
73 // Add a prototype for printf if it is not already in the program.
74 //
75 bool InsertTraceCode::doInitialization(Module *M) {
76   const Type *SBP = PointerType::get(Type::SByteTy);
77   const FunctionType *MTy =
78     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
79
80   PrintfFunc = M->getOrInsertFunction("printf", MTy);
81   return false;
82 }
83
84
85 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
86   // Create a constant internal string reference...
87   Constant *Init = ConstantArray::get(str);
88
89   // Create the global variable and record it in the module
90   // The GV will be renamed to a unique name if needed.
91   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
92                                           "trstr");
93   M->getGlobalList().push_back(GV);
94   return GV;
95 }
96
97
98 // 
99 // Check if this instruction has any uses outside its basic block,
100 // or if it used by either a Call or Return instruction.
101 // 
102 static inline bool LiveAtBBExit(const Instruction* I) {
103   const BasicBlock *BB = I->getParent();
104   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
105     if (const Instruction *UI = dyn_cast<Instruction>(*U))
106       if (UI->getParent() != BB || isa<ReturnInst>(UI))
107         return true;
108
109   return false;
110 }
111
112
113 static inline bool TraceThisOpCode(unsigned opCode) {
114   // Explicitly test for opCodes *not* to trace so that any new opcodes will
115   // be traced by default (VoidTy's are already excluded)
116   // 
117   return (opCode  < Instruction::FirstOtherOp &&
118           opCode != Instruction::Alloca &&
119           opCode != Instruction::PHINode &&
120           opCode != Instruction::Cast);
121 }
122
123
124 static bool ShouldTraceValue(const Instruction *I) {
125   return
126     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
127     TraceThisOpCode(I->getOpcode());
128 }
129
130 static string getPrintfCodeFor(const Value *V) {
131   if (V == 0) return "";
132   if (V->getType()->isFloatingPoint())
133     return "%g";
134   else if (V->getType() == Type::LabelTy || isa<PointerType>(V->getType()))
135     return "0x%p";
136   else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
137     return "%d";
138     
139   assert(0 && "Illegal value to print out...");
140   return "";
141 }
142
143
144 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
145                             string Message, Function *Printf) {
146   // Escape Message by replacing all % characters with %% chars.
147   unsigned Offset = 0;
148   while ((Offset = Message.find('%', Offset)) != string::npos) {
149     Message.replace(Offset, 1, "%%");
150     Offset += 2;  // Skip over the new %'s
151   }
152
153   Module *Mod = BB->getParent()->getParent();
154
155   // Turn the marker string into a global variable...
156   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
157
158   // Turn the format string into an sbyte *
159   Instruction *GEP = 
160     new GetElementPtrInst(fmtVal,
161                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
162                           "trstr");
163   BBI = BB->getInstList().insert(BBI, GEP)+1;
164   
165   // Insert the first print instruction to print the string flag:
166   vector<Value*> PrintArgs;
167   PrintArgs.push_back(GEP);
168   if (V) PrintArgs.push_back(V);
169   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
170   BBI = BB->getInstList().insert(BBI, I)+1;
171 }
172                             
173
174 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
175                                    BasicBlock::iterator &BBI,
176                                    const string &Message, Function *Printf) {
177   std::ostringstream OutStr;
178   if (V) WriteAsOperand(OutStr, V);
179   InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
180 }
181
182
183 // Insert print instructions at the end of the basic block *bb
184 // for each value in valueVec[] that is live at the end of that basic block,
185 // or that is stored to memory in this basic block.
186 // If the value is stored to memory, we load it back before printing
187 // We also return all such loaded values in the vector valuesStoredInFunction
188 // for printing at the exit from the function.  (Note that in each invocation
189 // of the function, this will only get the last value stored for each static
190 // store instruction).
191 // *bb must be the block in which the value is computed;
192 // this is not checked here.
193 // 
194 static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf,
195                                 vector<Instruction*> *valuesStoredInFunction) {
196   // Get an iterator to point to the insertion location, which is
197   // just before the terminator instruction.
198   // 
199   BasicBlock::iterator InsertPos = BB->end()-1;
200   assert((*InsertPos)->isTerminator());
201   
202   // If the terminator is a conditional branch, insert the trace code just
203   // before the instruction that computes the branch condition (just to
204   // avoid putting a call between the CC-setting instruction and the branch).
205   // Use laterInstrSet to mark instructions that come after the setCC instr
206   // because those cannot be traced at the location we choose.
207   // 
208   Instruction *SetCC = 0;
209   if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
210     if (!Branch->isUnconditional())
211       if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
212         if (I->getParent() == BB) {
213           SetCC = I;
214           while (*InsertPos != SetCC)
215             --InsertPos;        // Back up until we can insert before the setcc
216         }
217
218   // Copy all of the instructions into a vector to avoid problems with Setcc
219   const vector<Instruction*> Insts(BB->begin(), InsertPos);
220
221   std::ostringstream OutStr;
222   WriteAsOperand(OutStr, BB, false);
223   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
224
225   // Insert a print instruction for each value.
226   // 
227   for (vector<Instruction*>::const_iterator II = Insts.begin(),
228          IE = Insts.end(); II != IE; ++II) {
229     Instruction *I = *II;
230     if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
231       assert(valuesStoredInFunction &&
232              "Should not be printing a store instruction at function exit");
233       LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
234                                   "reload");
235       InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
236       valuesStoredInFunction->push_back(LI);
237     }
238     if (ShouldTraceValue(I))
239       InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf);
240   }
241 }
242
243 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){
244   // Get an iterator to point to the insertion location
245   BasicBlock *BB = M->getEntryNode();
246   BasicBlock::iterator BBI = BB->begin();
247
248   std::ostringstream OutStr;
249   WriteAsOperand(OutStr, M, true);
250   InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(), Printf);
251
252   // Now print all the incoming arguments
253   const Function::ArgumentListType &argList = M->getArgumentList();
254   unsigned ArgNo = 0;
255   for (Function::ArgumentListType::const_iterator
256          I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
257     InsertVerbosePrintInst((Value*)*I, BB, BBI,
258                            "  Arg #" + utostr(ArgNo), Printf);
259   }
260 }
261
262
263 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
264                                                 Function *Printf) {
265   // Get an iterator to point to the insertion location
266   BasicBlock::iterator BBI = BB->end()-1;
267   ReturnInst *Ret = cast<ReturnInst>(*BBI);
268   
269   std::ostringstream OutStr;
270   WriteAsOperand(OutStr, BB->getParent(), true);
271   InsertPrintInst(0, BB, BBI, "LEAVING  FUNCTION: " + OutStr.str(), Printf);
272   
273   // print the return value, if any
274   if (BB->getParent()->getReturnType() != Type::VoidTy)
275     InsertPrintInst(Ret->getReturnValue(), BB, BBI, "  Returning: ", Printf);
276 }
277
278
279 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
280                            bool traceFunctionEvents, Function *Printf) {
281   if (!traceBasicBlockExits && !traceFunctionEvents)
282     return false;
283
284   vector<Instruction*> valuesStoredInFunction;
285   vector<BasicBlock*>  exitBlocks;
286
287   if (traceFunctionEvents)
288     InsertCodeToShowFunctionEntry(M, Printf);
289   
290   for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
291     BasicBlock *BB = *BI;
292     if (isa<ReturnInst>(BB->getTerminator()))
293       exitBlocks.push_back(BB); // record this as an exit block
294     
295     if (traceBasicBlockExits)
296       TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction);
297   }
298
299   if (traceFunctionEvents)
300     for (unsigned i=0; i < exitBlocks.size(); ++i) {
301 #if 0
302       TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module,
303                           /*indent*/ 0, /*isFunctionExit*/ true,
304                           /*valuesStoredInFunction*/ NULL);
305 #endif
306       InsertCodeToShowFunctionExit(exitBlocks[i], Printf);
307     }
308
309   return true;
310 }