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