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