blob: 2d1ff3dad810af776d8675b343a832265ef35dac [file] [log] [blame]
Vikram S. Advea200a6c2001-10-14 23:18:45 +00001// $Id$
2//***************************************************************************
3// File:
4// TraceValues.cpp
5//
6// Purpose:
7// Support for inserting LLVM code to print values at basic block
8// and method exits. Also exports functions to create a call
9// "printf" instruction with one of the signatures listed below.
10//
11// History:
12// 10/11/01 - Vikram Adve - Created
13//**************************************************************************/
14
15
16#include "llvm/Transforms/Instrumentation/TraceValues.h"
17#include "llvm/GlobalVariable.h"
18#include "llvm/ConstPoolVals.h"
19#include "llvm/Type.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instruction.h"
Vikram S. Advea0db1c92001-10-18 18:16:11 +000022#include "llvm/iMemory.h"
Vikram S. Advea200a6c2001-10-14 23:18:45 +000023#include "llvm/iTerminators.h"
24#include "llvm/iOther.h"
25#include "llvm/BasicBlock.h"
26#include "llvm/Method.h"
27#include "llvm/Module.h"
28#include "llvm/SymbolTable.h"
Chris Lattnera0a8b5b2001-10-18 05:28:08 +000029#include "llvm/Assembly/Writer.h"
Vikram S. Adve7ac553a2001-10-18 13:49:22 +000030#include "llvm/Support/HashExtras.h"
31#include <strstream>
32#include <hash_map>
33
34
35//*********************** Internal Data Structures *************************/
36
37const char* const PRINTF = "printf";
38
39
40//************************** Internal Functions ****************************/
41
Vikram S. Advea200a6c2001-10-14 23:18:45 +000042
Chris Lattnera0a8b5b2001-10-18 05:28:08 +000043static inline GlobalVariable *
44GetStringRef(Module *M, const string &str)
Vikram S. Advea200a6c2001-10-14 23:18:45 +000045{
Vikram S. Adve7ac553a2001-10-18 13:49:22 +000046 static hash_map<string, GlobalVariable*> stringRefCache;
47 static Module* lastModule = NULL;
48
49 if (lastModule != M)
50 { // Let's make sure we create separate global references in each module
51 stringRefCache.clear();
52 lastModule = M;
53 }
54
55 GlobalVariable* result = stringRefCache[str];
56 if (result == NULL)
57 {
58 ConstPoolArray *Init = ConstPoolArray::get(str);
59 result = new GlobalVariable(Init->getType(), /*Const*/true, Init);
60 M->getGlobalList().push_back(result);
61 stringRefCache[str] = result;
62 }
63
64 return result;
Vikram S. Advea200a6c2001-10-14 23:18:45 +000065}
66
Vikram S. Adve7ac553a2001-10-18 13:49:22 +000067
Chris Lattner1afbdc02001-10-15 13:07:21 +000068static inline bool
Vikram S. Advea200a6c2001-10-14 23:18:45 +000069TraceThisOpCode(unsigned opCode)
70{
71 // Explicitly test for opCodes *not* to trace so that any new opcodes will
Chris Lattnera0a8b5b2001-10-18 05:28:08 +000072 // be traced by default (VoidTy's are already excluded)
Vikram S. Advea200a6c2001-10-14 23:18:45 +000073 //
74 return (opCode < Instruction::FirstOtherOp &&
Vikram S. Advea200a6c2001-10-14 23:18:45 +000075 opCode != Instruction::Alloca &&
Vikram S. Advea200a6c2001-10-14 23:18:45 +000076 opCode != Instruction::PHINode &&
77 opCode != Instruction::Cast);
78}
79
Vikram S. Advea0db1c92001-10-18 18:16:11 +000080//
81// Check if this instruction has any uses outside its basic block
82//
83static inline bool
84LiveAtBBExit(Instruction* I)
85{
86 BasicBlock* bb = I->getParent();
87 bool isLive = false;
88 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
89 {
90 const Instruction* userI = dyn_cast<Instruction>(*U);
91 if (userI == NULL || userI->getParent() != bb)
92 isLive = true;
93 }
94
95 return isLive;
96}
97
Vikram S. Advea200a6c2001-10-14 23:18:45 +000098
Chris Lattnera0a8b5b2001-10-18 05:28:08 +000099static void
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000100FindValuesToTraceInBB(BasicBlock* bb, vector<Instruction*>& valuesToTraceInBB)
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000101{
102 for (BasicBlock::iterator II = bb->begin(); II != bb->end(); ++II)
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000103 if ((*II)->getOpcode() == Instruction::Store
104 || (LiveAtBBExit(*II) &&
105 (*II)->getType()->isPrimitiveType() &&
106 (*II)->getType() != Type::VoidTy &&
107 TraceThisOpCode((*II)->getOpcode())))
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000108 {
109 valuesToTraceInBB.push_back(*II);
110 }
111}
112
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000113
114//
115// Let's save this code for future use; it has been tested and works:
116//
117// The signatures of the printf methods supported are:
118// int printf(ubyte*, ubyte*, ubyte*, ubyte*, int intValue)
119// int printf(ubyte*, ubyte*, ubyte*, ubyte*, unsigned uintValue)
120// int printf(ubyte*, ubyte*, ubyte*, ubyte*, float floatValue)
121// int printf(ubyte*, ubyte*, ubyte*, ubyte*, double doubleValue)
122// int printf(ubyte*, ubyte*, ubyte*, ubyte*, char* stringValue)
123// int printf(ubyte*, ubyte*, ubyte*, ubyte*, void* ptrValue)
124//
125// The invocation should be:
126// call "printf"(fmt, bbName, valueName, valueTypeName, value).
127//
128Method*
129GetPrintfMethodForType(Module* module, const Type* valueType)
130{
131 static const int LASTARGINDEX = 4;
132 static PointerType* ubytePtrTy = NULL;
133 static vector<const Type*> argTypesVec(LASTARGINDEX + 1);
134
135 if (ubytePtrTy == NULL)
136 { // create these once since they are invariant
137 ubytePtrTy = PointerType::get(ArrayType::get(Type::UByteTy));
138 argTypesVec[0] = ubytePtrTy;
139 argTypesVec[1] = ubytePtrTy;
140 argTypesVec[2] = ubytePtrTy;
141 argTypesVec[3] = ubytePtrTy;
142 }
143
144 SymbolTable* symtab = module->getSymbolTable();
145 argTypesVec[LASTARGINDEX] = valueType;
146 MethodType* printMethodTy = MethodType::get(Type::IntTy, argTypesVec,
147 /*isVarArg*/ false);
148
149 Method* printMethod =
150 cast<Method>(symtab->lookup(PointerType::get(printMethodTy), PRINTF));
151 if (printMethod == NULL)
152 { // Create a new method and add it to the module
153 printMethod = new Method(printMethodTy, PRINTF);
154 module->getMethodList().push_back(printMethod);
155
156 // Create the argument list for the method so that the full signature
157 // can be declared. The args can be anonymous.
158 Method::ArgumentListType &argList = printMethod->getArgumentList();
159 for (unsigned i=0; i < argTypesVec.size(); ++i)
160 argList.push_back(new MethodArgument(argTypesVec[i]));
161 }
162
163 return printMethod;
164}
165
166
167Instruction*
168CreatePrintfInstr(Value* val,
169 const BasicBlock* bb,
170 Module* module,
171 unsigned int indent,
172 bool isMethodExit)
173{
174 strstream fmtString, scopeNameString, valNameString;
175 vector<Value*> paramList;
176 const Type* valueType = val->getType();
177 Method* printMethod = GetPrintfMethodForType(module, valueType);
178
179 if (! valueType->isPrimitiveType() ||
180 valueType->getPrimitiveID() == Type::VoidTyID ||
181 valueType->getPrimitiveID() == Type::TypeTyID ||
182 valueType->getPrimitiveID() == Type::LabelTyID)
183 {
184 assert(0 && "Unsupported type for printing");
185 return NULL;
186 }
187
188 const Value* scopeToUse = (isMethodExit)? (const Value*) bb->getParent()
189 : (const Value*) bb;
190 if (scopeToUse->hasName())
191 scopeNameString << scopeToUse->getName() << ends;
192 else
193 scopeNameString << scopeToUse << ends;
194
195 if (val->hasName())
196 valNameString << val->getName() << ends;
197 else
198 valNameString << val << ends;
199
200 for (unsigned i=0; i < indent; i++)
201 fmtString << " ";
202
203 fmtString << " At exit of "
204 << ((isMethodExit)? "Method " : "BB ")
205 << "%s : val %s = %s ";
206
207 GlobalVariable* scopeNameVal = GetStringRef(module, scopeNameString.str());
208 GlobalVariable* valNameVal = GetStringRef(module,valNameString.str());
209 GlobalVariable* typeNameVal = GetStringRef(module,
210 val->getType()->getDescription().c_str());
211
212 switch(valueType->getPrimitiveID())
213 {
214 case Type::BoolTyID:
215 case Type::UByteTyID: case Type::UShortTyID:
216 case Type::UIntTyID: case Type::ULongTyID:
217 case Type::SByteTyID: case Type::ShortTyID:
218 case Type::IntTyID: case Type::LongTyID:
219 fmtString << " %d\0A";
220 break;
221
222 case Type::FloatTyID: case Type::DoubleTyID:
223 fmtString << " %g\0A";
224 break;
225
226 case Type::PointerTyID:
227 fmtString << " %p\0A";
228 break;
229
230 default:
231 assert(0 && "Should not get here. Check the IF expression above");
232 return NULL;
233 }
234
235 fmtString << ends;
236 GlobalVariable* fmtVal = GetStringRef(module, fmtString.str());
237
238 paramList.push_back(fmtVal);
239 paramList.push_back(scopeNameVal);
240 paramList.push_back(valNameVal);
241 paramList.push_back(typeNameVal);
242 paramList.push_back(val);
243
244 free(fmtString.str());
245 free(scopeNameString.str());
246 free(valNameString.str());
247
248 return new CallInst(printMethod, paramList);
249}
250
251
252
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000253// The invocation should be:
Chris Lattner5309e102001-10-18 06:03:05 +0000254// call "printVal"(value).
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000255//
Chris Lattner5309e102001-10-18 06:03:05 +0000256static Value *GetPrintMethodForType(Module *Mod, const Type *VTy) {
257 MethodType *MTy = MethodType::get(Type::VoidTy, vector<const Type*>(1, VTy),
258 /*isVarArg*/ false);
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000259
260 SymbolTable *ST = Mod->getSymbolTableSure();
Chris Lattner5309e102001-10-18 06:03:05 +0000261 if (Value *V = ST->lookup(PointerType::get(MTy), "printVal"))
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000262 return V;
263
264 // Create a new method and add it to the module
Chris Lattner5309e102001-10-18 06:03:05 +0000265 Method *M = new Method(MTy, "printVal");
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000266 Mod->getMethodList().push_back(M);
267 return M;
268}
269
270
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000271static void
272InsertPrintInsts(Value *Val,
273 BasicBlock* BB,
274 BasicBlock::iterator &BBI,
275 Module *Mod,
276 unsigned int indent,
277 bool isMethodExit)
278{
Chris Lattner5309e102001-10-18 06:03:05 +0000279 const Type* ValTy = Val->getType();
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000280
Chris Lattner5309e102001-10-18 06:03:05 +0000281 assert(ValTy->isPrimitiveType() &&
282 ValTy->getPrimitiveID() != Type::VoidTyID &&
283 ValTy->getPrimitiveID() != Type::TypeTyID &&
284 ValTy->getPrimitiveID() != Type::LabelTyID &&
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000285 "Unsupported type for printing");
286
Chris Lattner5309e102001-10-18 06:03:05 +0000287 const Value* scopeToUse =
288 isMethodExit ? (const Value*)BB->getParent() : (const Value*)BB;
289
290 // Create the marker string...
291 strstream scopeNameString;
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000292 WriteAsOperand(scopeNameString, scopeToUse) << " : ";
Chris Lattner5309e102001-10-18 06:03:05 +0000293 WriteAsOperand(scopeNameString, Val) << " = " << ends;
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000294 string fmtString(indent, ' ');
295
Chris Lattner5309e102001-10-18 06:03:05 +0000296 fmtString += string(" At exit of") + scopeNameString.str();
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000297 free(scopeNameString.str());
298
Chris Lattner5309e102001-10-18 06:03:05 +0000299 // Turn the marker string into a global variable...
300 GlobalVariable *fmtVal = GetStringRef(Mod, fmtString);
301
302 // Insert the first print instruction to print the string flag:
303 Instruction *I = new CallInst(GetPrintMethodForType(Mod, fmtVal->getType()),
304 vector<Value*>(1, fmtVal));
305 BBI = BB->getInstList().insert(BBI, I)+1;
306
307 // Insert the next print instruction to print the value:
308 I = new CallInst(GetPrintMethodForType(Mod, ValTy),
309 vector<Value*>(1, Val));
310 BBI = BB->getInstList().insert(BBI, I)+1;
311
312 // Print out a newline
313 fmtVal = GetStringRef(Mod, "\n");
314 I = new CallInst(GetPrintMethodForType(Mod, fmtVal->getType()),
315 vector<Value*>(1, fmtVal));
316 BBI = BB->getInstList().insert(BBI, I)+1;
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000317}
318
319
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000320static LoadInst*
321InsertLoadInst(StoreInst* storeInst,
322 BasicBlock *bb,
323 BasicBlock::iterator &BBI)
324{
325 LoadInst* loadInst = new LoadInst(storeInst->getPtrOperand(),
326 storeInst->getIndexVec());
327 BBI = bb->getInstList().insert(BBI, loadInst) + 1;
328 return loadInst;
329}
330
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000331
332//
333// Insert print instructions at the end of the basic block *bb
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000334// for each value in valueVec[] that is live at the end of that basic block,
335// or that is stored to memory in this basic block.
336// If the value is stored to memory, we load it back before printing
337// We also return all such loaded values in the vector valuesStoredInMethod
338// for printing at the exit from the method. (Note that in each invocation
339// of the method, this will only get the last value stored for each static
340// store instruction).
341// *bb must be the block in which the value is computed;
342// this is not checked here.
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000343//
344static void
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000345TraceValuesAtBBExit(const vector<Instruction*>& valueVec,
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000346 BasicBlock* bb,
347 Module* module,
348 unsigned int indent,
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000349 bool isMethodExit,
350 vector<Instruction*>* valuesStoredInMethod)
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000351{
352 // Get an iterator to point to the insertion location
353 //
354 BasicBlock::InstListType& instList = bb->getInstList();
Chris Lattner5309e102001-10-18 06:03:05 +0000355 BasicBlock::iterator here = instList.end()-1;
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000356 assert((*here)->isTerminator());
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000357
358 // Insert a print instruction for each value.
359 //
360 for (unsigned i=0, N=valueVec.size(); i < N; i++)
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000361 {
362 Instruction* I = valueVec[i];
363 if (I->getOpcode() == Instruction::Store)
364 {
365 assert(valuesStoredInMethod != NULL &&
366 "Should not be printing a store instruction at method exit");
367 I = InsertLoadInst((StoreInst*) I, bb, here);
368 valuesStoredInMethod->push_back(I);
369 }
370 InsertPrintInsts(I, bb, here, module, indent, isMethodExit);
371 }
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000372}
373
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000374
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000375
376static Instruction*
377CreateMethodTraceInst(
378 Method* method,
379 unsigned int indent,
380 const string& msg)
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000381{
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000382 string fmtString(indent, ' ');
383 strstream methodNameString;
384 WriteAsOperand(methodNameString, method) << ends;
385 fmtString += msg + string(" METHOD ") + methodNameString.str();
386 free(methodNameString.str());
387
388 GlobalVariable *fmtVal = GetStringRef(method->getParent(), fmtString);
389 Instruction *printInst =
390 new CallInst(GetPrintMethodForType(method->getParent(), fmtVal->getType()),
391 vector<Value*>(1, fmtVal));
392
393 return printInst;
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000394}
395
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000396
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000397static inline void
398InsertCodeToShowMethodEntry(Method* method,
399 BasicBlock* entryBB,
400 unsigned int indent)
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000401{
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000402 // Get an iterator to point to the insertion location
403 BasicBlock::InstListType& instList = entryBB->getInstList();
404 BasicBlock::iterator here = instList.begin();
405
406 Instruction *printInst = CreateMethodTraceInst(method, indent, "ENTERING");
407
408 here = entryBB->getInstList().insert(here, printInst) + 1;
409}
410
411
412static inline void
413InsertCodeToShowMethodExit(Method* method,
414 BasicBlock* exitBB,
415 unsigned int indent)
416{
417 // Get an iterator to point to the insertion location
418 BasicBlock::InstListType& instList = exitBB->getInstList();
419 BasicBlock::iterator here = instList.end()-1;
420 assert((*here)->isTerminator());
421
422 Instruction *printInst = CreateMethodTraceInst(method, indent, "LEAVING ");
423
424 here = exitBB->getInstList().insert(here, printInst) + 1;
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000425}
426
427
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000428//************************** External Functions ****************************/
429
430
431bool
432InsertTraceCode::doInsertTraceCode(Method *M,
433 bool traceBasicBlockExits,
434 bool traceMethodExits)
435{
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000436 vector<Instruction*> valuesStoredInMethod;
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000437 Module* module = M->getParent();
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000438 vector<BasicBlock*> exitBlocks;
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000439
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000440 if (M->isExternal() ||
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000441 (! traceBasicBlockExits && ! traceMethodExits))
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000442 return false;
443
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000444 if (traceMethodExits)
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000445 InsertCodeToShowMethodEntry(M, M->getEntryNode(), /*indent*/ 0);
446
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000447 for (Method::iterator BI = M->begin(); BI != M->end(); ++BI)
448 {
449 BasicBlock* bb = *BI;
450 bool isExitBlock = false;
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000451 vector<Instruction*> valuesToTraceInBB;
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000452
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000453 FindValuesToTraceInBB(bb, valuesToTraceInBB);
454
455 if (bb->succ_begin() == bb->succ_end())
456 { // record this as an exit block
457 exitBlocks.push_back(bb);
458 isExitBlock = true;
459 }
460
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000461 if (traceBasicBlockExits)
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000462 TraceValuesAtBBExit(valuesToTraceInBB, bb, module,
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000463 /*indent*/ 4, /*isMethodExit*/ false,
464 &valuesStoredInMethod);
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000465 }
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000466
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000467 if (traceMethodExits)
468 for (unsigned i=0; i < exitBlocks.size(); ++i)
469 {
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000470 TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
471 /*indent*/ 0, /*isMethodExit*/ true,
472 /*valuesStoredInMethod*/ NULL);
473 InsertCodeToShowMethodExit(M, exitBlocks[i], /*indent*/ 0);
Vikram S. Adve7ac553a2001-10-18 13:49:22 +0000474 }
Vikram S. Advea0db1c92001-10-18 18:16:11 +0000475
Chris Lattnera0a8b5b2001-10-18 05:28:08 +0000476 return true;
Vikram S. Advea200a6c2001-10-14 23:18:45 +0000477}