Initial makefile
[oota-llvm.git] / lib / Transforms / Instrumentation / TraceValues.cpp
index c77d39e099b5dfc244658a6e383e1bbd9a0e9626..57230c6b77c1355b9601200561b435be3d4c7c2b 100644 (file)
 #include "llvm/Assembly/Writer.h"
 #include "Support/CommandLine.h"
 #include "Support/StringExtras.h"
+#include <algorithm>
 #include <sstream>
 using std::vector;
 using std::string;
 
+static cl::Flag DisablePtrHashing("tracedisablehashdisable",
+                                  "Disable pointer hashing", cl::NoFlags);
 
-enum TraceHashPtrOpt {
-   HashToSeqNum, NoHash
-};
-
-static cl::Enum<enum TraceHashPtrOpt> TraceHashPtrs("tracehash", cl::NoFlags,
-  "Hash pointer values when tracing",
-  clEnumValN(HashToSeqNum, "on", "Hash pointers to sequence number"),
-  clEnumValN(NoHash ,      "off","Disable hashing of pointers"), 0);
-
-
-static cl::StringList TraceFuncName ("tracefunc", "trace these functions", cl::NoFlags);
+static cl::StringList TraceFuncName ("tracefunc", "trace only specific funct"
+                                     "ions", cl::NoFlags);
 
 
 // We trace a particular function if no functions to trace were specified
