MEGAPATCH checkin.

For details, See: docs/2002-06-25-MegaPatchInfo.txt


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@2779 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Transforms/ExprTypeConvert.cpp b/lib/Transforms/ExprTypeConvert.cpp
index a1f6425..a6106b0 100644
--- a/lib/Transforms/ExprTypeConvert.cpp
+++ b/lib/Transforms/ExprTypeConvert.cpp
@@ -31,7 +31,7 @@
 static bool AllIndicesZero(const MemAccessInst *MAI) {
   for (User::const_op_iterator S = MAI->idx_begin(), E = MAI->idx_end();
        S != E; ++S)
-    if (!isa<Constant>(*S) || !cast<Constant>(*S)->isNullValue())
+    if (!isa<Constant>(S->get()) || !cast<Constant>(S->get())->isNullValue())
       return false;
   return true;
 }
@@ -110,7 +110,7 @@
   unsigned Scale  = (unsigned)ScaleVal  * OldTypeSize / DataSize;
 
   // Locate the malloc instruction, because we may be inserting instructions
-  It = find(BB->getInstList().begin(), BB->getInstList().end(), MI);
+  It = MI;
 
   // If we have a scale, apply it first...
   if (Expr.Var) {
@@ -118,7 +118,7 @@
     if (Expr.Var->getType() != Type::UIntTy) {
       Instruction *CI = new CastInst(Expr.Var, Type::UIntTy);
       if (Expr.Var->hasName()) CI->setName(Expr.Var->getName()+"-uint");
-      It = BB->getInstList().insert(It, CI)+1;
+      It = ++BB->getInstList().insert(It, CI);
       Expr.Var = CI;
     }
 
@@ -127,7 +127,7 @@
         BinaryOperator::create(Instruction::Mul, Expr.Var,
                                ConstantUInt::get(Type::UIntTy, Scale));
       if (Expr.Var->hasName()) ScI->setName(Expr.Var->getName()+"-scl");
-      It = BB->getInstList().insert(It, ScI)+1;
+      It = ++BB->getInstList().insert(It, ScI);
       Expr.Var = ScI;
     }
 
@@ -145,7 +145,7 @@
       BinaryOperator::create(Instruction::Add, Expr.Var,
                              ConstantUInt::get(Type::UIntTy, Offset));
     if (Expr.Var->hasName()) AddI->setName(Expr.Var->getName()+"-off");
-    It = BB->getInstList().insert(It, AddI)+1;
+    It = ++BB->getInstList().insert(It, AddI);
     Expr.Var = AddI;
   }
 
@@ -193,9 +193,10 @@
     // We also do not allow conversion of a cast that casts from a ptr to array
     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
     //
-    if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
-      if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
-        if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
+    if (const PointerType *SPT = 
+        dyn_cast<PointerType>(I->getOperand(0)->getType()))
+      if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
+        if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
           if (AT->getElementType() == DPT->getElementType())
             return false;
     break;
@@ -475,7 +476,7 @@
       // and we could convert this to an appropriate GEP for the new type.
       //
       const PointerType *NewSrcTy = PointerType::get(PVTy);
-      BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+      BasicBlock::iterator It = I;
 
       // Check to see if 'N' is an expression that can be converted to
       // the appropriate size... if so, allow it.
@@ -519,9 +520,7 @@
 
   assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
 
-  BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
-  assert(It != BIL.end() && "Instruction not in own basic block??");
-  BIL.insert(It, Res);
+  BIL.insert(I, Res);
 
   // Add the instruction to the expression map
   VMC.ExprMap[I] = Res;
@@ -618,9 +617,10 @@
     // We also do not allow conversion of a cast that casts from a ptr to array
     // of X to a *X.  For example: cast [4 x %List *] * %val to %List * *
     //
-    if (PointerType *SPT = dyn_cast<PointerType>(I->getOperand(0)->getType()))
-      if (PointerType *DPT = dyn_cast<PointerType>(I->getType()))
-        if (ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
+    if (const PointerType *SPT = 
+        dyn_cast<PointerType>(I->getOperand(0)->getType()))
+      if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
+        if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
           if (AT->getElementType() == DPT->getElementType())
             return false;
     return true;
@@ -719,7 +719,7 @@
         // a whole structure at a time), so the level raiser must be trying to
         // store into the first field.  Check for this and allow it now:
         //
-        if (StructType *SElTy = dyn_cast<StructType>(ElTy)) {
+        if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
           unsigned Offset = 0;
           std::vector<Value*> Indices;
           ElTy = getStructOffsetType(ElTy, Offset, Indices, false);
@@ -817,9 +817,9 @@
 
     // Are we trying to change the function pointer value to a new type?
     if (OpNum == 0) {
-      PointerType *PTy = dyn_cast<PointerType>(Ty);
+      const PointerType *PTy = dyn_cast<PointerType>(Ty);
       if (PTy == 0) return false;  // Can't convert to a non-pointer type...
-      FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
+      const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
       if (MTy == 0) return false;  // Can't convert to a non ptr to function...
 
       // Perform sanity checks to make sure that new function type has the
@@ -926,7 +926,7 @@
     if (isa<PointerType>(NewTy)) {
       Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
       std::vector<Value*> Indices;
-      BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+      BasicBlock::iterator It = I;
 
       if (const Type *ETy = ConvertableToGEP(NewTy, IndexVal, Indices, &It)) {
         // If successful, convert the add to a GEP
@@ -1016,7 +1016,7 @@
     // Convert a one index getelementptr into just about anything that is
     // desired.
     //
-    BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+    BasicBlock::iterator It = I;
     const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
     unsigned DataSize = TD.getTypeSize(OldElTy);
     Value *Index = I->getOperand(1);
@@ -1025,7 +1025,7 @@
       // Insert a multiply of the old element type is not a unit size...
       Index = BinaryOperator::create(Instruction::Mul, Index,
                                      ConstantUInt::get(Type::UIntTy, DataSize));
-      It = BIL.insert(It, cast<Instruction>(Index))+1;
+      It = ++BIL.insert(It, cast<Instruction>(Index));
     }
 
     // Perform the conversion now...
@@ -1042,7 +1042,7 @@
       // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
       // anything that is a pointer type...
       //
-      BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+      BasicBlock::iterator It = I;
     
       // Check to see if the second argument is an expression that can
       // be converted to the appropriate size... if so, allow it.
@@ -1086,8 +1086,8 @@
     std::vector<Value*> Params(I->op_begin()+1, I->op_end());
 
     if (Meth == OldVal) {   // Changing the function pointer?
-      PointerType *NewPTy = cast<PointerType>(NewVal->getType());
-      FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
+      const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
+      const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
       const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
 
       // Get an iterator to the call instruction so that we can insert casts for
@@ -1096,7 +1096,7 @@
       // compatible.  The reason for this is that we prefer to have resolved
       // functions but casted arguments if possible.
       //
-      BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+      BasicBlock::iterator It = I;
 
       // Convert over all of the call operands to their new types... but only
       // convert over the part that is not in the vararg section of the call.
@@ -1107,7 +1107,7 @@
           // is a lossless cast...
           //
           Params[i] = new CastInst(Params[i], PTs[i], "call.resolve.cast");
-          It = BIL.insert(It, cast<Instruction>(Params[i]))+1;
+          It = ++BIL.insert(It, cast<Instruction>(Params[i]));
         }
       Meth = NewVal;  // Update call destination to new value
 
@@ -1130,7 +1130,7 @@
   // If the instruction was newly created, insert it into the instruction
   // stream.
   //
-  BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
+  BasicBlock::iterator It = I;
   assert(It != BIL.end() && "Instruction not in own basic block??");
   BIL.insert(It, Res);   // Keep It pointing to old instruction
 
@@ -1186,7 +1186,7 @@
 
   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); 
        OI != OE; ++OI)
-    if (Instruction *U = dyn_cast<Instruction>(*OI)) {
+    if (Instruction *U = dyn_cast<Instruction>(OI->get())) {
       *OI = 0;
       RecursiveDelete(Cache, U);
     }
diff --git a/lib/Transforms/IPO/FunctionResolution.cpp b/lib/Transforms/IPO/FunctionResolution.cpp
index 9eb6e54..6cb901b 100644
--- a/lib/Transforms/IPO/FunctionResolution.cpp
+++ b/lib/Transforms/IPO/FunctionResolution.cpp
@@ -13,8 +13,6 @@
 
 #include "llvm/Transforms/CleanupGCCOutput.h"
 #include "llvm/Module.h"
-#include "llvm/Function.h"
-#include "llvm/BasicBlock.h"
 #include "llvm/SymbolTable.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Pass.h"
@@ -34,7 +32,7 @@
   struct FunctionResolvingPass : public Pass {
     const char *getPassName() const { return "Resolve Functions"; }
 
-    bool run(Module *M);
+    bool run(Module &M);
   };
 }
 
@@ -50,12 +48,10 @@
     Dest->getFunctionType()->getParamTypes();
   BasicBlock *BB = CI->getParent();
 
-  // Get an iterator to where we want to insert cast instructions if the
+  // Keep an iterator to where we want to insert cast instructions if the
   // argument types don't agree.
   //
-  BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
-  assert(BBI != BB->end() && "CallInst not in parent block?");
-
+  BasicBlock::iterator BBI = CI;
   assert(CI->getNumOperands()-1 == ParamTys.size() &&
          "Function calls resolved funny somehow, incompatible number of args");
 
@@ -68,7 +64,7 @@
 
     if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
       Instruction *Cast = new CastInst(V, ParamTys[i-1]);
-      BBI = BB->getInstList().insert(BBI, Cast)+1;
+      BBI = ++BB->getInstList().insert(BBI, Cast);
       V = Cast;
     }
 
@@ -80,7 +76,7 @@
   // Replace the old call instruction with a new call instruction that calls
   // the real function.
   //
-  BBI = BB->getInstList().insert(BBI, NewCall)+1;
+  BBI = ++BB->getInstList().insert(BBI, NewCall);
 
   // Remove the old call instruction from the program...
   BB->getInstList().remove(BBI);
@@ -110,8 +106,8 @@
 }
 
 
