1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and method
6 //===----------------------------------------------------------------------===//
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/Assembly/Writer.h"
19 #include "Support/StringExtras.h"
23 // Add a prototype for printf if it is not already in the program.
25 bool InsertTraceCode::doPassInitialization(Module *M) {
26 SymbolTable *ST = M->getSymbolTable();
27 const Type *SBP = PointerType::get(Type::SByteTy);
28 const MethodType *MTy =
29 MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
31 if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
32 PrintfMeth = cast<Method>(Meth);
36 // Create a new method and add it to the module
37 PrintfMeth = new Method(MTy, false, "printf");
38 M->getMethodList().push_back(PrintfMeth);
43 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
44 // Create a constant internal string reference...
45 Constant *Init = ConstantArray::get(str);
46 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
48 M->getGlobalList().push_back(GV);
54 // Check if this instruction has any uses outside its basic block,
55 // or if it used by either a Call or Return instruction.
57 static inline bool LiveAtBBExit(const Instruction* I) {
58 const BasicBlock *BB = I->getParent();
59 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
60 if (const Instruction *UI = dyn_cast<Instruction>(*U))
61 if (UI->getParent() != BB || isa<ReturnInst>(UI))
68 static inline bool TraceThisOpCode(unsigned opCode) {
69 // Explicitly test for opCodes *not* to trace so that any new opcodes will
70 // be traced by default (VoidTy's are already excluded)
72 return (opCode < Instruction::FirstOtherOp &&
73 opCode != Instruction::Alloca &&
74 opCode != Instruction::PHINode &&
75 opCode != Instruction::Cast);
79 static bool ShouldTraceValue(const Instruction *I) {
81 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
82 TraceThisOpCode(I->getOpcode());
85 static string getPrintfCodeFor(const Value *V) {
86 if (V == 0) return "";
87 switch (V->getType()->getPrimitiveID()) {
89 case Type::UByteTyID: case Type::UShortTyID:
90 case Type::UIntTyID: case Type::ULongTyID:
91 case Type::SByteTyID: case Type::ShortTyID:
92 case Type::IntTyID: case Type::LongTyID:
95 case Type::FloatTyID: case Type::DoubleTyID:
98 case Type::LabelTyID: case Type::PointerTyID:
102 assert(0 && "Illegal value to print out...");
108 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
109 string Message, Method *Printf) {
110 // Escape Message by replacing all % characters with %% chars.
112 while ((Offset = Message.find('%', Offset)) != string::npos) {
113 string::iterator Offs = Message.begin()+Offset;
114 //Message.replace(Offs, Offs+1, "%%");
115 Message.replace(Offset, 2, "%%");
116 Offset += 2; // Skip over the new %'s
119 Module *Mod = BB->getParent()->getParent();
121 // Turn the marker string into a global variable...
122 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
124 // Turn the format string into an sbyte *
126 new GetElementPtrInst(fmtVal,
127 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
129 BBI = BB->getInstList().insert(BBI, GEP)+1;
131 // Insert the first print instruction to print the string flag:
132 vector<Value*> PrintArgs;
133 PrintArgs.push_back(GEP);
134 if (V) PrintArgs.push_back(V);
135 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
136 BBI = BB->getInstList().insert(BBI, I)+1;
140 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
141 BasicBlock::iterator &BBI,
142 const string &Message, Method *Printf) {
143 ostringstream OutStr;
144 if (V) WriteAsOperand(OutStr, V);
145 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
149 // Insert print instructions at the end of the basic block *bb
150 // for each value in valueVec[] that is live at the end of that basic block,
151 // or that is stored to memory in this basic block.
152 // If the value is stored to memory, we load it back before printing
153 // We also return all such loaded values in the vector valuesStoredInMethod
154 // for printing at the exit from the method. (Note that in each invocation
155 // of the method, this will only get the last value stored for each static
156 // store instruction).
157 // *bb must be the block in which the value is computed;
158 // this is not checked here.
160 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
161 vector<Instruction*> *valuesStoredInMethod) {
162 // Get an iterator to point to the insertion location, which is
163 // just before the terminator instruction.
165 BasicBlock::iterator InsertPos = BB->end()-1;
166 assert((*InsertPos)->isTerminator());
168 // If the terminator is a conditional branch, insert the trace code just
169 // before the instruction that computes the branch condition (just to
170 // avoid putting a call between the CC-setting instruction and the branch).
171 // Use laterInstrSet to mark instructions that come after the setCC instr
172 // because those cannot be traced at the location we choose.
174 Instruction *SetCC = 0;
175 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
176 if (!Branch->isUnconditional())
177 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
178 if (I->getParent() == BB) {
180 while (*InsertPos != SetCC)
181 --InsertPos; // Back up until we can insert before the setcc
184 // Copy all of the instructions into a vector to avoid problems with Setcc
185 const vector<Instruction*> Insts(BB->begin(), InsertPos);
187 ostringstream OutStr;
188 WriteAsOperand(OutStr, BB, false);
189 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
191 // Insert a print instruction for each value.
193 for (vector<Instruction*>::const_iterator II = Insts.begin(),
194 IE = Insts.end(); II != IE; ++II) {
195 Instruction *I = *II;
196 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
197 assert(valuesStoredInMethod &&
198 "Should not be printing a store instruction at method exit");
199 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
201 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
202 valuesStoredInMethod->push_back(LI);
204 if (ShouldTraceValue(I))
205 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
209 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
210 // Get an iterator to point to the insertion location
211 BasicBlock *BB = M->getEntryNode();
212 BasicBlock::iterator BBI = BB->begin();
214 ostringstream OutStr;
215 WriteAsOperand(OutStr, M, true);
216 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
218 // Now print all the incoming arguments
219 const Method::ArgumentListType &argList = M->getArgumentList();
221 for (Method::ArgumentListType::const_iterator
222 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
223 InsertVerbosePrintInst(*I, BB, BBI,
224 " Arg #" + utostr(ArgNo), Printf);
229 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
230 // Get an iterator to point to the insertion location
231 BasicBlock::iterator BBI = BB->end()-1;
232 ReturnInst *Ret = cast<ReturnInst>(*BBI);
234 ostringstream OutStr;
235 WriteAsOperand(OutStr, BB->getParent(), true);
236 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
238 // print the return value, if any
239 if (BB->getParent()->getReturnType() != Type::VoidTy)
240 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
244 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
245 bool traceMethodEvents, Method *Printf) {
246 if (M->isExternal() || (!traceBasicBlockExits && !traceMethodEvents))
249 vector<Instruction*> valuesStoredInMethod;
250 vector<BasicBlock*> exitBlocks;
252 Module *module = M->getParent();
254 if (traceMethodEvents)
255 InsertCodeToShowMethodEntry(M, Printf);
257 for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
258 BasicBlock *BB = *BI;
259 if (isa<ReturnInst>(BB->getTerminator()))
260 exitBlocks.push_back(BB); // record this as an exit block
262 if (traceBasicBlockExits)
263 TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
266 if (traceMethodEvents)
267 for (unsigned i=0; i < exitBlocks.size(); ++i) {
269 TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
270 /*indent*/ 0, /*isMethodExit*/ true,
271 /*valuesStoredInMethod*/ NULL);
273 InsertCodeToShowMethodExit(exitBlocks[i], Printf);