@@ -45,22 +39,17 @@ TraceThisFunction(Function* func)
 {
   if (TraceFuncName.getNumOccurances() == 0)
     return true;
-  
-  for (std::vector<std::string>::const_iterator SI=TraceFuncName.begin(),
-         SE=TraceFuncName.end(); SI != SE; ++SI)
-    if (func->getName() == *SI)
-      return true;
-  
-  return false;
+
+  return std::find(TraceFuncName.begin(), TraceFuncName.end(), func->getName())
+                  != TraceFuncName.end();
 }
 
 
 namespace {
-  class ExternalFuncs {
-  public:
+  struct ExternalFuncs {
     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
-    void doInitialization(Module *M); // Add prototypes for external functions
+    void doInitialization(Module &M); // Add prototypes for external functions
   };
   
   class InsertTraceCode : public FunctionPass {
@@ -75,7 +64,7 @@ namespace {
     
     // Add a prototype for runtime functions not already in the program.
     //
-    bool doInitialization(Module *M);
+    bool doInitialization(Module &M);
     
     //--------------------------------------------------------------------------
     // Function InsertCodeToTraceValues
@@ -88,8 +77,8 @@ namespace {
 
     // runOnFunction - This method does the work.
     //
-    bool runOnFunction(Function *F) {
-      return doit(F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
+    bool runOnFunction(Function &F) {
+      return doit(&F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
     }
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
@@ -109,38 +98,36 @@ Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
 
 // Add a prototype for external functions used by the tracing code.
 //
-void ExternalFuncs::doInitialization(Module *M) {
+void ExternalFuncs::doInitialization(Module &M) {
   const Type *SBP = PointerType::get(Type::SByteTy);
   const FunctionType *MTy =
     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
-  PrintfFunc = M->getOrInsertFunction("printf", MTy);
-  
-  // Use varargs functions with no args instead of func(sbyte*) so that
-  // we don't have to generate cast instructions below :-)
-  // 
+  PrintfFunc = M.getOrInsertFunction("printf", MTy);
+
+  // uint (sbyte*)
   const FunctionType *hashFuncTy =
-    FunctionType::get(Type::UIntTy, vector<const Type*>(), true);
-  HashPtrFunc = M->getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
+    FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
+  HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
   
-  // varargs again, same reason.
-  const FunctionType *voidVAFuncTy =
-    FunctionType::get(Type::VoidTy, vector<const Type*>(), true);
+  // void (sbyte*)
+  const FunctionType *voidSBPFuncTy =
+    FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
   
-  ReleasePtrFunc =M->getOrInsertFunction("ReleasePointerSeqNum", voidVAFuncTy);
-  RecordPtrFunc = M->getOrInsertFunction("RecordPointer", voidVAFuncTy);
+  ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
+  RecordPtrFunc  = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
   
   const FunctionType *voidvoidFuncTy =
     FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
   
-  PushOnEntryFunc = M->getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
-  ReleaseOnReturnFunc = M->getOrInsertFunction("ReleasePointersPopSet",
+  PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
+  ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
                                                voidvoidFuncTy);
 }
 
 
 // Add a prototype for external functions used by the tracing code.
 //
-bool InsertTraceCode::doInitialization(Module *M) {
+bool InsertTraceCode::doInitialization(Module &M) {
   externalFuncs.doInitialization(M);
   return false;
 }
@@ -198,7 +185,7 @@ static string getPrintfCodeFor(const Value *V) {
   else if (V->getType() == Type::LabelTy)
     return "0x%p";
   else if (isa<PointerType>(V->getType()))
-    return (TraceHashPtrs == NoHash)? "0x%p" : "%d";
+    return DisablePtrHashing ? "0x%p" : "%d";
   else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
     return "%d";
   
@@ -227,14 +214,20 @@ static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
     new GetElementPtrInst(fmtVal,
                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
                           "trstr");
-  BBI = BB->getInstList().insert(BBI, GEP)+1;
+  BBI = ++BB->getInstList().insert(BBI, GEP);
   
   // Insert a call to the hash function if this is a pointer value
-  if (V && isa<PointerType>(V->getType()) && TraceHashPtrs == HashToSeqNum) {
-    vector<Value*> HashArgs;
-    HashArgs.push_back(V);
+  if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
+    const Type *SBP = PointerType::get(Type::SByteTy);
+    if (V->getType() != SBP) {   // Cast pointer to be sbyte*
+      Instruction *I = new CastInst(V, SBP, "Hash_cast");
+      BBI = ++BB->getInstList().insert(BBI, I);
+      V = I;
+    }
+
+    vector<Value*> HashArgs(1, V);
     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
-    BBI = BB->getInstList().insert(BBI, cast<Instruction>(V))+1;
+    BBI = ++BB->getInstList().insert(BBI, cast<Instruction>(V));
   }
   
   // Insert the first print instruction to print the string flag:
@@ -242,7 +235,7 @@ static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
   PrintArgs.push_back(GEP);
   if (V) PrintArgs.push_back(V);
   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
-  BBI = BB->getInstList().insert(BBI, I)+1;
+  BBI = ++BB->getInstList().insert(BBI, I);
 }
                             
 
@@ -260,37 +253,48 @@ static void
 InsertReleaseInst(Value *V, BasicBlock *BB,
                   BasicBlock::iterator &BBI,
                   Function* ReleasePtrFunc) {
-  vector<Value*> releaseArgs;
-  releaseArgs.push_back(V);
+  
+  const Type *SBP = PointerType::get(Type::SByteTy);
+  if (V->getType() != SBP) {   // Cast pointer to be sbyte*
+    Instruction *I = new CastInst(V, SBP, "RPSN_cast");
+    BBI = ++BB->getInstList().insert(BBI, I);
+    V = I;
+  }
+  vector<Value*> releaseArgs(1, V);
   Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
-  BBI = BB->getInstList().insert(BBI, I)+1;
+  BBI = ++BB->getInstList().insert(BBI, I);
 }
 
 static void 
 InsertRecordInst(Value *V, BasicBlock *BB,
                  BasicBlock::iterator &BBI,
                  Function* RecordPtrFunc) {
-  vector<Value*> releaseArgs;
-  releaseArgs.push_back(V);
+    const Type *SBP = PointerType::get(Type::SByteTy);
+  if (V->getType() != SBP) {   // Cast pointer to be sbyte*
+    Instruction *I = new CastInst(V, SBP, "RP_cast");
+    BBI = ++BB->getInstList().insert(BBI, I);
+    V = I;
+  }
+  vector<Value*> releaseArgs(1, V);
   Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
-  BBI = BB->getInstList().insert(BBI, I)+1;
+  BBI = ++BB->getInstList().insert(BBI, I);
 }
 
 static void
 InsertPushOnEntryFunc(Function *M,
                       Function* PushOnEntryFunc) {
   // Get an iterator to point to the insertion location
-  BasicBlock *BB = M->getEntryNode();
-  BB->getInstList().insert(BB->begin(), new CallInst(PushOnEntryFunc,
-                                                     vector<Value*> ()));
+  BasicBlock &BB = M->getEntryNode();
+  BB.getInstList().insert(BB.begin(), new CallInst(PushOnEntryFunc,
+                                                   vector<Value*>()));
 }
 
 static void 
 InsertReleaseRecordedInst(BasicBlock *BB,
                           Function* ReleaseOnReturnFunc) {
-  BasicBlock::iterator BBI = BB->end()-1;
-  BBI = 1 + BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
-                                                       vector<Value*>()));
+  BasicBlock::iterator BBI = --BB->end();
+  BBI = ++BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
+                                                     vector<Value*>()));
 }
 
 // Look for alloca and free instructions. These are the ptrs to release.
@@ -302,28 +306,26 @@ ReleasePtrSeqNumbers(BasicBlock *BB,
                      ExternalFuncs& externalFuncs) {
   
   for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
-    if (FreeInst *FI = dyn_cast<FreeInst>(*II))
+    if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
       InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
-    else if (AllocaInst *AI = dyn_cast<AllocaInst>(*II))
+    else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
       {
-        BasicBlock::iterator nextI = II+1;
+        BasicBlock::iterator nextI = ++II;
         InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);     
-        II = nextI - 1;
+        II = --nextI;
       }
   }
 }  
 
 
-// Insert print instructions at the end of the basic block *bb
-// for each value in valueVec[] that is live at the end of that basic block,
-// or that is stored to memory in this basic block.
-// If the value is stored to memory, we load it back before printing
+// Insert print instructions at the end of basic block BB for each value
+// computed in BB that is live at the end of BB,
+// or that is stored to memory in BB.
+// If the value is stored to memory, we load it back before printing it
 // We also return all such loaded values in the vector valuesStoredInFunction
 // for printing at the exit from the function.  (Note that in each invocation
 // of the function, this will only get the last value stored for each static
 // store instruction).
-// *bb must be the block in which the value is computed;
-// this is not checked here.
 // 
 static void TraceValuesAtBBExit(BasicBlock *BB,
                                 Function *Printf, Function* HashPtrToSeqNum,
@@ -331,9 +333,18 @@ static void TraceValuesAtBBExit(BasicBlock *BB,
   // Get an iterator to point to the insertion location, which is
   // just before the terminator instruction.
   // 
-  BasicBlock::iterator InsertPos = BB->end()-1;
-  assert((*InsertPos)->isTerminator());
+  BasicBlock::iterator InsertPos = --BB->end();
+  assert(InsertPos->isTerminator());
   
+#undef CANNOT_SAVE_CCR_ACROSS_CALLS
+#ifdef CANNOT_SAVE_CCR_ACROSS_CALLS
+  // 
+  // *** DISABLING THIS BECAUSE SAVING %CCR ACROSS CALLS WORKS NOW.
+  // *** DELETE THIS CODE AFTER SOME TESTING.
+  // *** NOTE: THIS CODE IS BROKEN ANYWAY WHEN THE SETCC IS NOT JUST
+  // ***       BEFORE THE BRANCH.
+  // -- Vikram Adve, 7/7/02.
+  // 
   // If the terminator is a conditional branch, insert the trace code just
   // before the instruction that computes the branch condition (just to
   // avoid putting a call between the CC-setting instruction and the branch).
@@ -345,55 +356,54 @@ static void TraceValuesAtBBExit(BasicBlock *BB,
     if (!Branch->isUnconditional())
       if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
         if (I->getParent() == BB) {
-          SetCC = I;
-          while (*InsertPos != SetCC)
-            --InsertPos;        // Back up until we can insert before the setcc
+          InsertPos = SetCC = I; // Back up until we can insert before the setcc
         }
-
-  // Copy all of the instructions into a vector to avoid problems with Setcc
-  const vector<Instruction*> Insts(BB->begin(), InsertPos);
+#endif CANNOT_SAVE_CCR_ACROSS_CALLS
 
   std::ostringstream OutStr;
   WriteAsOperand(OutStr, BB, false);
   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
                   Printf, HashPtrToSeqNum);
 
-  // Insert a print instruction for each value.
+  // Insert a print instruction for each instruction preceding InsertPos.
+  // The print instructions must go before InsertPos, so we use the
+  // instruction *preceding* InsertPos to check when to terminate the loop.
   // 
-  for (vector<Instruction*>::const_iterator II = Insts.begin(),
-         IE = Insts.end(); II != IE; ++II) {
-    Instruction *I = *II;
-    if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
-      assert(valuesStoredInFunction &&
-             "Should not be printing a store instruction at function exit");
-      LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
-                                  "reload");
-      InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
-      valuesStoredInFunction->push_back(LI);
-    }
-    if (ShouldTraceValue(I))
-      InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
+  if (InsertPos != BB->begin()) { // there's at least one instr before InsertPos
+    BasicBlock::iterator II = BB->begin(), IEincl = InsertPos;
+    --IEincl;
+    do {                          // do from II up to IEincl, inclusive
+      if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
+        assert(valuesStoredInFunction &&
+               "Should not be printing a store instruction at function exit");
+        LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
+                                  "reload."+SI->getPointerOperand()->getName());
+        InsertPos = ++BB->getInstList().insert(InsertPos, LI);
+        valuesStoredInFunction->push_back(LI);
+      }
+      if (ShouldTraceValue(II))
+        InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf,HashPtrToSeqNum);
+    } while (II++ != IEincl);
   }
 }
 
 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
                                                  Function* HashPtrToSeqNum){
   // Get an iterator to point to the insertion location
-  BasicBlock *BB = M->getEntryNode();
-  BasicBlock::iterator BBI = BB->begin();
+  BasicBlock &BB = M->getEntryNode();
+  BasicBlock::iterator BBI = BB.begin();
 
   std::ostringstream OutStr;
   WriteAsOperand(OutStr, M, true);
-  InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
+  InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
                   Printf, HashPtrToSeqNum);
 
   // Now print all the incoming arguments