-bool FunctionResolvingPass::run(Module *M) {
-  SymbolTable *ST = M->getSymbolTable();
+bool FunctionResolvingPass::run(Module &M) {
+  SymbolTable *ST = M.getSymbolTable();
   if (!ST) return false;
 
   std::map<string, vector<Function*> > Functions;
@@ -151,9 +147,8 @@
         // warnings... here we will actually DCE the function so that it isn't
         // used later.
         //
-        if (Functions[i]->use_size() == 0) {
-          M->getFunctionList().remove(Functions[i]);
-          delete Functions[i];
+        if (Functions[i]->use_empty()) {
+          M.getFunctionList().erase(Functions[i]);
           Functions.erase(Functions.begin()+i);
           Changed = true;
           ++NumResolved;
diff --git a/lib/Transforms/IPO/InlineSimple.cpp b/lib/Transforms/IPO/InlineSimple.cpp
index 12430e1..7d36e37 100644
--- a/lib/Transforms/IPO/InlineSimple.cpp
+++ b/lib/Transforms/IPO/InlineSimple.cpp
@@ -20,18 +20,16 @@
 
 #include "llvm/Transforms/FunctionInlining.h"
 #include "llvm/Module.h"
-#include "llvm/Function.h"
 #include "llvm/Pass.h"
 #include "llvm/iTerminators.h"
 #include "llvm/iPHINode.h"
 #include "llvm/iOther.h"
 #include "llvm/Type.h"
-#include "llvm/Argument.h"
 #include "Support/StatisticReporter.h"
-
-static Statistic<> NumInlined("inline\t\t- Number of functions inlined");
 #include <algorithm>
 #include <iostream>
+
+static Statistic<> NumInlined("inline\t\t- Number of functions inlined");
 using std::cerr;
 
 // RemapInstruction - Convert the instruction operands from referencing the 
@@ -65,17 +63,16 @@
 // exists in the instruction stream.  Similiarly this will inline a recursive
 // function by one level.
 //
-bool InlineFunction(BasicBlock::iterator CIIt) {
-  assert(isa<CallInst>(*CIIt) && "InlineFunction only works on CallInst nodes");
-  assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
-  assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
+bool InlineFunction(CallInst *CI) {
+  assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
+  assert(CI->getParent() && "Instruction not embedded in basic block!");
+  assert(CI->getParent()->getParent() && "Instruction not in function!");
 
-  CallInst *CI = cast<CallInst>(*CIIt);
-  const Function *CalledMeth = CI->getCalledFunction();
-  if (CalledMeth == 0 ||   // Can't inline external function or indirect call!
-      CalledMeth->isExternal()) return false;
+  const Function *CalledFunc = CI->getCalledFunction();
+  if (CalledFunc == 0 ||   // Can't inline external function or indirect call!
+      CalledFunc->isExternal()) return false;
 
-  //cerr << "Inlining " << CalledMeth->getName() << " into " 
+  //cerr << "Inlining " << CalledFunc->getName() << " into " 
   //     << CurrentMeth->getName() << "\n";
 
   BasicBlock *OrigBB = CI->getParent();
@@ -84,7 +81,7 @@
   // immediately before the call.  The original basic block now ends with an
   // unconditional branch to NewBB, and NewBB starts with the call instruction.
   //
-  BasicBlock *NewBB = OrigBB->splitBasicBlock(CIIt);
+  BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
   NewBB->setName("InlinedFunctionReturnNode");
 
   // Remove (unlink) the CallInst from the start of the new basic block.  
@@ -95,8 +92,8 @@
   // function.
   //
   PHINode *PHI = 0;
-  if (CalledMeth->getReturnType() != Type::VoidTy) {
-    PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
+  if (CalledFunc->getReturnType() != Type::VoidTy) {
+    PHI = new PHINode(CalledFunc->getReturnType(), CI->getName());
 
     // The PHI node should go at the front of the new basic block to merge all 
     // possible incoming values.
@@ -118,19 +115,17 @@
   // Add the function arguments to the mapping: (start counting at 1 to skip the
   // function reference itself)
   //
-  Function::ArgumentListType::const_iterator PTI = 
-    CalledMeth->getArgumentList().begin();
+  Function::const_aiterator PTI = CalledFunc->abegin();
   for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
-    ValueMap[*PTI] = CI->getOperand(a);
+    ValueMap[PTI] = CI->getOperand(a);
   
   ValueMap[NewBB] = NewBB;  // Returns get converted to reference NewBB
 
   // Loop over all of the basic blocks in the function, inlining them as 
   // appropriate.  Keep track of the first basic block of the function...
   //
-  for (Function::const_iterator BI = CalledMeth->begin(); 
-       BI != CalledMeth->end(); ++BI) {
-    const BasicBlock *BB = *BI;
+  for (Function::const_iterator BB = CalledFunc->begin(); 
+       BB != CalledFunc->end(); ++BB) {
     assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
     
     // Create a new basic block to copy instructions into!
@@ -148,23 +143,24 @@
     // Loop over all instructions copying them over...
     Instruction *NewInst;
     for (BasicBlock::const_iterator II = BB->begin();
-	 II != (BB->end()-1); ++II) {
-      IBB->getInstList().push_back((NewInst = (*II)->clone()));
-      ValueMap[*II] = NewInst;                  // Add instruction map to value.
-      if ((*II)->hasName())
-        NewInst->setName((*II)->getName()+".i");  // .i = inlined once
+	 II != --BB->end(); ++II) {
+      IBB->getInstList().push_back((NewInst = II->clone()));
+      ValueMap[II] = NewInst;                  // Add instruction map to value.
+      if (II->hasName())
+        NewInst->setName(II->getName()+".i");  // .i = inlined once
     }
 
     // Copy over the terminator now...
     switch (TI->getOpcode()) {
     case Instruction::Ret: {
-      const ReturnInst *RI = cast<const ReturnInst>(TI);
+      const ReturnInst *RI = cast<ReturnInst>(TI);
 
       if (PHI) {   // The PHI node should include this value!
 	assert(RI->getReturnValue() && "Ret should have value!");
 	assert(RI->getReturnValue()->getType() == PHI->getType() && 
 	       "Ret value not consistent in function!");
-	PHI->addIncoming((Value*)RI->getReturnValue(), cast<BasicBlock>(BB));
+	PHI->addIncoming((Value*)RI->getReturnValue(),
+                         (BasicBlock*)cast<BasicBlock>(&*BB));
       }
 
       // Add a branch to the code that was after the original Call.
@@ -185,15 +181,14 @@
   // Loop over all of the instructions in the function, fixing up operand 
   // references as we go.  This uses ValueMap to do all the hard work.
   //
-  for (Function::const_iterator BI = CalledMeth->begin(); 
-       BI != CalledMeth->end(); ++BI) {
-    const BasicBlock *BB = *BI;
+  for (Function::const_iterator BB = CalledFunc->begin(); 
+       BB != CalledFunc->end(); ++BB) {
     BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
 
     // Loop over all instructions, fixing each one as we find it...
     //
-    for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
-      RemapInstruction(*II, ValueMap);
+    for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
+      RemapInstruction(II, ValueMap);
   }
 
   if (PHI) RemapInstruction(PHI, ValueMap);  // Fix the PHI node also...
@@ -204,24 +199,13 @@
   TerminatorInst *Br = OrigBB->getTerminator();
   assert(Br && Br->getOpcode() == Instruction::Br && 
 	 "splitBasicBlock broken!");
-  Br->setOperand(0, ValueMap[CalledMeth->front()]);
+  Br->setOperand(0, ValueMap[&CalledFunc->front()]);
 
   // Since we are now done with the CallInst, we can finally delete it.
   delete CI;
   return true;
 }
 
-bool InlineFunction(CallInst *CI) {
-  assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
-  BasicBlock *PBB = CI->getParent();
-
-  BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
-
-  assert(CallIt != PBB->end() && 
-	 "CallInst has parent that doesn't contain CallInst?!?");
-  return InlineFunction(CallIt);
-}
-
 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
   assert(CI->getParent() && CI->getParent()->getParent() && 
 	 "Call not embedded into a function!");
@@ -242,11 +226,12 @@
 
 static inline bool DoFunctionInlining(BasicBlock *BB) {
   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
-    if (CallInst *CI = dyn_cast<CallInst>(*I)) {
+    if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
       // Check to see if we should inline this function
       Function *F = CI->getCalledFunction();
-      if (F && ShouldInlineFunction(CI, F))
-	return InlineFunction(I);
+      if (F && ShouldInlineFunction(CI, F)) {
+	return InlineFunction(CI);
+      }
     }
   }
   return false;
@@ -255,16 +240,14 @@
 // doFunctionInlining - Use a heuristic based approach to inline functions that
 // seem to look good.
 //
-static bool doFunctionInlining(Function *F) {
+static bool doFunctionInlining(Function &F) {
   bool Changed = false;
 
   // Loop through now and inline instructions a basic block at a time...
-  for (Function::iterator I = F->begin(); I != F->end(); )
-    if (DoFunctionInlining(*I)) {
+  for (Function::iterator I = F.begin(); I != F.end(); )
+    if (DoFunctionInlining(I)) {
       ++NumInlined;
       Changed = true;
-      // Iterator is now invalidated by new basic blocks inserted
-      I = F->begin();
     } else {
       ++I;
     }
@@ -275,7 +258,7 @@
 namespace {
   struct FunctionInlining : public FunctionPass {
     const char *getPassName() const { return "Function Inlining"; }
-    virtual bool runOnFunction(Function *F) {
+    virtual bool runOnFunction(Function &F) {
       return doFunctionInlining(F);
     }
   };
diff --git a/lib/Transforms/IPO/RaiseAllocations.cpp b/lib/Transforms/IPO/RaiseAllocations.cpp
index 5dc1254..42e1a28 100644
--- a/lib/Transforms/IPO/RaiseAllocations.cpp
+++ b/lib/Transforms/IPO/RaiseAllocations.cpp
@@ -33,12 +33,12 @@
   // doPassInitialization - For the raise allocations pass, this finds a
   // declaration for malloc and free if they exist.
   //
-  bool doInitialization(Module *M);
+  bool doInitialization(Module &M);
 
   // runOnBasicBlock - This method does the actual work of converting
   // instructions over, assuming that the pass has already been initialized.
   //
-  bool runOnBasicBlock(BasicBlock *BB);
+  bool runOnBasicBlock(BasicBlock &BB);
 };
 
 }  // end anonymous namespace
@@ -50,7 +50,7 @@
 }
 
 
-bool RaiseAllocations::doInitialization(Module *M) {
+bool RaiseAllocations::doInitialization(Module &M) {
   // If the module has a symbol table, they might be referring to the malloc
   // and free functions.  If this is the case, grab the method pointers that 
   // the module is using.
@@ -68,22 +68,22 @@
                    std::vector<const Type*>(1, PointerType::get(Type::SByteTy)),
                       false);
 
-  MallocFunc = M->getFunction("malloc", MallocType);
-  FreeFunc   = M->getFunction("free"  , FreeType);
+  MallocFunc = M.getFunction("malloc", MallocType);
+  FreeFunc   = M.getFunction("free"  , FreeType);
 
   // Check to see if the prototype is missing, giving us sbyte*(...) * malloc
   // This handles the common declaration of: 'char *malloc();'
   if (MallocFunc == 0) {
     MallocType = FunctionType::get(PointerType::get(Type::SByteTy),
                                    std::vector<const Type*>(), true);
-    MallocFunc = M->getFunction("malloc", MallocType);
+    MallocFunc = M.getFunction("malloc", MallocType);
   }
 
   // Check to see if the prototype was forgotten, giving us void (...) * free
   // This handles the common forward declaration of: 'void free();'
   if (FreeFunc == 0) {
     FreeType = FunctionType::get(Type::VoidTy, std::vector<const Type*>(),true);
-    FreeFunc = M->getFunction("free", FreeType);
+    FreeFunc = M.getFunction("free", FreeType);
   }
 
 
@@ -95,12 +95,12 @@
 
 // runOnBasicBlock - Process a basic block, fixing it up...
 //
-bool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {
+bool RaiseAllocations::runOnBasicBlock(BasicBlock &BB) {
   bool Changed = false;
-  BasicBlock::InstListType &BIL = BB->getInstList();
+  BasicBlock::InstListType &BIL = BB.getInstList();
 
-  for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
-    Instruction *I = *BI;
+  for (BasicBlock::iterator BI = BB.begin(); BI != BB.end();) {
+    Instruction *I = BI;
 
     if (CallInst *CI = dyn_cast<CallInst>(I)) {
       if (CI->getCalledValue() == MallocFunc) {      // Replace call to malloc?
@@ -111,7 +111,7 @@
         // source size.
         if (Source->getType() != Type::UIntTy) {
           CastInst *New = new CastInst(Source, Type::UIntTy, "MallocAmtCast");
-          BI = BIL.insert(BI, New)+1;
+          BI = ++BIL.insert(BI, New);
           Source = New;
         }
 
@@ -132,7 +132,7 @@
         if (!isa<PointerType>(Source->getType())) {
           CastInst *New = new CastInst(Source, PointerType::get(Type::SByteTy),
                                        "FreePtrCast");
-          BI = BIL.insert(BI, New)+1;
+          BI = ++BIL.insert(BI, New);
           Source = New;
         }
 
diff --git a/lib/Transforms/Instrumentation/TraceValues.cpp b/lib/Transforms/Instrumentation/TraceValues.cpp
index 079edce..92aff12 100644
--- a/lib/Transforms/Instrumentation/TraceValues.cpp
+++ b/lib/Transforms/Instrumentation/TraceValues.cpp
@@ -49,7 +49,7 @@
   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 {
@@ -64,7 +64,7 @@
     
     // Add a prototype for runtime functions not already in the program.
     //
-    bool doInitialization(Module *M);
+    bool doInitialization(Module &M);
     
     //--------------------------------------------------------------------------
     // Function InsertCodeToTraceValues
@@ -77,8 +77,8 @@
 
     // 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 {
@@ -98,36 +98,36 @@
 
 // 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);
+  PrintfFunc = M.getOrInsertFunction("printf", MTy);
 
   // uint (sbyte*)
   const FunctionType *hashFuncTy =
     FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
-  HashPtrFunc = M->getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
+  HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
   
   // void (sbyte*)
   const FunctionType *voidSBPFuncTy =
     FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
   
-  ReleasePtrFunc =M->getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
-  RecordPtrFunc = M->getOrInsertFunction("RecordPointer", voidSBPFuncTy);
+  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;
 }
@@ -214,20 +214,20 @@
     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()) && !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)+1;
+      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:
@@ -235,7 +235,7 @@
   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);
 }
                             
 
@@ -257,12 +257,12 @@
   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)+1;
+    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 
@@ -272,29 +272,29 @@
     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)+1;
+    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.
@@ -306,13 +306,13 @@
                      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;
       }
   }
 }  
@@ -335,8 +335,8 @@
   // 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(BB->back().isTerminator());
   
   // If the terminator is a conditional branch, insert the trace code just
   // before the instruction that computes the branch condition (just to
@@ -349,14 +349,9 @@
     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);
-
   std::ostringstream OutStr;
   WriteAsOperand(OutStr, BB, false);
   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
@@ -364,39 +359,35 @@
 
   // Insert a print instruction for each value.
   // 
-  for (vector<Instruction*>::const_iterator II = Insts.begin(),
-         IE = Insts.end(); II != IE; ++II) {
-    Instruction *I = *II;
-    if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
+  for (BasicBlock::iterator II = BB->begin(), IE = InsertPos++; II != IE; ++II){
+    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");
-      InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
+                                  "reload."+SI->getPointerOperand()->getName());
+      InsertPos = ++BB->getInstList().insert(InsertPos, LI);
       valuesStoredInFunction->push_back(LI);
     }
-    if (ShouldTraceValue(I))
-      InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
+    if (ShouldTraceValue(II))
+      InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
   }
 }
 
 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,
+  for (Function::aiterator I = M->abegin(), E = M->aend(); I != E; ++I,++ArgNo){
+    InsertVerbosePrintInst(I, &BB, BBI,
                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
                            HashPtrToSeqNum);
   }
@@ -407,8 +398,8 @@
                                                 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);
@@ -417,7 +408,7 @@
   
   // 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);
 }
 
@@ -443,8 +434,7 @@
   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
     
diff --git a/lib/Transforms/LevelRaise.cpp b/lib/Transforms/LevelRaise.cpp
index b0bae97..c310034 100644
--- a/lib/Transforms/LevelRaise.cpp
+++ b/lib/Transforms/LevelRaise.cpp
@@ -58,13 +58,13 @@
 //
 static bool HandleCastToPointer(BasicBlock::iterator BI,
                                 const PointerType *DestPTy) {
-  CastInst *CI = cast<CastInst>(*BI);
-  if (CI->use_empty()) return false;
+  CastInst &CI = cast<CastInst>(*BI);
+  if (CI.use_empty()) return false;
 
   // Scan all of the uses, looking for any uses that are not add
   // instructions.  If we have non-adds, do not make this transformation.
   //
-  for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
+  for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
        I != E; ++I) {
     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
       if (BO->getOpcode() != Instruction::Add)
@@ -75,7 +75,7 @@
   }
 
   std::vector<Value*> Indices;
-  Value *Src = CI->getOperand(0);
+  Value *Src = CI.getOperand(0);
   const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
   if (Result == 0) return false;  // Not convertable...
 
@@ -83,13 +83,13 @@
 
   // If we have a getelementptr capability... transform all of the 
   // add instruction uses into getelementptr's.
-  while (!CI->use_empty()) {
-    BinaryOperator *I = cast<BinaryOperator>(*CI->use_begin());
+  while (!CI.use_empty()) {
+    BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
     assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
            "Use is not a valid add instruction!");
     
     // Get the value added to the cast result pointer...
-    Value *OtherPtr = I->getOperand((I->getOperand(0) == CI) ? 1 : 0);
+    Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
 
     Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
     PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
@@ -102,16 +102,14 @@
       // add instruction type, insert a cast now.
       //
 
-      // Insert the GEP instruction before the old add instruction... and get an
-      // iterator to point at the add instruction...
-      BasicBlock::iterator GEPI = InsertInstBeforeInst(GEP, I)+1;
+      // Insert the GEP instruction before the old add instruction...
+      I->getParent()->getInstList().insert(I, GEP);
 
       PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
-      CastInst *CI = new CastInst(GEP, I->getType());
-      GEP = CI;
+      GEP = new CastInst(GEP, I->getType());
 
       // Replace the old add instruction with the shiny new GEP inst
-      ReplaceInstWithInst(I->getParent()->getInstList(), GEPI, GEP);
+      ReplaceInstWithInst(I, GEP);
     }
 
     PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
@@ -160,7 +158,7 @@
 
   GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
                                                  AddOp2->getName());
-  BI = BB->getInstList().insert(BI, GEP)+1;
+  BI = ++BB->getInstList().insert(BI, GEP);
 
   Instruction *NCI = new CastInst(GEP, AddOp1->getType());
   ReplaceInstWithInst(BB->getInstList(), BI, NCI);
@@ -169,7 +167,7 @@
 }
 
 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
-  Instruction *I = *BI;
+  Instruction *I = BI;
 
   if (CastInst *CI = dyn_cast<CastInst>(I)) {
     Value       *Src    = CI->getOperand(0);
@@ -193,7 +191,7 @@
       // DCE the instruction now, to avoid having the iterative version of DCE
       // have to worry about it.
       //
-      delete BB->getInstList().remove(BI);
+      BI = BB->getInstList().erase(BI);
 
       ++NumCastOfCast;
       return true;
@@ -326,7 +324,7 @@
             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
                                                            CI->getName());
             CI->setName("");
-            BI = BB->getInstList().insert(BI, GEP)+1;
+            BI = ++BB->getInstList().insert(BI, GEP);
 
             // Make the old cast instruction reference the new GEP instead of
             // the old src value.
@@ -359,7 +357,7 @@
     //
     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
-        if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
+        if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
           // convertable types?
           if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
               !SI->hasIndices()) {      // No subscripts yet!
@@ -369,7 +367,7 @@
             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
                                          CI->getName());
             CI->setName("");
-            BI = BB->getInstList().insert(BI, NCI)+1;
+            BI = ++BB->getInstList().insert(BI, NCI);
 
             // Replace the old store with a new one!
             ReplaceInstWithInst(BB->getInstList(), BI,
@@ -399,7 +397,7 @@
     //
     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
-        if (PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
+        if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
           // convertable types?
           if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType()) &&
               !LI->hasIndices()) {      // No subscripts yet!
@@ -410,7 +408,7 @@
             
             // Insert the new T cast instruction... stealing old T's name
             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
-            BI = BB->getInstList().insert(BI, NewLI)+1;
+            BI = ++BB->getInstList().insert(BI, NewLI);
 
             // Replace the old store with a new one!
             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
@@ -435,24 +433,22 @@
 
 
 
-static bool DoRaisePass(Function *F) {
+static bool DoRaisePass(Function &F) {
   bool Changed = false;
-  for (Function::iterator MI = F->begin(), ME = F->end(); MI != ME; ++MI) {
-    BasicBlock *BB = *MI;
-    BasicBlock::InstListType &BIL = BB->getInstList();
-
+  for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
       DEBUG(cerr << "Processing: " << *BI);
       if (dceInstruction(BI) || doConstantPropogation(BI)) {
         Changed = true; 
         ++NumDCEorCP;
         DEBUG(cerr << "***\t\t^^-- DeadCode Elinated!\n");
-      } else if (PeepholeOptimize(BB, BI))
+      } else if (PeepholeOptimize(BB, BI)) {
         Changed = true;
-      else
+      } else {
         ++BI;
+      }
     }
-  }
+
   return Changed;
 }
 
@@ -460,8 +456,8 @@
 // RaisePointerReferences::doit - Raise a function representation to a higher
 // level.
 //
-static bool doRPR(Function *F) {
-  DEBUG(cerr << "\n\n\nStarting to work on Function '" << F->getName()<< "'\n");
+static bool doRPR(Function &F) {
+  DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
 
   // Insert casts for all incoming pointer pointer values that are treated as
   // arrays...
@@ -486,7 +482,7 @@
   struct RaisePointerReferences : public FunctionPass {
     const char *getPassName() const { return "Raise Pointer References"; }
 
-    virtual bool runOnFunction(Function *F) { return doRPR(F); }
+    virtual bool runOnFunction(Function &F) { return doRPR(F); }
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
diff --git a/lib/Transforms/Scalar/ADCE.cpp b/lib/Transforms/Scalar/ADCE.cpp
index 862ec5a..237c458 100644
--- a/lib/Transforms/Scalar/ADCE.cpp
+++ b/lib/Transforms/Scalar/ADCE.cpp
@@ -46,8 +46,8 @@
   
   // Execute the Aggressive Dead Code Elimination Algorithm
   //
-  virtual bool runOnFunction(Function *F) {
-    Func = F;
+  virtual bool runOnFunction(Function &F) {
+    Func = &F;
     bool Changed = doADCE();
     assert(WorkList.empty());
     LiveSet.clear();
@@ -126,14 +126,12 @@
        BBI != BBE; ++BBI) {
     BasicBlock *BB = *BBI;
     for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
-      Instruction *I = *II;
-
-      if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
-	markInstructionLive(I);
+      if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
+	markInstructionLive(II);
         ++II;  // Increment the inst iterator if the inst wasn't deleted
-      } else if (isInstructionTriviallyDead(I)) {
+      } else if (isInstructionTriviallyDead(II)) {
         // Remove the instruction from it's basic block...
-        delete BB->getInstList().remove(II);
+        II = BB->getInstList().erase(II);
         ++NumInstRemoved;
         MadeChanges = true;
       } else {
@@ -185,9 +183,8 @@
   if (DebugFlag) {
     cerr << "Current Function: X = Live\n";
     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
-      for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
-           BI != BE; ++BI) {
-        if (LiveSet.count(*BI)) cerr << "X ";
+      for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
+        if (LiveSet.count(BI)) cerr << "X ";
         cerr << *BI;
       }
   }
@@ -201,8 +198,8 @@
   if (AliveBlocks.size() != Func->size()) {
     // Insert a new entry node to eliminate the entry node as a special case.
     BasicBlock *NewEntry = new BasicBlock();
-    NewEntry->getInstList().push_back(new BranchInst(Func->front()));
-    Func->getBasicBlocks().push_front(NewEntry);
+    NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
+    Func->getBasicBlockList().push_front(NewEntry);
     AliveBlocks.insert(NewEntry);    // This block is always alive!
     
     // Loop over all of the alive blocks in the function.  If any successor
@@ -211,8 +208,8 @@
     // the block to reflect this.
     //
     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
-      if (AliveBlocks.count(*I)) {
-        BasicBlock *BB = *I;
+      if (AliveBlocks.count(I)) {
+        BasicBlock *BB = I;
         TerminatorInst *TI = BB->getTerminator();
       
         // Loop over all of the successors, looking for ones that are not alive
@@ -242,7 +239,7 @@
             // should be identical to the incoming values for LastDead.
             //
             for (BasicBlock::iterator II = NextAlive->begin();
-                 PHINode *PN = dyn_cast<PHINode>(*II); ++II) {
+                 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
               // Get the incoming value for LastDead...
               int OldIdx = PN->getBasicBlockIndex(LastDead);
               assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
@@ -258,17 +255,16 @@
         // sweep over the program can safely delete dead instructions without
         // other dead instructions still refering to them.
         //
-        for (BasicBlock::iterator I = BB->begin(), E = BB->end()-1; I != E; ++I)
-          if (!LiveSet.count(*I))               // Is this instruction alive?
-            (*I)->dropAllReferences();          // Nope, drop references... 
+        for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
+          if (!LiveSet.count(I))                // Is this instruction alive?
+            I->dropAllReferences();             // Nope, drop references... 
       }
   }
 
   // Loop over all of the basic blocks in the function, dropping references of
   // the dead basic blocks
   //
-  for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
-    BasicBlock *BB = *I;
+  for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
     if (!AliveBlocks.count(BB)) {
       // Remove all outgoing edges from this basic block and convert the
       // terminator into a return instruction.
@@ -283,7 +279,7 @@
         }
         
         // Delete the old terminator instruction...
-        delete BB->getInstList().remove(BB->end()-1);
+        BB->getInstList().pop_back();
         const Type *RetTy = Func->getReturnType();
         Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
                                           Constant::getNullValue(RetTy) : 0);
@@ -302,14 +298,13 @@
   // instructions from alive blocks.
   //
   for (Function::iterator BI = Func->begin(); BI != Func->end(); )
-    if (!AliveBlocks.count(*BI))
-      delete Func->getBasicBlocks().remove(BI);
+    if (!AliveBlocks.count(BI))
+      BI = Func->getBasicBlockList().erase(BI);
     else {
-      BasicBlock *BB = *BI;
-      for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
-        if (!LiveSet.count(*II)) {             // Is this instruction alive?
+      for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
+        if (!LiveSet.count(II)) {             // Is this instruction alive?
           // Nope... remove the instruction from it's basic block...
-          delete BB->getInstList().remove(II);
+          II = BI->getInstList().erase(II);
           ++NumInstRemoved;
           MadeChanges = true;
         } else {
diff --git a/lib/Transforms/Scalar/ConstantProp.cpp b/lib/Transforms/Scalar/ConstantProp.cpp
index 720266c..51bd6cb 100644
--- a/lib/Transforms/Scalar/ConstantProp.cpp
+++ b/lib/Transforms/Scalar/ConstantProp.cpp
@@ -26,7 +26,7 @@
   struct ConstantPropogation : public FunctionPass {
     const char *getPassName() const { return "Simple Constant Propogation"; }
 
-    bool runOnFunction(Function *F);
+    bool runOnFunction(Function &F);
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
@@ -39,7 +39,7 @@
 }
 
 
-bool ConstantPropogation::runOnFunction(Function *F) {
+bool ConstantPropogation::runOnFunction(Function &F) {
   // Initialize the worklist to all of the instructions ready to process...
   std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
   bool Changed = false;
diff --git a/lib/Transforms/Scalar/DCE.cpp b/lib/Transforms/Scalar/DCE.cpp
index fa2392f..1f5def6 100644
--- a/lib/Transforms/Scalar/DCE.cpp
+++ b/lib/Transforms/Scalar/DCE.cpp
@@ -28,10 +28,9 @@
   struct DeadInstElimination : public BasicBlockPass {
     const char *getPassName() const { return "Dead Instruction Elimination"; }
     
-    virtual bool runOnBasicBlock(BasicBlock *BB) {
-      BasicBlock::InstListType &Vals = BB->getInstList();
+    virtual bool runOnBasicBlock(BasicBlock &BB) {
       bool Changed = false;
-      for (BasicBlock::iterator DI = Vals.begin(); DI != Vals.end(); )
+      for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); )
         if (dceInstruction(DI)) {
           Changed = true;
           ++DIEEliminated;
@@ -60,7 +59,7 @@
   struct DCE : public FunctionPass {
     const char *getPassName() const { return "Dead Code Elimination"; }
 
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
 
      virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
@@ -68,7 +67,7 @@
  };
 }
 
-bool DCE::runOnFunction(Function *F) {
+bool DCE::runOnFunction(Function &F) {
   // Start out with all of the instructions in the worklist...
   std::vector<Instruction*> WorkList(inst_begin(F), inst_end(F));
   std::set<Instruction*> DeadInsts;
@@ -103,16 +102,14 @@
   if (DeadInsts.empty()) return false;
 
   // Otherwise, loop over the program, removing and deleting the instructions...
-  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
-    BasicBlock::InstListType &BBIL = (*I)->getInstList();
-    for (BasicBlock::iterator BI = BBIL.begin(); BI != BBIL.end(); )
-      if (DeadInsts.count(*BI)) {            // Is this instruction dead?
-        delete BBIL.remove(BI);              // Yup, remove and delete inst
+  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+    for (BasicBlock::iterator BI = I->begin(); BI != I->end(); )
+      if (DeadInsts.count(BI)) {             // Is this instruction dead?
+        BI = I->getInstList().erase(BI);     // Yup, remove and delete inst
         ++DCEEliminated;
       } else {                               // This instruction is not dead
         ++BI;                                // Continue on to the next one...
       }
-  }
 
   return true;
 }
diff --git a/lib/Transforms/Scalar/DecomposeMultiDimRefs.cpp b/lib/Transforms/Scalar/DecomposeMultiDimRefs.cpp
index 90301f8..ab6059a 100644
--- a/lib/Transforms/Scalar/DecomposeMultiDimRefs.cpp
+++ b/lib/Transforms/Scalar/DecomposeMultiDimRefs.cpp
@@ -23,7 +23,7 @@
   struct DecomposePass : public BasicBlockPass {
     const char *getPassName() const { return "Decompose Subscripting Exps"; }
 
-    virtual bool runOnBasicBlock(BasicBlock *BB);
+    virtual bool runOnBasicBlock(BasicBlock &BB);
 
   private:
     static void decomposeArrayRef(BasicBlock::iterator &BBI);
@@ -38,10 +38,10 @@
 // runOnBasicBlock - Entry point for array or structure references with multiple
 // indices.
 //
-bool DecomposePass::runOnBasicBlock(BasicBlock *BB) {
+bool DecomposePass::runOnBasicBlock(BasicBlock &BB) {
   bool Changed = false;
-  for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ) {
-    if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*II)) {
+  for (BasicBlock::iterator II = BB.begin(); II != BB.end(); ) {
+    if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(&*II)) {
       if (MAI->getNumOperands() > MAI->getFirstIndexOperandNumber()+1) {
         decomposeArrayRef(II);
         Changed = true;
@@ -67,9 +67,9 @@
 // If any index is (uint) 0, we omit the getElementPtr instruction.
 // 
 void DecomposePass::decomposeArrayRef(BasicBlock::iterator &BBI) {
-  MemAccessInst *MAI = cast<MemAccessInst>(*BBI);
-  BasicBlock *BB = MAI->getParent();
-  Value *LastPtr = MAI->getPointerOperand();
+  MemAccessInst &MAI = cast<MemAccessInst>(*BBI);
+  BasicBlock *BB = MAI.getParent();
+  Value *LastPtr = MAI.getPointerOperand();
 
   // Remove the instruction from the stream
   BB->getInstList().remove(BBI);
@@ -78,22 +78,22 @@
   
   // Process each index except the last one.
   // 
-  User::const_op_iterator OI = MAI->idx_begin(), OE = MAI->idx_end();
+  User::const_op_iterator OI = MAI.idx_begin(), OE = MAI.idx_end();
   for (; OI+1 != OE; ++OI) {
     assert(isa<PointerType>(LastPtr->getType()));
       
     // Check for a zero index.  This will need a cast instead of
     // a getElementPtr, or it may need neither.
     bool indexIsZero = isa<Constant>(*OI) && 
-                       cast<Constant>(*OI)->isNullValue() &&
-                       (*OI)->getType() == Type::UIntTy;
+                       cast<Constant>(OI->get())->isNullValue() &&
+                       OI->get()->getType() == Type::UIntTy;
       
     // Extract the first index.  If the ptr is a pointer to a structure
     // and the next index is a structure offset (i.e., not an array offset), 
     // we need to include an initial [0] to index into the pointer.
     //
     vector<Value*> Indices;
-    PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
+    const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
     if (isa<StructType>(PtrTy->getElementType())
         && !PtrTy->indexValid(*OI))
       Indices.push_back(Constant::getNullValue(Type::UIntTy));
@@ -131,7 +131,7 @@
   // 
   // Now create a new instruction to replace the original one
   //
-  PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
+  const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
 
   // First, get the final index vector.  As above, we may need an initial [0].
   vector<Value*> Indices;
@@ -142,15 +142,15 @@
   Indices.push_back(*OI);
 
   Instruction *NewI = 0;
-  switch(MAI->getOpcode()) {
+  switch(MAI.getOpcode()) {
   case Instruction::Load:
-    NewI = new LoadInst(LastPtr, Indices, MAI->getName());
+    NewI = new LoadInst(LastPtr, Indices, MAI.getName());
     break;
   case Instruction::Store:
-    NewI = new StoreInst(MAI->getOperand(0), LastPtr, Indices);
+    NewI = new StoreInst(MAI.getOperand(0), LastPtr, Indices);
     break;
   case Instruction::GetElementPtr:
-    NewI = new GetElementPtrInst(LastPtr, Indices, MAI->getName());
+    NewI = new GetElementPtrInst(LastPtr, Indices, MAI.getName());
     break;
   default:
     assert(0 && "Unrecognized memory access instruction");
@@ -158,14 +158,15 @@
   NewInsts.push_back(NewI);
   
   // Replace all uses of the old instruction with the new
-  MAI->replaceAllUsesWith(NewI);
+  MAI.replaceAllUsesWith(NewI);
 
   // Now delete the old instruction...
-  delete MAI;
+  delete &MAI;
 
   // Insert all of the new instructions...
-  BBI = BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
+  BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
   
   // Advance the iterator to the instruction following the one just inserted...
-  BBI += NewInsts.size();
+  BBI = NewInsts.back();
+  ++BBI;
 }
diff --git a/lib/Transforms/Scalar/GCSE.cpp b/lib/Transforms/Scalar/GCSE.cpp
index 2792550..850e65a 100644
--- a/lib/Transforms/Scalar/GCSE.cpp
+++ b/lib/Transforms/Scalar/GCSE.cpp
@@ -43,21 +43,21 @@
       return "Global Common Subexpression Elimination";
     }
 
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
 
     // Visitation methods, these are invoked depending on the type of
     // instruction being checked.  They should return true if a common
     // subexpression was folded.
     //
-    bool visitUnaryOperator(Instruction *I);
-    bool visitBinaryOperator(Instruction *I);
-    bool visitGetElementPtrInst(GetElementPtrInst *I);
-    bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
-    bool visitShiftInst(ShiftInst *I) {
-      return visitBinaryOperator((Instruction*)I);
+    bool visitUnaryOperator(Instruction &I);
+    bool visitBinaryOperator(Instruction &I);
+    bool visitGetElementPtrInst(GetElementPtrInst &I);
+    bool visitCastInst(CastInst &I){return visitUnaryOperator((Instruction&)I);}
+    bool visitShiftInst(ShiftInst &I) {
+      return visitBinaryOperator((Instruction&)I);
     }
-    bool visitLoadInst(LoadInst *LI);
-    bool visitInstruction(Instruction *) { return false; }
+    bool visitLoadInst(LoadInst &LI);
+    bool visitInstruction(Instruction &) { return false; }
 
   private:
     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
@@ -93,7 +93,7 @@
 // GCSE::runOnFunction - This is the main transformation entry point for a
 // function.
 //
-bool GCSE::runOnFunction(Function *F) {
+bool GCSE::runOnFunction(Function &F) {
   bool Changed = false;
 
   DomSetInfo = &getAnalysis<DominatorSet>();
@@ -110,7 +110,7 @@
   // program.  If so, eliminate them!
   //
   while (!WorkList.empty()) {
-    Instruction *I = *WorkList.begin();  // Get an instruction from the worklist
+    Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
     WorkList.erase(WorkList.begin());
 
     // Visit the instruction, dispatching to the correct visit function based on
@@ -131,7 +131,7 @@
 // uses of the instruction use First now instead.
 //
 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
-  Instruction *Second = *SI;
+  Instruction &Second = *SI;
   
   //cerr << "DEL " << (void*)Second << Second;
 
@@ -139,15 +139,15 @@
   WorkList.insert(First);
 
   // Add all uses of the second instruction to the worklist
-  for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
+  for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
        UI != UE; ++UI)
     WorkList.insert(cast<Instruction>(*UI));
     
   // Make all users of 'Second' now use 'First'
-  Second->replaceAllUsesWith(First);
+  Second.replaceAllUsesWith(First);
 
   // Erase the second instruction from the program
-  delete Second->getParent()->getInstList().remove(SI);
+  Second.getParent()->getInstList().erase(SI);
 }
 
 // CommonSubExpressionFound - The two instruction I & Other have been found to
@@ -170,16 +170,15 @@
     //
     // Scan the basic block looking for the "first" instruction
     BasicBlock::iterator BI = BB1->begin();
-    while (*BI != I && *BI != Other) {
+    while (&*BI != I && &*BI != Other) {
       ++BI;
       assert(BI != BB1->end() && "Instructions not found in parent BB!");
     }
 
     // Keep track of which instructions occurred first & second
-    Instruction *First = *BI;
+    Instruction *First = BI;
     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
-    BI = find(BI, BB1->end(), Second);
-    assert(BI != BB1->end() && "Second instruction not found in parent block!");
+    BI = Second;
 
     // Destroy Second, using First instead.
     ReplaceInstWithInst(First, BI);    
@@ -188,13 +187,9 @@
     // dominates the other instruction, we can simply use it
     //
   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
-    BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
-    assert(BI != BB2->end() && "Other not in parent basic block!");
-    ReplaceInstWithInst(I, BI);    
+    ReplaceInstWithInst(I, Other);
   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
-    BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
-    assert(BI != BB1->end() && "I not in parent basic block!");
-    ReplaceInstWithInst(Other, BI);
+    ReplaceInstWithInst(Other, I);
   } else {
     // Handle the most general case now.  In this case, neither I dom Other nor
     // Other dom I.  Because we are in SSA form, we are guaranteed that the
@@ -215,12 +210,10 @@
 
     // Rip 'I' out of BB1, and move it to the end of SharedDom.
     BB1->getInstList().remove(I);
-    SharedDom->getInstList().insert(SharedDom->end()-1, I);
+    SharedDom->getInstList().insert(--SharedDom->end(), I);
 
     // Eliminate 'Other' now.
-    BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
-    assert(BI != BB2->end() && "I not in parent basic block!");
-    ReplaceInstWithInst(I, BI);
+    ReplaceInstWithInst(I, Other);
   }
 }
 
@@ -231,25 +224,25 @@
 //
 //===----------------------------------------------------------------------===//
 
-bool GCSE::visitUnaryOperator(Instruction *I) {
-  Value *Op = I->getOperand(0);
-  Function *F = I->getParent()->getParent();
+bool GCSE::visitUnaryOperator(Instruction &I) {
+  Value *Op = I.getOperand(0);
+  Function *F = I.getParent()->getParent();
   
   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
        UI != UE; ++UI)
     if (Instruction *Other = dyn_cast<Instruction>(*UI))
       // Check to see if this new binary operator is not I, but same operand...
-      if (Other != I && Other->getOpcode() == I->getOpcode() &&
+      if (Other != &I && Other->getOpcode() == I.getOpcode() &&
           Other->getOperand(0) == Op &&     // Is the operand the same?
           // Is it embeded in the same function?  (This could be false if LHS
           // is a constant or global!)
           Other->getParent()->getParent() == F &&
 
           // Check that the types are the same, since this code handles casts...
-          Other->getType() == I->getType()) {
+          Other->getType() == I.getType()) {
         
         // These instructions are identical.  Handle the situation.
-        CommonSubExpressionFound(I, Other);
+        CommonSubExpressionFound(&I, Other);
         return true;   // One instruction eliminated!
       }
   
@@ -259,45 +252,45 @@
 // isIdenticalBinaryInst - Return true if the two binary instructions are
 // identical.
 //
-static inline bool isIdenticalBinaryInst(const Instruction *I1,
+static inline bool isIdenticalBinaryInst(const Instruction &I1,
                                          const Instruction *I2) {
   // Is it embeded in the same function?  (This could be false if LHS
   // is a constant or global!)
-  if (I1->getOpcode() != I2->getOpcode() ||
-      I1->getParent()->getParent() != I2->getParent()->getParent())
+  if (I1.getOpcode() != I2->getOpcode() ||
+      I1.getParent()->getParent() != I2->getParent()->getParent())
     return false;
   
   // They are identical if both operands are the same!
-  if (I1->getOperand(0) == I2->getOperand(0) &&
-      I1->getOperand(1) == I2->getOperand(1))
+  if (I1.getOperand(0) == I2->getOperand(0) &&
+      I1.getOperand(1) == I2->getOperand(1))
     return true;
   
   // If the instruction is commutative and associative, the instruction can
   // match if the operands are swapped!
   //
-  if ((I1->getOperand(0) == I2->getOperand(1) &&
-       I1->getOperand(1) == I2->getOperand(0)) &&
-      (I1->getOpcode() == Instruction::Add || 
-       I1->getOpcode() == Instruction::Mul ||
-       I1->getOpcode() == Instruction::And || 
-       I1->getOpcode() == Instruction::Or  ||
-       I1->getOpcode() == Instruction::Xor))
+  if ((I1.getOperand(0) == I2->getOperand(1) &&
+       I1.getOperand(1) == I2->getOperand(0)) &&
+      (I1.getOpcode() == Instruction::Add || 
+       I1.getOpcode() == Instruction::Mul ||
+       I1.getOpcode() == Instruction::And || 
+       I1.getOpcode() == Instruction::Or  ||
+       I1.getOpcode() == Instruction::Xor))
     return true;
 
   return false;
 }
 
-bool GCSE::visitBinaryOperator(Instruction *I) {
-  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
-  Function *F = I->getParent()->getParent();
+bool GCSE::visitBinaryOperator(Instruction &I) {
+  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
+  Function *F = I.getParent()->getParent();
   
   for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
        UI != UE; ++UI)
     if (Instruction *Other = dyn_cast<Instruction>(*UI))
       // Check to see if this new binary operator is not I, but same operand...
-      if (Other != I && isIdenticalBinaryInst(I, Other)) {        
+      if (Other != &I && isIdenticalBinaryInst(I, Other)) {        
         // These instructions are identical.  Handle the situation.
-        CommonSubExpressionFound(I, Other);
+        CommonSubExpressionFound(&I, Other);
         return true;   // One instruction eliminated!
       }
   
@@ -319,42 +312,42 @@
     std::equal(I1->op_begin(), I1->op_end(), I2->op_begin());
 }
 
-bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
-  Value *Op = I->getOperand(0);
-  Function *F = I->getParent()->getParent();
+bool GCSE::visitGetElementPtrInst(GetElementPtrInst &I) {
+  Value *Op = I.getOperand(0);
+  Function *F = I.getParent()->getParent();
   
   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
        UI != UE; ++UI)
     if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
       // Check to see if this new getelementptr is not I, but same operand...
-      if (Other != I && IdenticalComplexInst(I, Other)) {
+      if (Other != &I && IdenticalComplexInst(&I, Other)) {
         // These instructions are identical.  Handle the situation.
-        CommonSubExpressionFound(I, Other);
+        CommonSubExpressionFound(&I, Other);
         return true;   // One instruction eliminated!
       }
   
   return false;
 }
 
-bool GCSE::visitLoadInst(LoadInst *LI) {
-  Value *Op = LI->getOperand(0);
-  Function *F = LI->getParent()->getParent();
+bool GCSE::visitLoadInst(LoadInst &LI) {
+  Value *Op = LI.getOperand(0);
+  Function *F = LI.getParent()->getParent();
   
   for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
        UI != UE; ++UI)
     if (LoadInst *Other = dyn_cast<LoadInst>(*UI))
       // Check to see if this new load is not LI, but has the same operands...
-      if (Other != LI && IdenticalComplexInst(LI, Other) &&
-          TryToRemoveALoad(LI, Other))
+      if (Other != &LI && IdenticalComplexInst(&LI, Other) &&
+          TryToRemoveALoad(&LI, Other))
         return true;   // An instruction was eliminated!
   
   return false;
 }
 
-static inline bool isInvalidatingInst(const Instruction *I) {
-  return I->getOpcode() == Instruction::Store ||
-         I->getOpcode() == Instruction::Call ||
-         I->getOpcode() == Instruction::Invoke;
+static inline bool isInvalidatingInst(const Instruction &I) {
+  return I.getOpcode() == Instruction::Store ||
+         I.getOpcode() == Instruction::Call ||
+         I.getOpcode() == Instruction::Invoke;
 }
 
 // TryToRemoveALoad - Try to remove one of L1 or L2.  The problem with removing
@@ -373,9 +366,7 @@
 
   BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
 
-  // FIXME: This is incredibly painful with broken rep
-  BasicBlock::iterator L1I = std::find(BB1->begin(), BB1->end(), L1);
-  assert(L1I != BB1->end() && "Inst not in own parent?");
+  BasicBlock::iterator L1I = L1;
 
   // L1 now dominates L2.  Check to see if the intervening instructions between
   // the two loads include a store or call...
@@ -384,7 +375,7 @@
     // In this degenerate case, no checking of global basic blocks has to occur
     // just check the instructions BETWEEN L1 & L2...
     //
-    for (++L1I; *L1I != L2; ++L1I)
+    for (++L1I; &*L1I != L2; ++L1I)
       if (isInvalidatingInst(*L1I))
         return false;   // Cannot eliminate load
 
@@ -404,7 +395,7 @@
     // Make sure that there are no store instructions between the start of BB2
     // and the second load instruction...
     //
-    for (BasicBlock::iterator II = BB2->begin(); *II != L2; ++II)
+    for (BasicBlock::iterator II = BB2->begin(); &*II != L2; ++II)
       if (isInvalidatingInst(*II)) {
         BBContainsStore[BB2] = true;
         return false;   // Cannot eliminate load
diff --git a/lib/Transforms/Scalar/IndVarSimplify.cpp b/lib/Transforms/Scalar/IndVarSimplify.cpp
index 6446526..7a32315 100644
--- a/lib/Transforms/Scalar/IndVarSimplify.cpp
+++ b/lib/Transforms/Scalar/IndVarSimplify.cpp
@@ -47,9 +47,10 @@
   // info into a vector...
   //
   std::vector<InductionVariable> IndVars;    // Induction variables for block
-  for (BasicBlock::iterator I = Header->begin(); 
-       PHINode *PN = dyn_cast<PHINode>(*I); ++I)
+  BasicBlock::iterator AfterPHIIt = Header->begin();
+  for (; PHINode *PN = dyn_cast<PHINode>(&*AfterPHIIt); ++AfterPHIIt)
     IndVars.push_back(InductionVariable(PN, Loops));
+  // AfterPHIIt now points to first nonphi instruction...
 
   // If there are no phi nodes in this basic block, there can't be indvars...
   if (IndVars.empty()) return Changed;
@@ -77,7 +78,7 @@
     PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
 
     // Insert the phi node at the end of the other phi nodes...
-    Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
+    AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
 
     // Create the increment instruction to add one to the counter...
     Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
@@ -85,7 +86,7 @@
                                               "add1-indvar");
 
     // Insert the add instruction after all of the PHI nodes...
-    Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
+    Header->getInstList().insert(AfterPHIIt, Add);
 
     // Figure out which block is incoming and which is the backedge for the loop
     BasicBlock *Incoming, *BackEdgeBlock;
@@ -123,7 +124,6 @@
   // Loop through and replace all of the auxillary induction variables with
   // references to the primary induction variable...
   //
-  unsigned InsertPos = IndVars.size();
   for (unsigned i = 0; i < IndVars.size(); ++i) {
     InductionVariable *IV = &IndVars[i];
 
@@ -139,12 +139,11 @@
 
         // If the types are not compatible, insert a cast now...
         if (Val->getType() != IV->Step->getType())
-          Val = InsertCast(Val, IV->Step->getType(),
-                           Header->begin()+InsertPos++);
+          Val = InsertCast(Val, IV->Step->getType(), AfterPHIIt);
 
         Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
         // Insert the phi node at the end of the other phi nodes...
-        Header->getInstList().insert(Header->begin()+InsertPos++, Val);
+        Header->getInstList().insert(AfterPHIIt, Val);
       }
 
       if (!isa<Constant>(IV->Start) ||   // If the start != 0
@@ -154,18 +153,16 @@
 
         // If the types are not compatible, insert a cast now...
         if (Val->getType() != IV->Start->getType())
-          Val = InsertCast(Val, IV->Start->getType(),
-                           Header->begin()+InsertPos++);
+          Val = InsertCast(Val, IV->Start->getType(), AfterPHIIt);
 
         Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
         // Insert the phi node at the end of the other phi nodes...
-        Header->getInstList().insert(Header->begin()+InsertPos++, Val);
+        Header->getInstList().insert(AfterPHIIt, Val);
       }
 
       // If the PHI node has a different type than val is, insert a cast now...
       if (Val->getType() != IV->Phi->getType())
-          Val = InsertCast(Val, IV->Phi->getType(),
-                           Header->begin()+InsertPos++);
+        Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
       
       // Replace all uses of the old PHI node with the new computed value...
       IV->Phi->replaceAllUsesWith(Val);
@@ -176,9 +173,7 @@
       Val->setName(OldName);
 
       // Delete the old, now unused, phi node...
-      Header->getInstList().remove(IV->Phi);
-      delete IV->Phi;
-      InsertPos--;            // Deleted an instr, decrement insert position
+      Header->getInstList().erase(IV->Phi);
       Changed = true;
       ++NumRemoved;
     }
@@ -193,7 +188,7 @@
       return "Induction Variable Cannonicalize";
     }
 
-    virtual bool runOnFunction(Function *F) {
+    virtual bool runOnFunction(Function &) {
       LoopInfo &LI = getAnalysis<LoopInfo>();
 
       // Induction Variables live in the header nodes of loops
diff --git a/lib/Transforms/Scalar/InstructionCombining.cpp b/lib/Transforms/Scalar/InstructionCombining.cpp
index 6032ab9..7092989 100644
--- a/lib/Transforms/Scalar/InstructionCombining.cpp
+++ b/lib/Transforms/Scalar/InstructionCombining.cpp
@@ -36,11 +36,11 @@
     // Worklist of all of the instructions that need to be simplified.
     std::vector<Instruction*> WorkList;
 
-    void AddUsesToWorkList(Instruction *I) {
+    void AddUsesToWorkList(Instruction &I) {
       // The instruction was simplified, add all users of the instruction to
       // the work lists because they might get more simplified now...
       //
-      for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
+      for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
            UI != UE; ++UI)
         WorkList.push_back(cast<Instruction>(*UI));
     }
@@ -48,7 +48,7 @@
   public:
     const char *getPassName() const { return "Instruction Combining"; }
 
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
@@ -61,37 +61,37 @@
     //     I          - Change was made, I is still valid
     //   otherwise    - Change was made, replace I with returned instruction
     //   
-    Instruction *visitNot(UnaryOperator *I);
-    Instruction *visitAdd(BinaryOperator *I);
-    Instruction *visitSub(BinaryOperator *I);
-    Instruction *visitMul(BinaryOperator *I);
-    Instruction *visitDiv(BinaryOperator *I);
-    Instruction *visitRem(BinaryOperator *I);
-    Instruction *visitAnd(BinaryOperator *I);
-    Instruction *visitOr (BinaryOperator *I);
-    Instruction *visitXor(BinaryOperator *I);
-    Instruction *visitSetCondInst(BinaryOperator *I);
-    Instruction *visitShiftInst(Instruction *I);
-    Instruction *visitCastInst(CastInst *CI);
-    Instruction *visitPHINode(PHINode *PN);
-    Instruction *visitGetElementPtrInst(GetElementPtrInst *GEP);
-    Instruction *visitMemAccessInst(MemAccessInst *MAI);
+    Instruction *visitNot(UnaryOperator &I);
+    Instruction *visitAdd(BinaryOperator &I);
+    Instruction *visitSub(BinaryOperator &I);
+    Instruction *visitMul(BinaryOperator &I);
+    Instruction *visitDiv(BinaryOperator &I);
+    Instruction *visitRem(BinaryOperator &I);
+    Instruction *visitAnd(BinaryOperator &I);
+    Instruction *visitOr (BinaryOperator &I);
+    Instruction *visitXor(BinaryOperator &I);
+    Instruction *visitSetCondInst(BinaryOperator &I);
+    Instruction *visitShiftInst(Instruction &I);
+    Instruction *visitCastInst(CastInst &CI);
+    Instruction *visitPHINode(PHINode &PN);
+    Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
+    Instruction *visitMemAccessInst(MemAccessInst &MAI);
 
     // visitInstruction - Specify what to return for unhandled instructions...
-    Instruction *visitInstruction(Instruction *I) { return 0; }
+    Instruction *visitInstruction(Instruction &I) { return 0; }
   };
 }
 
 
-Instruction *InstCombiner::visitNot(UnaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitNot(UnaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
 
   // not (not X) = X
-  if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(0)))
+  if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(0)))
     if (Op->getOpcode() == Instruction::Not) {
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Op->getOperand(0));
-      return I;
+      I.replaceAllUsesWith(Op->getOperand(0));
+      return &I;
     }
   return 0;
 }
@@ -100,9 +100,9 @@
 // Make sure that this instruction has a constant on the right hand side if it
 // has any constant arguments.  If not, fix it an return true.
 //
-static bool SimplifyBinOp(BinaryOperator *I) {
-  if (isa<Constant>(I->getOperand(0)) && !isa<Constant>(I->getOperand(1)))
-    return !I->swapOperands();
+static bool SimplifyBinOp(BinaryOperator &I) {
+  if (isa<Constant>(I.getOperand(0)) && !isa<Constant>(I.getOperand(1)))
+    return !I.swapOperands();
   return false;
 }
 
@@ -118,16 +118,16 @@
   return 0;
 }
 
-Instruction *InstCombiner::visitAdd(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead add instructions...
+Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead add instructions...
   bool Changed = SimplifyBinOp(I);
-  Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
+  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
 
   // Eliminate 'add int %X, 0'
-  if (RHS == Constant::getNullValue(I->getType())) {
+  if (RHS == Constant::getNullValue(I.getType())) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(LHS);
-    return I;
+    I.replaceAllUsesWith(LHS);
+    return &I;
   }
 
   // -A + B  -->  B - A
@@ -150,33 +150,33 @@
         //    %Z = add int %X, 2
         //
         if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
-          I->setOperand(0, ILHS->getOperand(0));
-          I->setOperand(1, Val);
-          return I;
+          I.setOperand(0, ILHS->getOperand(0));
+          I.setOperand(1, Val);
+          return &I;
         }
       }
     }
   }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
-Instruction *InstCombiner::visitSub(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead add instructions...
-  Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
+Instruction *InstCombiner::visitSub(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead add instructions...
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
   if (Op0 == Op1) {         // sub X, X  -> 0
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
-    return I;
+    I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
+    return &I;
   }
 
   // If this is a subtract instruction with a constant RHS, convert it to an add
   // instruction of a negative constant
   //
   if (Constant *Op2 = dyn_cast<Constant>(Op1))
-    if (Constant *RHS = *Constant::getNullValue(I->getType()) - *Op2) // 0 - RHS
-      return BinaryOperator::create(Instruction::Add, Op0, RHS, I->getName());
+    if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
+      return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
 
   // If this is a 'C = x-B', check to see if 'B = -A', so that C = x+A...
   if (Value *V = dyn_castNegInst(Op1))
@@ -198,59 +198,59 @@
   return 0;
 }
 
-Instruction *InstCombiner::visitMul(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitMul(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
   bool Changed = SimplifyBinOp(I);
-  Value *Op1 = I->getOperand(0);
+  Value *Op1 = I.getOperand(0);
 
   // Simplify add instructions with a constant RHS...
-  if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(1))) {
-    if (I->getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
+  if (Constant *Op2 = dyn_cast<Constant>(I.getOperand(1))) {
+    if (I.getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1)){
       // Eliminate 'mul int %X, 1'
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Op1);
-      return I;
+      I.replaceAllUsesWith(Op1);
+      return &I;
 
-    } else if (I->getType()->isIntegral() &&
+    } else if (I.getType()->isIntegral() &&
                cast<ConstantInt>(Op2)->equalsInt(2)) {
       // Convert 'mul int %X, 2' to 'add int %X, %X'
-      return BinaryOperator::create(Instruction::Add, Op1, Op1, I->getName());
+      return BinaryOperator::create(Instruction::Add, Op1, Op1, I.getName());
 
     } else if (Op2->isNullValue()) {
       // Eliminate 'mul int %X, 0'
-      AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Op2);   // Set this value to zero directly
-      return I;
+      AddUsesToWorkList(I);        // Add all modified instrs to worklist
+      I.replaceAllUsesWith(Op2);   // Set this value to zero directly
+      return &I;
     }
   }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
 
-Instruction *InstCombiner::visitDiv(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
 
   // div X, 1 == X
-  if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
+  if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
     if (RHS->equalsInt(1)) {
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(I->getOperand(0));
-      return I;
+      I.replaceAllUsesWith(I.getOperand(0));
+      return &I;
     }
   return 0;
 }
 
 
-Instruction *InstCombiner::visitRem(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitRem(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
 
   // rem X, 1 == 0
-  if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1)))
+  if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
     if (RHS->equalsInt(1)) {
-      AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
-      return I;
+      AddUsesToWorkList(I);          // Add all modified instrs to worklist
+      I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
+      return &I;
     }
   return 0;
 }
@@ -273,123 +273,123 @@
 }
 
 
-Instruction *InstCombiner::visitAnd(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
   bool Changed = SimplifyBinOp(I);
-  Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
   // and X, X = X   and X, 0 == 0
-  if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
-    AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Op1);
-    return I;
+  if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType())) {
+    AddUsesToWorkList(I);            // Add all modified instrs to worklist
+    I.replaceAllUsesWith(Op1);
+    return &I;
   }
 
   // and X, -1 == X
   if (Constant *RHS = dyn_cast<Constant>(Op1))
-    if (RHS == getMaxValue(I->getType())) {
+    if (RHS == getMaxValue(I.getType())) {
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Op0);
-      return I;
+      I.replaceAllUsesWith(Op0);
+      return &I;
     }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
 
 
-Instruction *InstCombiner::visitOr(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitOr(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
   bool Changed = SimplifyBinOp(I);
-  Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
   // or X, X = X   or X, 0 == X
-  if (Op0 == Op1 || Op1 == Constant::getNullValue(I->getType())) {
+  if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType())) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Op0);
-    return I;
+    I.replaceAllUsesWith(Op0);
+    return &I;
   }
 
   // or X, -1 == -1
   if (Constant *RHS = dyn_cast<Constant>(Op1))
-    if (RHS == getMaxValue(I->getType())) {
+    if (RHS == getMaxValue(I.getType())) {
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Op1);
-      return I;
+      I.replaceAllUsesWith(Op1);
+      return &I;
     }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
 
 
-Instruction *InstCombiner::visitXor(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitXor(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
   bool Changed = SimplifyBinOp(I);
-  Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
   // xor X, X = 0
   if (Op0 == Op1) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
-    return I;
+    I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
+    return &I;
   }
 
   // xor X, 0 == X
-  if (Op1 == Constant::getNullValue(I->getType())) {
+  if (Op1 == Constant::getNullValue(I.getType())) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Op0);
-    return I;
+    I.replaceAllUsesWith(Op0);
+    return &I;
   }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
 // true when both operands are equal...
 //
-static bool isTrueWhenEqual(Instruction *I) {
-  return I->getOpcode() == Instruction::SetEQ ||
-         I->getOpcode() == Instruction::SetGE ||
-         I->getOpcode() == Instruction::SetLE;
+static bool isTrueWhenEqual(Instruction &I) {
+  return I.getOpcode() == Instruction::SetEQ ||
+         I.getOpcode() == Instruction::SetGE ||
+         I.getOpcode() == Instruction::SetLE;
 }
 
-Instruction *InstCombiner::visitSetCondInst(BinaryOperator *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
   bool Changed = SimplifyBinOp(I);
 
   // setcc X, X
-  if (I->getOperand(0) == I->getOperand(1)) {
+  if (I.getOperand(0) == I.getOperand(1)) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(ConstantBool::get(isTrueWhenEqual(I)));
-    return I;
+    I.replaceAllUsesWith(ConstantBool::get(isTrueWhenEqual(I)));
+    return &I;
   }
 
   // setcc <global*>, 0 - Global value addresses are never null!
-  if (isa<GlobalValue>(I->getOperand(0)) &&
-      isa<ConstantPointerNull>(I->getOperand(1))) {
+  if (isa<GlobalValue>(I.getOperand(0)) &&
+      isa<ConstantPointerNull>(I.getOperand(1))) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(ConstantBool::get(!isTrueWhenEqual(I)));
-    return I;
+    I.replaceAllUsesWith(ConstantBool::get(!isTrueWhenEqual(I)));
+    return &I;
   }
 
-  return Changed ? I : 0;
+  return Changed ? &I : 0;
 }
 
 
 
-Instruction *InstCombiner::visitShiftInst(Instruction *I) {
-  if (I->use_empty()) return 0;       // Don't fix dead instructions...
-  assert(I->getOperand(1)->getType() == Type::UByteTy);
-  Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
+Instruction *InstCombiner::visitShiftInst(Instruction &I) {
+  if (I.use_empty()) return 0;       // Don't fix dead instructions...
+  assert(I.getOperand(1)->getType() == Type::UByteTy);
+  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
   // shl X, 0 == X and shr X, 0 == X
   // shl 0, X == 0 and shr 0, X == 0
   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
       Op0 == Constant::getNullValue(Op0->getType())) {
     AddUsesToWorkList(I);         // Add all modified instrs to worklist
-    I->replaceAllUsesWith(Op0);
-    return I;
+    I.replaceAllUsesWith(Op0);
+    return &I;
   }
 
   // shl int X, 32 = 0 and shr sbyte Y, 9 = 0, ... just don't eliminate shr of
@@ -398,10 +398,10 @@
   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
     if (CUI->getValue() >= TypeBits &&
-        !(Op0->getType()->isSigned() && I->getOpcode() == Instruction::Shr)) {
+        !(Op0->getType()->isSigned() && I.getOpcode() == Instruction::Shr)) {
       AddUsesToWorkList(I);         // Add all modified instrs to worklist
-      I->replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
-      return I;
+      I.replaceAllUsesWith(Constant::getNullValue(Op0->getType()));
+      return &I;
     }
   }
   return 0;
@@ -411,12 +411,12 @@
 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
 // instruction.
 //
-static inline bool isEliminableCastOfCast(const CastInst *CI,
+static inline bool isEliminableCastOfCast(const CastInst &CI,
                                           const CastInst *CSrc) {
-  assert(CI->getOperand(0) == CSrc);
+  assert(CI.getOperand(0) == CSrc);
   const Type *SrcTy = CSrc->getOperand(0)->getType();
   const Type *MidTy = CSrc->getType();
-  const Type *DstTy = CI->getType();
+  const Type *DstTy = CI.getType();
 
   // It is legal to eliminate the instruction if casting A->B->A
   if (SrcTy == DstTy) return true;
@@ -437,27 +437,27 @@
 
 // CastInst simplification
 //
-Instruction *InstCombiner::visitCastInst(CastInst *CI) {
-  if (CI->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitCastInst(CastInst &CI) {
+  if (CI.use_empty()) return 0;       // Don't fix dead instructions...
 
   // If the user is casting a value to the same type, eliminate this cast
   // instruction...
-  if (CI->getType() == CI->getOperand(0)->getType() && !CI->use_empty()) {
+  if (CI.getType() == CI.getOperand(0)->getType() && !CI.use_empty()) {
     AddUsesToWorkList(CI);         // Add all modified instrs to worklist
-    CI->replaceAllUsesWith(CI->getOperand(0));
-    return CI;
+    CI.replaceAllUsesWith(CI.getOperand(0));
+    return &CI;
   }
 
 
   // If casting the result of another cast instruction, try to eliminate this
   // one!
   //
-  if (CastInst *CSrc = dyn_cast<CastInst>(CI->getOperand(0)))
+  if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0)))
     if (isEliminableCastOfCast(CI, CSrc)) {
       // This instruction now refers directly to the cast's src operand.  This
       // has a good chance of making CSrc dead.
-      CI->setOperand(0, CSrc->getOperand(0));
-      return CI;
+      CI.setOperand(0, CSrc->getOperand(0));
+      return &CI;
     }
 
   return 0;
@@ -466,28 +466,28 @@
 
 // PHINode simplification
 //
-Instruction *InstCombiner::visitPHINode(PHINode *PN) {
-  if (PN->use_empty()) return 0;       // Don't fix dead instructions...
+Instruction *InstCombiner::visitPHINode(PHINode &PN) {
+  if (PN.use_empty()) return 0;       // Don't fix dead instructions...
 
   // If the PHI node only has one incoming value, eliminate the PHI node...
-  if (PN->getNumIncomingValues() == 1) {
+  if (PN.getNumIncomingValues() == 1) {
     AddUsesToWorkList(PN);         // Add all modified instrs to worklist
-    PN->replaceAllUsesWith(PN->getIncomingValue(0));
-    return PN;
+    PN.replaceAllUsesWith(PN.getIncomingValue(0));
+    return &PN;
   }
 
   return 0;
 }
 
 
-Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst *GEP) {
+Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
   // Is it getelementptr %P, uint 0
-  // If so, elminate the noop.
-  if (GEP->getNumOperands() == 2 && !GEP->use_empty() &&
-      GEP->getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
+  // If so, eliminate the noop.
+  if (GEP.getNumOperands() == 2 && !GEP.use_empty() &&
+      GEP.getOperand(1) == Constant::getNullValue(Type::UIntTy)) {
     AddUsesToWorkList(GEP);         // Add all modified instrs to worklist
-    GEP->replaceAllUsesWith(GEP->getOperand(0));
-    return GEP;
+    GEP.replaceAllUsesWith(GEP.getOperand(0));
+    return &GEP;
   }
 
   return visitMemAccessInst(GEP);
@@ -498,36 +498,36 @@
 // getelementptr instruction, combine the indices of the GEP into this
 // instruction
 //
-Instruction *InstCombiner::visitMemAccessInst(MemAccessInst *MAI) {
+Instruction *InstCombiner::visitMemAccessInst(MemAccessInst &MAI) {
   GetElementPtrInst *Src =
-    dyn_cast<GetElementPtrInst>(MAI->getPointerOperand());
+    dyn_cast<GetElementPtrInst>(MAI.getPointerOperand());
   if (!Src) return 0;
 
   std::vector<Value *> Indices;
   
   // Only special case we have to watch out for is pointer arithmetic on the
   // 0th index of MAI. 
-  unsigned FirstIdx = MAI->getFirstIndexOperandNumber();
-  if (FirstIdx == MAI->getNumOperands() || 
-      (FirstIdx == MAI->getNumOperands()-1 &&
-       MAI->getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) { 
+  unsigned FirstIdx = MAI.getFirstIndexOperandNumber();
+  if (FirstIdx == MAI.getNumOperands() || 
+      (FirstIdx == MAI.getNumOperands()-1 &&
+       MAI.getOperand(FirstIdx) == ConstantUInt::get(Type::UIntTy, 0))) { 
     // Replace the index list on this MAI with the index on the getelementptr
     Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
-  } else if (*MAI->idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) { 
+  } else if (*MAI.idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) { 
     // Otherwise we can do the fold if the first index of the GEP is a zero
     Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
-    Indices.insert(Indices.end(), MAI->idx_begin()+1, MAI->idx_end());
+    Indices.insert(Indices.end(), MAI.idx_begin()+1, MAI.idx_end());
   }
 
   if (Indices.empty()) return 0;  // Can't do the fold?
 
-  switch (MAI->getOpcode()) {
+  switch (MAI.getOpcode()) {
   case Instruction::GetElementPtr:
-    return new GetElementPtrInst(Src->getOperand(0), Indices, MAI->getName());
+    return new GetElementPtrInst(Src->getOperand(0), Indices, MAI.getName());
   case Instruction::Load:
-    return new LoadInst(Src->getOperand(0), Indices, MAI->getName());
+    return new LoadInst(Src->getOperand(0), Indices, MAI.getName());
   case Instruction::Store:
-    return new StoreInst(MAI->getOperand(0), Src->getOperand(0), Indices);
+    return new StoreInst(MAI.getOperand(0), Src->getOperand(0), Indices);
   default:
     assert(0 && "Unknown memaccessinst!");
     break;
@@ -537,7 +537,7 @@
 }
 
 
-bool InstCombiner::runOnFunction(Function *F) {
+bool InstCombiner::runOnFunction(Function &F) {
   bool Changed = false;
 
   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
@@ -547,7 +547,7 @@
     WorkList.pop_back();
 
     // Now that we have an instruction, try combining it to simplify it...
-    Instruction *Result = visit(I);
+    Instruction *Result = visit(*I);
     if (Result) {
       ++NumCombined;
       // Should we replace the old instruction with a new one?
@@ -562,10 +562,16 @@
         }
 
         ReplaceInstWithInst(I, Result);
+      } else {
+        // FIXME:
+        // FIXME:
+        // FIXME: This should DCE the instruction to simplify the cases above.
+        // FIXME:
+        // FIXME:
       }
 
       WorkList.push_back(Result);
-      AddUsesToWorkList(Result);
+      AddUsesToWorkList(*Result);
       Changed = true;
     }
   }
diff --git a/lib/Transforms/Scalar/LICM.cpp b/lib/Transforms/Scalar/LICM.cpp
index 2e5adf6..98de447 100644
--- a/lib/Transforms/Scalar/LICM.cpp
+++ b/lib/Transforms/Scalar/LICM.cpp
@@ -35,7 +35,7 @@
   struct LICM : public FunctionPass, public InstVisitor<LICM> {
     const char *getPassName() const { return "Loop Invariant Code Motion"; }
 
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
 
     // This transformation requires natural loop information...
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
@@ -69,7 +69,7 @@
     // hoist - When an instruction is found to only use loop invariant operands
     // that is safe to hoist, this instruction is called to do the dirty work.
     //
-    void hoist(Instruction *I);
+    void hoist(Instruction &I);
 
     // isLoopInvariant - Return true if the specified value is loop invariant
     inline bool isLoopInvariant(Value *V) {
@@ -85,21 +85,21 @@
     // the specified instruction types are hoisted.
     //
     friend class InstVisitor<LICM>;
-    void visitUnaryOperator(Instruction *I) {
-      if (isLoopInvariant(I->getOperand(0))) hoist(I);
+    void visitUnaryOperator(Instruction &I) {
+      if (isLoopInvariant(I.getOperand(0))) hoist(I);
     }
-    void visitBinaryOperator(Instruction *I) {
-      if (isLoopInvariant(I->getOperand(0)) &&isLoopInvariant(I->getOperand(1)))
+    void visitBinaryOperator(Instruction &I) {
+      if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
         hoist(I);
     }
 
-    void visitCastInst(CastInst *I) { visitUnaryOperator((Instruction*)I); }
-    void visitShiftInst(ShiftInst *I) { visitBinaryOperator((Instruction*)I); }
+    void visitCastInst(CastInst &I) { visitUnaryOperator((Instruction&)I); }
+    void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
 
-    void visitGetElementPtrInst(GetElementPtrInst *GEPI) {
-      Instruction *I = (Instruction*)GEPI;
-      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
-        if (!isLoopInvariant(I->getOperand(i))) return;
+    void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
+      Instruction &I = (Instruction&)GEPI;
+      for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
+        if (!isLoopInvariant(I.getOperand(i))) return;
       hoist(I);
     }
   };
@@ -107,7 +107,7 @@
 
 Pass *createLICMPass() { return new LICM(); }
 
-bool LICM::runOnFunction(Function *F) {
+bool LICM::runOnFunction(Function &) {
   // get our loop information...
   const std::vector<Loop*> &TopLevelLoops =
     getAnalysis<LoopInfo>().getTopLevelLoops();
@@ -177,30 +177,26 @@
 }
 
 void LICM::visitBasicBlock(BasicBlock *BB) {
-  // This cannot use an iterator, because it might get invalidated when PHI
-  // nodes are inserted!
-  //
-  for (unsigned i = 0; i < BB->size(); ) {
-    visit(BB->begin()[i]);
+  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
+    visit(*I);
     
-    BasicBlock::iterator It = BB->begin()+i;
-    if (dceInstruction(It))
+    if (dceInstruction(I))
       Changed = true;
     else
-      ++i;
+      ++I;
   }
 }
 
 
-void LICM::hoist(Instruction *Inst) {
-  if (Inst->use_empty()) return;  // Don't (re) hoist dead instructions!
+void LICM::hoist(Instruction &Inst) {
+  if (Inst.use_empty()) return;  // Don't (re) hoist dead instructions!
   //cerr << "Hoisting " << Inst;
 
   BasicBlock *Header = CurLoop->getHeader();
 
   // Old instruction will be removed, so take it's name...
-  string InstName = Inst->getName();
-  Inst->setName("");
+  string InstName = Inst.getName();
+  Inst.setName("");
 
   // The common case is that we have a pre-header.  Generate special case code
   // that is faster if that is the case.
@@ -209,21 +205,21 @@
     BasicBlock *Pred = LoopPreds[0];
 
     // Create a new copy of the instruction, for insertion into Pred.
-    Instruction *New = Inst->clone();
+    Instruction *New = Inst.clone();
     New->setName(InstName);
 
     // Insert the new node in Pred, before the terminator.
-    Pred->getInstList().insert(Pred->end()-1, New);
+    Pred->getInstList().insert(--Pred->end(), New);
 
-    // Kill the old instruction.
-    Inst->replaceAllUsesWith(New);
+    // Kill the old instruction...
+    Inst.replaceAllUsesWith(New);
     ++NumHoistedPH;
 
   } else {
     // No loop pre-header, insert a PHI node into header to capture all of the
     // incoming versions of the value.
     //
-    PHINode *LoopVal = new PHINode(Inst->getType(), InstName+".phi");
+    PHINode *LoopVal = new PHINode(Inst.getType(), InstName+".phi");
 
     // Insert the new PHI node into the loop header...
     Header->getInstList().push_front(LoopVal);
@@ -233,11 +229,11 @@
       BasicBlock *Pred = LoopPreds[i];
       
       // Create a new copy of the instruction, for insertion into Pred.
-      Instruction *New = Inst->clone();
+      Instruction *New = Inst.clone();
       New->setName(InstName);
 
       // Insert the new node in Pred, before the terminator.
-      Pred->getInstList().insert(Pred->end()-1, New);
+      Pred->getInstList().insert(--Pred->end(), New);
 
       // Add the incoming value to the PHI node.
       LoopVal->addIncoming(New, Pred);
@@ -253,7 +249,7 @@
     // entire loop body.  The old definition was defined _inside_ of the loop,
     // so the scope cannot extend outside of the loop, so we're ok.
     //
-    Inst->replaceAllUsesWith(LoopVal);
+    Inst.replaceAllUsesWith(LoopVal);
     ++NumHoistedNPH;
   }
 
diff --git a/lib/Transforms/Scalar/PiNodeInsertion.cpp b/lib/Transforms/Scalar/PiNodeInsertion.cpp
index 2e9c328..2c16049 100644
--- a/lib/Transforms/Scalar/PiNodeInsertion.cpp
+++ b/lib/Transforms/Scalar/PiNodeInsertion.cpp
@@ -42,7 +42,7 @@
   struct PiNodeInserter : public FunctionPass {
     const char *getPassName() const { return "Pi Node Insertion"; }
     
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
     
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
@@ -61,11 +61,10 @@
 Pass *createPiNodeInsertionPass() { return new PiNodeInserter(); }
 
 
-bool PiNodeInserter::runOnFunction(Function *F) {
+bool PiNodeInserter::runOnFunction(Function &F) {
   bool Changed = false;
-  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
-    BasicBlock *BB = *I;
-    TerminatorInst *TI = BB->getTerminator();
+  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+    TerminatorInst *TI = I->getTerminator();
     
     // FIXME: Insert PI nodes for switch statements too
 
@@ -112,8 +111,7 @@
 }
 
 
-// alreadyHasPiNodeFor - Return true if there is already a Pi node in BB for
-// V.
+// alreadyHasPiNodeFor - Return true if there is already a Pi node in BB for V.
 static bool alreadyHasPiNodeFor(Value *V, BasicBlock *BB) {
   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
     if (PHINode *PN = dyn_cast<PHINode>(*I))
diff --git a/lib/Transforms/Scalar/Reassociate.cpp b/lib/Transforms/Scalar/Reassociate.cpp
index fcbf8b3..7ccbd7b 100644
--- a/lib/Transforms/Scalar/Reassociate.cpp
+++ b/lib/Transforms/Scalar/Reassociate.cpp
@@ -39,13 +39,13 @@
       return "Expression Reassociation";
     }
 
-    bool runOnFunction(Function *F);
+    bool runOnFunction(Function &F);
 
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.preservesCFG();
     }
   private:
-    void BuildRankMap(Function *F);
+    void BuildRankMap(Function &F);
     unsigned getRank(Value *V);
     bool ReassociateExpr(BinaryOperator *I);
     bool ReassociateBB(BasicBlock *BB);
@@ -54,9 +54,9 @@
 
 Pass *createReassociatePass() { return new Reassociate(); }
 
-void Reassociate::BuildRankMap(Function *F) {
+void Reassociate::BuildRankMap(Function &F) {
   unsigned i = 1;
-  ReversePostOrderTraversal<Function*> RPOT(F);
+  ReversePostOrderTraversal<Function*> RPOT(&F);
   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
          E = RPOT.end(); I != E; ++I)
     RankMap[*I] = ++i;
@@ -182,15 +182,11 @@
       // adding it now, we are assured that the neg instructions we just
       // inserted dominate the instruction we are about to insert after them.
       //
-      BasicBlock::iterator NBI = BI;
-
-      // Scan through the inserted instructions, looking for RHS, which must be
-      // after LHS in the instruction list.
-      while (*NBI != RHS) ++NBI;
+      BasicBlock::iterator NBI = cast<Instruction>(RHS);
 
       Instruction *Add =
         BinaryOperator::create(Instruction::Add, LHS, RHS, I->getName()+".neg");
-      BB->getInstList().insert(NBI+1, Add);  // Add to the basic block...
+      BB->getInstList().insert(++NBI, Add);  // Add to the basic block...
       return Add;
     }
 
@@ -209,12 +205,11 @@
 bool Reassociate::ReassociateBB(BasicBlock *BB) {
   bool Changed = false;
   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
-    Instruction *Inst = *BI;
 
     // If this instruction is a commutative binary operator, and the ranks of
     // the two operands are sorted incorrectly, fix it now.
     //
-    if (BinaryOperator *I = isCommutativeOperator(Inst)) {
+    if (BinaryOperator *I = isCommutativeOperator(BI)) {
       if (!I->use_empty()) {
         // Make sure that we don't have a tree-shaped computation.  If we do,
         // linearize it.  Convert (A+B)+(C+D) into ((A+B)+C)+D
@@ -245,22 +240,23 @@
         Changed |= ReassociateExpr(I);
       }
 
-    } else if (Inst->getOpcode() == Instruction::Sub &&
-               Inst->getOperand(0) != Constant::getNullValue(Inst->getType())) {
+    } else if (BI->getOpcode() == Instruction::Sub &&
+               BI->getOperand(0) != Constant::getNullValue(BI->getType())) {
       // Convert a subtract into an add and a neg instruction... so that sub
       // instructions can be commuted with other add instructions...
       //
       Instruction *New = BinaryOperator::create(Instruction::Add,
-                                                Inst->getOperand(0),
-                                                Inst->getOperand(1),
-                                                Inst->getName());
-      Value *NegatedValue = Inst->getOperand(1);
+                                                BI->getOperand(0),
+                                                BI->getOperand(1),
+                                                BI->getName());
+      Value *NegatedValue = BI->getOperand(1);
 
       // Everyone now refers to the add instruction...
-      Inst->replaceAllUsesWith(New);
+      BI->replaceAllUsesWith(New);
 
       // Put the new add in the place of the subtract... deleting the subtract
-      delete BB->getInstList().replaceWith(BI, New);
+      BI = BB->getInstList().erase(BI);
+      BI = ++BB->getInstList().insert(BI, New);
 
       // Calculate the negative value of Operand 1 of the sub instruction...
       // and set it as the RHS of the add instruction we just made...
@@ -275,13 +271,13 @@
 }
 
 
-bool Reassociate::runOnFunction(Function *F) {
+bool Reassociate::runOnFunction(Function &F) {
   // Recalculate the rank map for F
   BuildRankMap(F);
 
   bool Changed = false;
-  for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
-    Changed |= ReassociateBB(*FI);
+  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
+    Changed |= ReassociateBB(FI);
 
   // We are done with the rank map...
   RankMap.clear();
diff --git a/lib/Transforms/Scalar/SCCP.cpp b/lib/Transforms/Scalar/SCCP.cpp
index 93e85fc..4d752e9 100644
--- a/lib/Transforms/Scalar/SCCP.cpp
+++ b/lib/Transforms/Scalar/SCCP.cpp
@@ -101,7 +101,7 @@
   // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
   // and return true if the function was modified.
   //
-  bool runOnFunction(Function *F);
+  bool runOnFunction(Function &F);
 
   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     AU.preservesCFG();
@@ -167,7 +167,7 @@
   // 
   void markExecutable(BasicBlock *BB) {
     if (BBExecutable.count(BB)) return;
-    DEBUG(cerr << "Marking BB Executable: " << BB);
+    DEBUG(cerr << "Marking BB Executable: " << *BB);
     BBExecutable.insert(BB);   // Basic block is executable!
     BBWorkList.push_back(BB);  // Add the block to the work list!
   }
@@ -177,35 +177,35 @@
   // operand made a transition, or the instruction is newly executable.  Change
   // the value type of I to reflect these changes if appropriate.
   //
-  void visitPHINode(PHINode *I);
+  void visitPHINode(PHINode &I);
 
   // Terminators
-  void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
-  void visitTerminatorInst(TerminatorInst *TI);
+  void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
+  void visitTerminatorInst(TerminatorInst &TI);
 
-  void visitUnaryOperator(Instruction *I);
-  void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
-  void visitBinaryOperator(Instruction *I);
-  void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
+  void visitUnaryOperator(Instruction &I);
+  void visitCastInst(CastInst &I) { visitUnaryOperator(I); }
+  void visitBinaryOperator(Instruction &I);
+  void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
 
   // Instructions that cannot be folded away...
-  void visitStoreInst     (Instruction *I) { /*returns void*/ }
-  void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
-  void visitCallInst      (Instruction *I) { markOverdefined(I); }
-  void visitInvokeInst    (Instruction *I) { markOverdefined(I); }
-  void visitAllocationInst(Instruction *I) { markOverdefined(I); }
-  void visitFreeInst      (Instruction *I) { /*returns void*/ }
+  void visitStoreInst     (Instruction &I) { /*returns void*/ }
+  void visitMemAccessInst (Instruction &I) { markOverdefined(&I); }
+  void visitCallInst      (Instruction &I) { markOverdefined(&I); }
+  void visitInvokeInst    (Instruction &I) { markOverdefined(&I); }
+  void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
+  void visitFreeInst      (Instruction &I) { /*returns void*/ }
 
-  void visitInstruction(Instruction *I) {
+  void visitInstruction(Instruction &I) {
     // If a new instruction is added to LLVM that we don't handle...
     cerr << "SCCP: Don't know how to handle: " << I;
-    markOverdefined(I);   // Just in case
+    markOverdefined(&I);   // Just in case
   }
 
   // getFeasibleSuccessors - Return a vector of booleans to indicate which
   // successors are reachable from a given terminator instruction.
   //
-  void getFeasibleSuccessors(TerminatorInst *I, std::vector<bool> &Succs);
+  void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
 
   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
   // block to the 'To' basic block is currently feasible...
@@ -218,8 +218,8 @@
   //
   void OperandChangedState(User *U) {
     // Only instructions use other variable values!
-    Instruction *I = cast<Instruction>(U);
-    if (!BBExecutable.count(I->getParent())) return;// Inst not executable yet!
+    Instruction &I = cast<Instruction>(*U);
+    if (!BBExecutable.count(I.getParent())) return;// Inst not executable yet!
     visit(I);
   }
 };
@@ -241,9 +241,9 @@
 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
 // and return true if the function was modified.
 //
-bool SCCP::runOnFunction(Function *F) {
+bool SCCP::runOnFunction(Function &F) {
   // Mark the first block of the function as being executable...
-  markExecutable(F->front());
+  markExecutable(&F.front());
 
   // Process the work lists until their are empty!
   while (!BBWorkList.empty() || !InstWorkList.empty()) {
@@ -284,8 +284,8 @@
   }
 
   if (DebugFlag) {
-    for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
-      if (!BBExecutable.count(*I))
+    for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
+      if (!BBExecutable.count(I))
         cerr << "BasicBlock Dead:" << *I;
   }
 
@@ -293,20 +293,19 @@
   // constants if we have found them to be of constant values.
   //
   bool MadeChanges = false;
-  for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
-    BasicBlock *BB = *FI;
+  for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
-      Instruction *Inst = *BI;
-      InstVal &IV = ValueState[Inst];
+      Instruction &Inst = *BI;
+      InstVal &IV = ValueState[&Inst];
       if (IV.isConstant()) {
         Constant *Const = IV.getConstant();
         DEBUG(cerr << "Constant: " << Const << " = " << Inst);
 
         // Replaces all of the uses of a variable with uses of the constant.
-        Inst->replaceAllUsesWith(Const);
+        Inst.replaceAllUsesWith(Const);
 
         // Remove the operator from the list of definitions... and delete it.
-        delete BB->getInstList().remove(BI);
+        BI = BB->getInstList().erase(BI);
 
         // Hey, we just changed something!
         MadeChanges = true;
@@ -315,7 +314,6 @@
         ++BI;
       }
     }
-  }
 
   // Reset state so that the next invocation will have empty data structures
   BBExecutable.clear();
@@ -328,9 +326,9 @@
 // getFeasibleSuccessors - Return a vector of booleans to indicate which
 // successors are reachable from a given terminator instruction.
 //
-void SCCP::getFeasibleSuccessors(TerminatorInst *TI, std::vector<bool> &Succs) {
-  assert(Succs.size() == TI->getNumSuccessors() && "Succs vector wrong size!");
-  if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
+void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
+  assert(Succs.size() == TI.getNumSuccessors() && "Succs vector wrong size!");
+  if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
     if (BI->isUnconditional()) {
       Succs[0] = true;
     } else {
@@ -343,14 +341,14 @@
         Succs[BCValue.getConstant() == ConstantBool::False] = true;
       }
     }
-  } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
+  } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
     // Invoke instructions successors are always executable.
     Succs[0] = Succs[1] = true;
-  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
+  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
     InstVal &SCValue = getValueState(SI->getCondition());
     if (SCValue.isOverdefined()) {  // Overdefined condition?
       // All destinations are executable!
-      Succs.assign(TI->getNumSuccessors(), true);
+      Succs.assign(TI.getNumSuccessors(), true);
     } else if (SCValue.isConstant()) {
       Constant *CPV = SCValue.getConstant();
       // Make sure to skip the "default value" which isn't a value
@@ -367,7 +365,7 @@
     }
   } else {
     cerr << "SCCP: Don't know how to handle: " << TI;
-    Succs.assign(TI->getNumSuccessors(), true);
+    Succs.assign(TI.getNumSuccessors(), true);
   }
 }
 
@@ -384,7 +382,7 @@
   // Check to make sure this edge itself is actually feasible now...
   TerminatorInst *FT = From->getTerminator();
   std::vector<bool> SuccFeasible(FT->getNumSuccessors());
-  getFeasibleSuccessors(FT, SuccFeasible);
+  getFeasibleSuccessors(*FT, SuccFeasible);
 
   // Check all edges from From to To.  If any are feasible, return true.
   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
@@ -414,8 +412,8 @@
 //    successors executable.
 //
 
-void SCCP::visitPHINode(PHINode *PN) {
-  unsigned NumValues = PN->getNumIncomingValues(), i;
+void SCCP::visitPHINode(PHINode &PN) {
+  unsigned NumValues = PN.getNumIncomingValues(), i;
   InstVal *OperandIV = 0;
 
   // Look at all of the executable operands of the PHI node.  If any of them
@@ -425,11 +423,11 @@
   // If there are no executable operands, the PHI remains undefined.
   //
   for (i = 0; i < NumValues; ++i) {
-    if (isEdgeFeasible(PN->getIncomingBlock(i), PN->getParent())) {
-      InstVal &IV = getValueState(PN->getIncomingValue(i));
+    if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
+      InstVal &IV = getValueState(PN.getIncomingValue(i));
       if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
-        markOverdefined(PN);
+        markOverdefined(&PN);
         return;
       }
 
@@ -445,7 +443,7 @@
           // Yes there is.  This means the PHI node is not constant.
           // You must be overdefined poor PHI.
           //
-          markOverdefined(PN);         // The PHI node now becomes overdefined
+          markOverdefined(&PN);         // The PHI node now becomes overdefined
           return;    // I'm done analyzing you
         }
       }
@@ -459,18 +457,18 @@
   //
   if (OperandIV) {
     assert(OperandIV->isConstant() && "Should only be here for constants!");
-    markConstant(PN, OperandIV->getConstant());  // Aquire operand value
+    markConstant(&PN, OperandIV->getConstant());  // Aquire operand value
   }
 }
 
-void SCCP::visitTerminatorInst(TerminatorInst *TI) {
-  std::vector<bool> SuccFeasible(TI->getNumSuccessors());
+void SCCP::visitTerminatorInst(TerminatorInst &TI) {
+  std::vector<bool> SuccFeasible(TI.getNumSuccessors());
   getFeasibleSuccessors(TI, SuccFeasible);
 
   // Mark all feasible successors executable...
   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
     if (SuccFeasible[i]) {
-      BasicBlock *Succ = TI->getSuccessor(i);
+      BasicBlock *Succ = TI.getSuccessor(i);
       markExecutable(Succ);
 
       // Visit all of the PHI nodes that merge values from this block...
@@ -478,49 +476,49 @@
       // constant now may not be.
       //
       for (BasicBlock::iterator I = Succ->begin();
-           PHINode *PN = dyn_cast<PHINode>(*I); ++I)
-        visitPHINode(PN);
+           PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
+        visitPHINode(*PN);
     }
 }
 
-void SCCP::visitUnaryOperator(Instruction *I) {
-  Value *V = I->getOperand(0);
+void SCCP::visitUnaryOperator(Instruction &I) {
+  Value *V = I.getOperand(0);
   InstVal &VState = getValueState(V);
   if (VState.isOverdefined()) {        // Inherit overdefinedness of operand
-    markOverdefined(I);
+    markOverdefined(&I);
   } else if (VState.isConstant()) {    // Propogate constant value
     Constant *Result = isa<CastInst>(I)
-      ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
-      : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
+      ? ConstantFoldCastInstruction(VState.getConstant(), I.getType())
+      : ConstantFoldUnaryInstruction(I.getOpcode(), VState.getConstant());
 
     if (Result) {
       // This instruction constant folds!
-      markConstant(I, Result);
+      markConstant(&I, Result);
     } else {
-      markOverdefined(I);   // Don't know how to fold this instruction.  :(
+      markOverdefined(&I);   // Don't know how to fold this instruction.  :(
     }
   }
 }
 
 // Handle BinaryOperators and Shift Instructions...
-void SCCP::visitBinaryOperator(Instruction *I) {
-  InstVal &V1State = getValueState(I->getOperand(0));
-  InstVal &V2State = getValueState(I->getOperand(1));
+void SCCP::visitBinaryOperator(Instruction &I) {
+  InstVal &V1State = getValueState(I.getOperand(0));
+  InstVal &V2State = getValueState(I.getOperand(1));
   if (V1State.isOverdefined() || V2State.isOverdefined()) {
-    markOverdefined(I);
+    markOverdefined(&I);
   } else if (V1State.isConstant() && V2State.isConstant()) {
     Constant *Result = 0;
     if (isa<BinaryOperator>(I))
-      Result = ConstantFoldBinaryInstruction(I->getOpcode(),
+      Result = ConstantFoldBinaryInstruction(I.getOpcode(),
                                              V1State.getConstant(),
                                              V2State.getConstant());
     else if (isa<ShiftInst>(I))
-      Result = ConstantFoldShiftInstruction(I->getOpcode(),
+      Result = ConstantFoldShiftInstruction(I.getOpcode(),
                                             V1State.getConstant(),
                                             V2State.getConstant());
     if (Result)
-      markConstant(I, Result);      // This instruction constant folds!
+      markConstant(&I, Result);      // This instruction constant folds!
     else
-      markOverdefined(I);   // Don't know how to fold this instruction.  :(
+      markOverdefined(&I);   // Don't know how to fold this instruction.  :(
   }
 }
diff --git a/lib/Transforms/Scalar/SimplifyCFG.cpp b/lib/Transforms/Scalar/SimplifyCFG.cpp
index 14c42e2..08611d2 100644
--- a/lib/Transforms/Scalar/SimplifyCFG.cpp
+++ b/lib/Transforms/Scalar/SimplifyCFG.cpp
@@ -26,7 +26,7 @@
   struct CFGSimplifyPass : public FunctionPass {
     const char *getPassName() const { return "Simplify CFG"; }
     
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
   };
 }
 
@@ -49,29 +49,28 @@
 // It is possible that we may require multiple passes over the code to fully
 // simplify the CFG.
 //
-bool CFGSimplifyPass::runOnFunction(Function *F) {
+bool CFGSimplifyPass::runOnFunction(Function &F) {
   std::set<BasicBlock*> Reachable;
-  bool Changed = MarkAliveBlocks(F->front(), Reachable);
+  bool Changed = MarkAliveBlocks(F.begin(), Reachable);
 
   // If there are unreachable blocks in the CFG...
-  if (Reachable.size() != F->size()) {
-    assert(Reachable.size() < F->size());
-    NumSimpl += F->size()-Reachable.size();
+  if (Reachable.size() != F.size()) {
+    assert(Reachable.size() < F.size());
+    NumSimpl += F.size()-Reachable.size();
 
     // Loop over all of the basic blocks that are not reachable, dropping all of
     // their internal references...
-    for (Function::iterator I = F->begin()+1, E = F->end(); I != E; ++I)
-      if (!Reachable.count(*I)) {
-        BasicBlock *BB = *I;
+    for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
+      if (!Reachable.count(BB)) {
         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
           if (Reachable.count(*SI))
             (*SI)->removePredecessor(BB);
         BB->dropAllReferences();
       }
     
-    for (Function::iterator I = F->begin()+1; I != F->end();)
-      if (!Reachable.count(*I))
-        delete F->getBasicBlocks().remove(I);
+    for (Function::iterator I = ++F.begin(); I != F.end();)
+      if (!Reachable.count(I))
+        I = F.getBasicBlockList().erase(I);
       else
         ++I;
 
@@ -85,12 +84,10 @@
     // Loop over all of the basic blocks (except the first one) and remove them
     // if they are unneeded...
     //
-    for (Function::iterator BBIt = F->begin()+1; BBIt != F->end(); ) {
-      if (SimplifyCFG(BBIt)) {
+    for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
+      if (SimplifyCFG(BBIt++)) {
         LocalChange = true;
         ++NumSimpl;
-      } else {
-        ++BBIt;
       }
     }
     Changed |= LocalChange;
diff --git a/lib/Transforms/Scalar/SymbolStripping.cpp b/lib/Transforms/Scalar/SymbolStripping.cpp
index cc0852e..46f4e44 100644
--- a/lib/Transforms/Scalar/SymbolStripping.cpp
+++ b/lib/Transforms/Scalar/SymbolStripping.cpp
@@ -42,29 +42,12 @@
   return RemovedSymbol;
 }
 
-
-// DoSymbolStripping - Remove all symbolic information from a function
-//
-static bool doSymbolStripping(Function *F) {
-  return StripSymbolTable(F->getSymbolTable());
-}
-
-// doStripGlobalSymbols - Remove all symbolic information from all functions 
-// in a module, and all module level symbols. (function names, etc...)
-//
-static bool doStripGlobalSymbols(Module *M) {
-  // Remove all symbols from functions in this module... and then strip all of
-  // the symbols in this module...
-  //  
-  return StripSymbolTable(M->getSymbolTable());
-}
-
 namespace {
   struct SymbolStripping : public FunctionPass {
     const char *getPassName() const { return "Strip Symbols from Functions"; }
 
-    virtual bool runOnFunction(Function *F) {
-      return doSymbolStripping(F);
+    virtual bool runOnFunction(Function &F) {
+      return StripSymbolTable(F.getSymbolTable());
     }
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesAll();
@@ -73,8 +56,8 @@
 
   struct FullSymbolStripping : public SymbolStripping {
     const char *getPassName() const { return "Strip Symbols from Module"; }
-    virtual bool doInitialization(Module *M) {
-      return doStripGlobalSymbols(M);
+    virtual bool doInitialization(Module &M) {
+      return StripSymbolTable(M.getSymbolTable());
     }
   };
 }
diff --git a/lib/Transforms/TransformInternals.cpp b/lib/Transforms/TransformInternals.cpp
index 9e7b63e..05bc694 100644
--- a/lib/Transforms/TransformInternals.cpp
+++ b/lib/Transforms/TransformInternals.cpp
@@ -140,12 +140,12 @@
         Offset -= Index*ElSize;               // Consume part of the offset
 
         if (BI) {              // Generate code?
-          BasicBlock *BB = (**BI)->getParent();
+          BasicBlock *BB = (*BI)->getParent();
           if (Expr.Var->getType() != Type::UIntTy) {
             CastInst *IdxCast = new CastInst(Expr.Var, Type::UIntTy);
             if (Expr.Var->hasName())
               IdxCast->setName(Expr.Var->getName()+"-idxcast");
-            *BI = BB->getInstList().insert(*BI, IdxCast)+1;
+            *BI = ++BB->getInstList().insert(*BI, IdxCast);
             Expr.Var = IdxCast;
           }
 
@@ -158,7 +158,7 @@
             if (Expr.Var->hasName())
               Scaler->setName(Expr.Var->getName()+"-scale");
 
-            *BI = BB->getInstList().insert(*BI, Scaler)+1;
+            *BI = ++BB->getInstList().insert(*BI, Scaler);
             Expr.Var = Scaler;
           }
 
@@ -168,7 +168,7 @@
                                                            Expr.Var, IndexAmt);
             if (Expr.Var->hasName())
               Offseter->setName(Expr.Var->getName()+"-offset");
-            *BI = BB->getInstList().insert(*BI, Offseter)+1;
+            *BI = ++BB->getInstList().insert(*BI, Offseter);
             Expr.Var = Offseter;
           }
         }
diff --git a/lib/Transforms/Utils/LowerAllocations.cpp b/lib/Transforms/Utils/LowerAllocations.cpp
index 80eab61..003be33 100644
--- a/lib/Transforms/Utils/LowerAllocations.cpp
+++ b/lib/Transforms/Utils/LowerAllocations.cpp
@@ -40,12 +40,12 @@
   // doPassInitialization - For the lower allocations pass, this ensures that a
   // module contains a declaration for a malloc and a free function.
   //
-  bool doInitialization(Module *M);
+  bool doInitialization(Module &M);
 
   // runOnBasicBlock - This method does the actual work of converting
   // instructions over, assuming that the pass has already been initialized.
   //
-  bool runOnBasicBlock(BasicBlock *BB);
+  bool runOnBasicBlock(BasicBlock &BB);
 };
 
 }
@@ -61,7 +61,7 @@
 //
 // This function is always successful.
 //
-bool LowerAllocations::doInitialization(Module *M) {
+bool LowerAllocations::doInitialization(Module &M) {
   const FunctionType *MallocType = 
     FunctionType::get(PointerType::get(Type::SByteTy),
                       vector<const Type*>(1, Type::UIntTy), false);
@@ -70,8 +70,8 @@
                       vector<const Type*>(1, PointerType::get(Type::SByteTy)),
                       false);
 
-  MallocFunc = M->getOrInsertFunction("malloc", MallocType);
-  FreeFunc   = M->getOrInsertFunction("free"  , FreeType);
+  MallocFunc = M.getOrInsertFunction("malloc", MallocType);
+  FreeFunc   = M.getOrInsertFunction("free"  , FreeType);
 
   return true;
 }
@@ -79,17 +79,18 @@
 // runOnBasicBlock - This method does the actual work of converting
 // instructions over, assuming that the pass has already been initialized.
 //
-bool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {
+bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
   bool Changed = false;
-  assert(MallocFunc && FreeFunc && BB && "Pass not initialized!");
+  assert(MallocFunc && FreeFunc && "Pass not initialized!");
+
+  BasicBlock::InstListType &BBIL = BB.getInstList();
 
   // Loop over all of the instructions, looking for malloc or free instructions
-  for (unsigned i = 0; i != BB->size(); ++i) {
-    BasicBlock::InstListType &BBIL = BB->getInstList();
-    if (MallocInst *MI = dyn_cast<MallocInst>(*(BBIL.begin()+i))) {
-      BBIL.remove(BBIL.begin()+i);   // remove the malloc instr...
-        
-      const Type *AllocTy = cast<PointerType>(MI->getType())->getElementType();
+  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
+    if (MallocInst *MI = dyn_cast<MallocInst>(&*I)) {
+      BBIL.remove(I);   // remove the malloc instr...
+
+      const Type *AllocTy = MI->getType()->getElementType();
       
       // Get the number of bytes to be allocated for one element of the
       // requested type...
@@ -103,35 +104,34 @@
         // Multiply it by the array size if neccesary...
         MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),
                                            MallocArg);
-        BBIL.insert(BBIL.begin()+i++, cast<Instruction>(MallocArg));
+        I = ++BBIL.insert(I, cast<Instruction>(MallocArg));
       }
       
       // Create the call to Malloc...
       CallInst *MCall = new CallInst(MallocFunc,
                                      vector<Value*>(1, MallocArg));
-      BBIL.insert(BBIL.begin()+i, MCall);
+      I = BBIL.insert(I, MCall);
       
       // Create a cast instruction to convert to the right type...
       CastInst *MCast = new CastInst(MCall, MI->getType());
-      BBIL.insert(BBIL.begin()+i+1, MCast);
+      I = BBIL.insert(++I, MCast);
       
       // Replace all uses of the old malloc inst with the cast inst
       MI->replaceAllUsesWith(MCast);
       delete MI;                          // Delete the malloc inst
       Changed = true;
       ++NumLowered;
-    } else if (FreeInst *FI = dyn_cast<FreeInst>(*(BBIL.begin()+i))) {
-      BBIL.remove(BB->getInstList().begin()+i);
+    } else if (FreeInst *FI = dyn_cast<FreeInst>(&*I)) {
+      BBIL.remove(I);
       
       // Cast the argument to free into a ubyte*...
       CastInst *MCast = new CastInst(FI->getOperand(0), 
                                      PointerType::get(Type::UByteTy));
-      BBIL.insert(BBIL.begin()+i, MCast);
+      I = ++BBIL.insert(I, MCast);
       
       // Insert a call to the free function...
-      CallInst *FCall = new CallInst(FreeFunc,
-                                     vector<Value*>(1, MCast));
-      BBIL.insert(BBIL.begin()+i+1, FCall);
+      CallInst *FCall = new CallInst(FreeFunc, vector<Value*>(1, MCast));
+      I = BBIL.insert(I, FCall);
       
       // Delete the old free instruction
       delete FI;
diff --git a/lib/Transforms/Utils/PromoteMemoryToRegister.cpp b/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
index 1afb11a..8a81ac7 100644
--- a/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
+++ b/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
@@ -52,7 +52,7 @@
     // runOnFunction - To run this pass, first we calculate the alloca
     // instructions that are safe for promotion, then we promote each one.
     //
-    virtual bool runOnFunction(Function *F);
+    virtual bool runOnFunction(Function &F);
 
     // getAnalysisUsage - We need dominance frontiers
     //
@@ -65,7 +65,7 @@
     void Traverse(BasicBlock *BB, BasicBlock *Pred, vector<Value*> &IncVals,
                   set<BasicBlock*> &Visited);
     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
-    void FindSafeAllocas(Function *F);
+    void FindSafeAllocas(Function &F);
   };
 
 }  // end of anonymous namespace
@@ -102,12 +102,12 @@
 
 // FindSafeAllocas - Find allocas that are safe to promote
 //
-void PromotePass::FindSafeAllocas(Function *F) {
-  BasicBlock *BB = F->getEntryNode();  // Get the entry node for the function
+void PromotePass::FindSafeAllocas(Function &F) {
+  BasicBlock &BB = F.getEntryNode();  // Get the entry node for the function
 
   // Look at all instructions in the entry node
-  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
-    if (AllocaInst *AI = dyn_cast<AllocaInst>(*I))       // Is it an alloca?
+  for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
+    if (AllocaInst *AI = dyn_cast<AllocaInst>(&*I))       // Is it an alloca?
       if (isSafeAlloca(AI)) {   // If safe alloca, add alloca to safe list
         AllocaLookup[AI] = Allocas.size();  // Keep reverse mapping
         Allocas.push_back(AI);
@@ -116,7 +116,7 @@
 
 
 
-bool PromotePass::runOnFunction(Function *F) {
+bool PromotePass::runOnFunction(Function &F) {
   // Calculate the set of safe allocas
   FindSafeAllocas(F);
 
@@ -178,7 +178,7 @@
   // and inserting the phi nodes we marked as necessary
   //
   set<BasicBlock*> Visited;         // The basic blocks we've already visited
-  Traverse(F->front(), 0, Values, Visited);
+  Traverse(F.begin(), 0, Values, Visited);
 
   // Remove all instructions marked by being placed in the KillList...
   //
@@ -186,8 +186,7 @@
     Instruction *I = KillList.back();
     KillList.pop_back();
 
-    I->getParent()->getInstList().remove(I);
-    delete I;
+    I->getParent()->getInstList().erase(I);
   }
 
   NumPromoted += Allocas.size();
@@ -248,7 +247,7 @@
 
   // keep track of the value of each variable we're watching.. how?
   for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
-    Instruction *I = *II; //get the instruction
+    Instruction *I = II; // get the instruction
 
     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
       Value *Ptr = LI->getPointerOperand();