-  const Function::ArgumentListType &argList = M->getArgumentList();
   unsigned ArgNo = 0;
-  for (Function::ArgumentListType::const_iterator
-         I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
-    InsertVerbosePrintInst((Value*)*I, BB, BBI,
-                           "  Arg #" + utostr(ArgNo), Printf, HashPtrToSeqNum);
+  for (Function::aiterator I = M->abegin(), E = M->aend(); I != E; ++I,++ArgNo){
+    InsertVerbosePrintInst(I, &BB, BBI,
+                           "  Arg #" + utostr(ArgNo) + ": ", Printf,
+                           HashPtrToSeqNum);
   }
 }
 
@@ -402,8 +412,8 @@ static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
                                                 Function *Printf,
                                                 Function* HashPtrToSeqNum) {
   // Get an iterator to point to the insertion location
-  BasicBlock::iterator BBI = BB->end()-1;
-  ReturnInst *Ret = cast<ReturnInst>(*BBI);
+  BasicBlock::iterator BBI = --BB->end();
+  ReturnInst &Ret = cast<ReturnInst>(BB->back());
   
   std::ostringstream OutStr;
   WriteAsOperand(OutStr, BB->getParent(), true);
@@ -412,7 +422,7 @@ static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
   
   // print the return value, if any
   if (BB->getParent()->getReturnType() != Type::VoidTy)
-    InsertPrintInst(Ret->getReturnValue(), BB, BBI, "  Returning: ",
+    InsertPrintInst(Ret.getReturnValue(), BB, BBI, "  Returning: ",
                     Printf, HashPtrToSeqNum);
 }
 
@@ -435,11 +445,10 @@ bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
                                   externalFuncs.HashPtrFunc);
   
   // Push a pointer set for recording alloca'd pointers at entry.
-  if (TraceHashPtrs == HashToSeqNum)
+  if (!DisablePtrHashing)
     InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
   
-  for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
-    BasicBlock *BB = *BI;
+  for (Function::iterator BB = M->begin(); BB != M->end(); ++BB) {
     if (isa<ReturnInst>(BB->getTerminator()))
       exitBlocks.push_back(BB); // record this as an exit block
     
@@ -447,7 +456,7 @@ bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
                           externalFuncs.HashPtrFunc, &valuesStoredInFunction);
     
-    if (TraceHashPtrs == HashToSeqNum)  // release seq. numbers on free/ret
+    if (!DisablePtrHashing)          // release seq. numbers on free/ret
       ReleasePtrSeqNumbers(BB, externalFuncs);
   }
   
@@ -459,7 +468,7 @@ bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
                                      externalFuncs.HashPtrFunc);
       
       // Release all recorded pointers before RETURN.  Do this LAST!
-      if (TraceHashPtrs == HashToSeqNum)
+      if (!DisablePtrHashing)
         InsertReleaseRecordedInst(exitBlocks[i],
                                   externalFuncs.ReleaseOnReturnFunc);
     }