Change MachineBasicBlock's vector of MachineInstr pointers into an
ilist of MachineInstr objects. This allows constant time removal and
insertion of MachineInstr instances from anywhere in each
MachineBasicBlock. It also allows for constant time splicing of
MachineInstrs into or out of MachineBasicBlocks.


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@11340 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Target/PowerPC/PowerPCTargetMachine.cpp b/lib/Target/PowerPC/PowerPCTargetMachine.cpp
index 88b33f0..54d0734 100644
--- a/lib/Target/PowerPC/PowerPCTargetMachine.cpp
+++ b/lib/Target/PowerPC/PowerPCTargetMachine.cpp
@@ -45,7 +45,6 @@
   PM.add(createRegisterAllocator());
   PM.add(createPrologEpilogCodeInserter());
   // <insert assembly code output passes here>
-  PM.add(createMachineCodeDeleter());
   return true; // change to `return false' when this actually works.
 }
 
diff --git a/lib/Target/SparcV9/InstrSched/InstrScheduling.cpp b/lib/Target/SparcV9/InstrSched/InstrScheduling.cpp
index 7d2ecec..f01196a 100644
--- a/lib/Target/SparcV9/InstrSched/InstrScheduling.cpp
+++ b/lib/Target/SparcV9/InstrSched/InstrScheduling.cpp
@@ -630,8 +630,8 @@
   // some NOPs from delay slots.  Also, PHIs are not included in the schedule.
   unsigned numInstr = 0;
   for (MachineBasicBlock::iterator I=MBB.begin(); I != MBB.end(); ++I)
-    if (! mii.isNop((*I)->getOpcode()) &&
-	! mii.isDummyPhiInstr((*I)->getOpcode()))
+    if (! mii.isNop(I->getOpcode()) &&
+	! mii.isDummyPhiInstr(I->getOpcode()))
       ++numInstr;
   assert(S.isched.getNumInstructions() >= numInstr &&
 	 "Lost some non-NOP instructions during scheduling!");
@@ -643,12 +643,12 @@
   // First find the dummy instructions at the start of the basic block
   MachineBasicBlock::iterator I = MBB.begin();
   for ( ; I != MBB.end(); ++I)
-    if (! mii.isDummyPhiInstr((*I)->getOpcode()))
+    if (! mii.isDummyPhiInstr(I->getOpcode()))
       break;
   
-  // Erase all except the dummy PHI instructions from MBB, and
+  // Remove all except the dummy PHI instructions from MBB, and
   // pre-allocate create space for the ones we will put back in.
-  MBB.erase(I, MBB.end());
+  while (I != MBB.end()) MBB.remove(I);
   
   InstrSchedule::const_iterator NIend = S.isched.end();
   for (InstrSchedule::const_iterator NI = S.isched.begin(); NI != NIend; ++NI)
@@ -1175,25 +1175,25 @@
   //  
   unsigned int firstDelaySlotIdx = node->getOrigIndexInBB() + 1;
   MachineBasicBlock& MBB = node->getMachineBasicBlock();
-  assert(MBB[firstDelaySlotIdx - 1] == brInstr &&
+  assert(&MBB[firstDelaySlotIdx - 1] == brInstr &&
          "Incorrect instr. index in basic block for brInstr");
   
   // First find all useful instructions already in the delay slots
   // and USE THEM.  We'll throw away the unused alternatives below
   // 
   for (unsigned i=firstDelaySlotIdx; i < firstDelaySlotIdx + ndelays; ++i)
-    if (! mii.isNop(MBB[i]->getOpcode()))
+    if (! mii.isNop(MBB[i].getOpcode()))
       sdelayNodeVec.insert(sdelayNodeVec.begin(),
-                           graph->getGraphNodeForInstr(MBB[i]));
+                           graph->getGraphNodeForInstr(&MBB[i]));
   
   // Then find the NOPs and keep only as many as are needed.
   // Put the rest in nopNodeVec to be deleted.
   for (unsigned i=firstDelaySlotIdx; i < firstDelaySlotIdx + ndelays; ++i)
-    if (mii.isNop(MBB[i]->getOpcode()))
+    if (mii.isNop(MBB[i].getOpcode()))
       if (sdelayNodeVec.size() < ndelays)
-        sdelayNodeVec.push_back(graph->getGraphNodeForInstr(MBB[i]));
+        sdelayNodeVec.push_back(graph->getGraphNodeForInstr(&MBB[i]));
       else {
-        nopNodeVec.push_back(graph->getGraphNodeForInstr(MBB[i]));
+        nopNodeVec.push_back(graph->getGraphNodeForInstr(&MBB[i]));
 	  
         //remove the MI from the Machine Code For Instruction
         const TerminatorInst *TI = MBB.getBasicBlock()->getTerminator();
@@ -1202,7 +1202,7 @@
           
         for(MachineCodeForInstruction::iterator mciI=llvmMvec.begin(), 
               mciE=llvmMvec.end(); mciI!=mciE; ++mciI){
-          if (*mciI==MBB[i])
+          if (*mciI == &MBB[i])
             llvmMvec.erase(mciI);
         }
       }
@@ -1282,10 +1282,10 @@
   // 
   delayNodeVec.clear();
   for (unsigned i=0; i < MBB.size(); ++i)
-    if (MBB[i] != brInstr &&
-        mii.getNumDelaySlots(MBB[i]->getOpcode()) > 0)
+    if (&MBB[i] != brInstr &&
+        mii.getNumDelaySlots(MBB[i].getOpcode()) > 0)
     {
-      SchedGraphNode* node = graph->getGraphNodeForInstr(MBB[i]);
+      SchedGraphNode* node = graph->getGraphNodeForInstr(&MBB[i]);
       ReplaceNopsWithUsefulInstr(S, node, delayNodeVec, graph);
     }
 }
diff --git a/lib/Target/SparcV9/InstrSched/SchedGraph.cpp b/lib/Target/SparcV9/InstrSched/SchedGraph.cpp
index fe150c2..01ca36f 100644
--- a/lib/Target/SparcV9/InstrSched/SchedGraph.cpp
+++ b/lib/Target/SparcV9/InstrSched/SchedGraph.cpp
@@ -53,7 +53,8 @@
 
 SchedGraphNode::SchedGraphNode(unsigned NID, MachineBasicBlock *mbb,
                                int   indexInBB, const TargetMachine& Target)
-  : SchedGraphNodeCommon(NID,indexInBB), MBB(mbb), MI(mbb ? (*mbb)[indexInBB] : 0) {
+  : SchedGraphNodeCommon(NID,indexInBB), MBB(mbb),
+    MI(mbb ? &(*mbb)[indexInBB] : (MachineInstr*)0) {
   if (MI) {
     MachineOpCode mopCode = MI->getOpcode();
     latency = Target.getInstrInfo().hasResultInterlock(mopCode)
@@ -183,10 +184,10 @@
   // all preceding instructions in the basic block.  Use 0 latency again.
   // 
   for (unsigned i=0, N=MBB.size(); i < N; i++)  {
-    if (MBB[i] == termMvec[first])   // reached the first branch
+    if (&MBB[i] == termMvec[first])   // reached the first branch
       break;
     
-    SchedGraphNode* fromNode = this->getGraphNodeForInstr(MBB[i]);
+    SchedGraphNode* fromNode = this->getGraphNodeForInstr(&MBB[i]);
     if (fromNode == NULL)
       continue;			// dummy instruction, e.g., PHI
     
@@ -198,11 +199,11 @@
     // the terminator) that also have delay slots, add an outgoing edge
     // from the instruction to the instructions in the delay slots.
     // 
-    unsigned d = mii.getNumDelaySlots(MBB[i]->getOpcode());
+    unsigned d = mii.getNumDelaySlots(MBB[i].getOpcode());
     assert(i+d < N && "Insufficient delay slots for instruction?");
       
     for (unsigned j=1; j <= d; j++) {
-      SchedGraphNode* toNode = this->getGraphNodeForInstr(MBB[i+j]);
+      SchedGraphNode* toNode = this->getGraphNodeForInstr(&MBB[i+j]);
       assert(toNode && "No node for machine instr in delay slot?");
       (void) new SchedGraphEdge(fromNode, toNode,
                                 SchedGraphEdge::CtrlDep,
@@ -554,9 +555,9 @@
   // Build graph nodes for each VM instruction and gather def/use info.
   // Do both those together in a single pass over all machine instructions.
   for (unsigned i=0; i < MBB.size(); i++)
-    if (!mii.isDummyPhiInstr(MBB[i]->getOpcode())) {
+    if (!mii.isDummyPhiInstr(MBB[i].getOpcode())) {
       SchedGraphNode* node = new SchedGraphNode(getNumNodes(), &MBB, i, target);
-      noteGraphNodeForInstr(MBB[i], node);
+      noteGraphNodeForInstr(&MBB[i], node);
       
       // Remember all register references and value defs
       findDefUseInfoAtInstr(target, node, memNodeVec, callDepNodeVec,
@@ -632,7 +633,7 @@
   
   // Then add incoming def-use (SSA) edges for each machine instruction.
   for (unsigned i=0, N=MBB.size(); i < N; i++)
-    addEdgesForInstruction(*MBB[i], valueToDefVecMap, target);
+    addEdgesForInstruction(MBB[i], valueToDefVecMap, target);
 
   // Then add edges for dependences on machine registers
   this->addMachineRegEdges(regToRefVecMap, target);
diff --git a/lib/Target/SparcV9/InstrSelection/InstrSelection.cpp b/lib/Target/SparcV9/InstrSelection/InstrSelection.cpp
index 5d9d0a3..4ddc4ed 100644
--- a/lib/Target/SparcV9/InstrSelection/InstrSelection.cpp
+++ b/lib/Target/SparcV9/InstrSelection/InstrSelection.cpp
@@ -283,10 +283,7 @@
       break;
     }
 
-  // find the position of first machine instruction generated by the
-  // terminator of this BB
-  MachineBasicBlock::iterator MCIt =
-    std::find(MBB->begin(), MBB->end(), FirstMIOfTerm);
+  MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
 
   assert(MCIt != MBB->end() && "Start inst of terminator not found");
   
diff --git a/lib/Target/SparcV9/LiveVar/BBLiveVar.cpp b/lib/Target/SparcV9/LiveVar/BBLiveVar.cpp
index d8878ad..e3515e8 100644
--- a/lib/Target/SparcV9/LiveVar/BBLiveVar.cpp
+++ b/lib/Target/SparcV9/LiveVar/BBLiveVar.cpp
@@ -41,7 +41,7 @@
   // iterate over all the machine instructions in BB
   for (MachineBasicBlock::const_reverse_iterator MII = MBB.rbegin(),
          MIE = MBB.rend(); MII != MIE; ++MII) {
-    const MachineInstr *MI = *MII;
+    const MachineInstr *MI = &*MII;
     
     if (DEBUG_LV >= LV_DEBUG_Verbose) {
       std::cerr << " *Iterating over machine instr ";
diff --git a/lib/Target/SparcV9/LiveVar/FunctionLiveVarInfo.cpp b/lib/Target/SparcV9/LiveVar/FunctionLiveVarInfo.cpp
index fd23a23..e2822c3 100644
--- a/lib/Target/SparcV9/LiveVar/FunctionLiveVarInfo.cpp
+++ b/lib/Target/SparcV9/LiveVar/FunctionLiveVarInfo.cpp
@@ -283,7 +283,7 @@
   for (MachineBasicBlock::const_reverse_iterator MII = MIVec.rbegin(),
          MIE = MIVec.rend(); MII != MIE; ++MII) {  
     // MI is cur machine inst
-    const MachineInstr *MI = *MII;  
+    const MachineInstr *MI = &*MII;  
 
     MInst2LVSetAI[MI] = SetAI;                 // record in After Inst map
 
@@ -299,7 +299,7 @@
       MachineBasicBlock::const_iterator fwdMII = MII.base(); // ptr to *next* MI
       for (unsigned i = 0; i < DS; ++i, ++fwdMII) {
         assert(fwdMII != MIVec.end() && "Missing instruction in delay slot?");
-        MachineInstr* DelaySlotMI = *fwdMII;
+        const MachineInstr* DelaySlotMI = fwdMII;
         if (! TM.getInstrInfo().isNop(DelaySlotMI->getOpcode())) {
           set_union(*MInst2LVSetBI[DelaySlotMI], *NewSet);
           if (i+1 == DS)
diff --git a/lib/Target/SparcV9/MappingInfo.cpp b/lib/Target/SparcV9/MappingInfo.cpp
index 2afde6b..4648c54 100644
--- a/lib/Target/SparcV9/MappingInfo.cpp
+++ b/lib/Target/SparcV9/MappingInfo.cpp
@@ -153,7 +153,7 @@
   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
        BI != BE; ++BI) {
     MachineBasicBlock &miBB = *BI;
-    key[miBB[0]] = i;
+    key[&miBB.front()] = i;
     i = i+(miBB.size());
   }
 }
@@ -174,7 +174,7 @@
     unsigned j = 0;
     for(MachineBasicBlock::iterator miI = miBB.begin(), miE = miBB.end();
         miI != miE; ++miI, ++j) {
-      key[*miI] = j;
+      key[miI] = j;
     }
   }
 }
@@ -195,7 +195,7 @@
        BI != BE; ++BI, ++bb) {
     MachineBasicBlock &miBB = *BI;
     writeNumber(bb);
-    writeNumber(BBkey[miBB[0]]);
+    writeNumber(BBkey[&miBB.front()]);
     writeNumber(miBB.size());
   }
 }
diff --git a/lib/Target/SparcV9/RegAlloc/LiveRangeInfo.cpp b/lib/Target/SparcV9/RegAlloc/LiveRangeInfo.cpp
index 2c0196d..f28ca86 100644
--- a/lib/Target/SparcV9/RegAlloc/LiveRangeInfo.cpp
+++ b/lib/Target/SparcV9/RegAlloc/LiveRangeInfo.cpp
@@ -171,7 +171,7 @@
     // iterate over all the machine instructions in BB
     for(MachineBasicBlock::iterator MInstIterator = MBB.begin();
         MInstIterator != MBB.end(); ++MInstIterator) {  
-      MachineInstr *MInst = *MInstIterator; 
+      MachineInstr *MInst = MInstIterator; 
 
       // If the machine instruction is a  call/return instruction, add it to
       // CallRetInstrList for processing its args, ret value, and ret addr.
@@ -330,7 +330,7 @@
 
     // iterate over all the machine instructions in BB
     for(MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII){
-      const MachineInstr *MI = *MII;
+      const MachineInstr *MI = MII;
 
       if( DEBUG_RA >= RA_DEBUG_LiveRanges) {
 	std::cerr << " *Iterating over machine instr ";
diff --git a/lib/Target/SparcV9/RegAlloc/PhyRegAlloc.cpp b/lib/Target/SparcV9/RegAlloc/PhyRegAlloc.cpp
index e45f13b..0cb1776 100644
--- a/lib/Target/SparcV9/RegAlloc/PhyRegAlloc.cpp
+++ b/lib/Target/SparcV9/RegAlloc/PhyRegAlloc.cpp
@@ -233,7 +233,7 @@
 
     // iterate over all the machine instructions in BB
     for ( ; MII != MBB.end(); ++MII) {
-      const MachineInstr *MInst = *MII;
+      const MachineInstr *MInst = MII;
 
       // get the LV set after the instruction
       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
@@ -355,25 +355,13 @@
   MII = MBB.insert(MII, newMI);
 }
 
-// used by: updateMachineCode (1 time)
-inline void DeleteInstruction(MachineBasicBlock& MBB,
-                              MachineBasicBlock::iterator& MII) {
-  MII = MBB.erase(MII);
-}
-
-// used by: updateMachineCode (1 time)
-inline void SubstituteInPlace(MachineInstr* newMI, MachineBasicBlock& MBB,
-                              MachineBasicBlock::iterator MII) {
-  *MII = newMI;
-}
-
 // used by: updateMachineCode (2 times)
 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
                                 MachineBasicBlock& MBB,
                                 MachineBasicBlock::iterator& MII,
                                 const std::string& msg) {
   if (!IBef.empty()) {
-      MachineInstr* OrigMI = *MII;
+      MachineInstr* OrigMI = MII;
       std::vector<MachineInstr *>::iterator AdIt; 
       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
           if (DEBUG_RA) {
@@ -391,7 +379,7 @@
                                MachineBasicBlock::iterator& MII,
                                const std::string& msg) {
   if (!IAft.empty()) {
-      MachineInstr* OrigMI = *MII;
+      MachineInstr* OrigMI = MII;
       std::vector<MachineInstr *>::iterator AdIt; 
       for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
           if (DEBUG_RA) {
@@ -442,14 +430,14 @@
 ///
 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
                                     MachineBasicBlock &MBB) {
-  MachineInstr* MInst = *MII;
+  MachineInstr* MInst = MII;
   unsigned Opcode = MInst->getOpcode();
 
   // Reset tmp stack positions so they can be reused for each machine instr.
   MF->getInfo()->popAllTempValues();  
 
   // Mark the operands for which regs have been allocated.
-  bool instrNeedsSpills = markAllocatedRegs(*MII);
+  bool instrNeedsSpills = markAllocatedRegs(MII);
 
 #ifndef NDEBUG
   // Mark that the operands have been updated.  Later,
@@ -506,7 +494,7 @@
     // their assigned registers or insert spill code, as appropriate. 
     // Also, fix operands of call/return instructions.
     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
-      if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpcode()))
+      if (! TM.getInstrInfo().isDummyPhiInstr(MII->getOpcode()))
         updateInstruction(MII, MBB);
 
     // Now, move code out of delay slots of branches and returns if needed.
@@ -523,56 +511,58 @@
     // 
     // If the annul bit of the branch is set, neither of these is legal!
     // If so, we need to handle spill differently but annulling is not yet used.
-    for (MachineBasicBlock::iterator MII = MBB.begin();
-         MII != MBB.end(); ++MII)
+    for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
       if (unsigned delaySlots =
-          TM.getInstrInfo().getNumDelaySlots((*MII)->getOpcode())) { 
-          MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
+          TM.getInstrInfo().getNumDelaySlots(MII->getOpcode())) { 
+          MachineBasicBlock::iterator DelaySlotMI = MII; ++DelaySlotMI;
+          assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
           
           // Check the 2 conditions above:
           // (1) Does a branch need instructions added after it?
           // (2) O/w does delay slot instr. need instrns before or after?
-          bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpcode()) ||
-                           TM.getInstrInfo().isReturn(MInst->getOpcode()));
+          bool isBranch = (TM.getInstrInfo().isBranch(MII->getOpcode()) ||
+                           TM.getInstrInfo().isReturn(MII->getOpcode()));
           bool cond1 = (isBranch &&
-                        AddedInstrMap.count(MInst) &&
-                        AddedInstrMap[MInst].InstrnsAfter.size() > 0);
+                        AddedInstrMap.count(MII) &&
+                        AddedInstrMap[MII].InstrnsAfter.size() > 0);
           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
 
           if (cond1 || cond2) {
-              assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
+              assert((MII->getOpCodeFlags() & AnnulFlag) == 0 &&
                      "FIXME: Moving an annulled delay slot instruction!"); 
               assert(delaySlots==1 &&
                      "InsertBefore does not yet handle >1 delay slots!");
-              InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
-
-              // In case (1), delete it and don't replace with anything!
-              // Otherwise (i.e., case (2) only) replace it with a NOP.
-              if (cond1) {
-                DeleteInstruction(MBB, ++MII); // MII now points to next inst.
-                --MII;                         // reset MII for ++MII of loop
-              }
-              else
-                SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
-                                  MBB, MII+1);        // replace with NOP
 
               if (DEBUG_RA) {
                 std::cerr << "\nRegAlloc: Moved instr. with added code: "
                      << *DelaySlotMI
-                     << "           out of delay slots of instr: " << *MInst;
+                     << "           out of delay slots of instr: " << *MII;
+              }
+
+              // move instruction before branch
+              MBB.insert(MII, MBB.remove(DelaySlotMI));
+
+              // On cond1 we are done (we already moved the
+              // instruction out of the delay slot). On cond2 we need
+              // to insert a nop in place of the moved instruction
+              if (cond2) {
+                MBB.insert(MII, BuildMI(TM.getInstrInfo().getNOPOpCode(),1));
               }
             }
-          else
+          else {
             // For non-branch instr with delay slots (probably a call), move
             // InstrAfter to the instr. in the last delay slot.
-            move2DelayedInstr(*MII, *(MII+delaySlots));
-        }
+            MachineBasicBlock::iterator tmp = MII;
+            std::advance(tmp, delaySlots);
+            move2DelayedInstr(MII, tmp);
+          }
+      }
 
     // Finally iterate over all instructions in BB and insert before/after
     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
-      MachineInstr *MInst = *MII; 
+      MachineInstr *MInst = MII; 
 
       // do not process Phis
       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpcode()))
@@ -635,7 +625,7 @@
                                        MachineBasicBlock::iterator& MII,
                                        MachineBasicBlock &MBB,
 				       const unsigned OpNum) {
-  MachineInstr *MInst = *MII;
+  MachineInstr *MInst = MII;
   const BasicBlock *BB = MBB.getBasicBlock();
 
   assert((! TM.getInstrInfo().isCall(MInst->getOpcode()) || OpNum == 0) &&
@@ -658,7 +648,8 @@
   // include all live variables before that branch or return -- we don't want to
   // trample those!  Verify that the set is included in the LV set before MInst.
   if (MII != MBB.begin()) {
-    MachineInstr *PredMI = *(MII-1);
+    MachineBasicBlock::iterator PredMI = MII;
+    --PredMI;
     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpcode()))
       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
              .empty() && "Live-var set before branch should be included in "
diff --git a/lib/Target/SparcV9/SparcV9AsmPrinter.cpp b/lib/Target/SparcV9/SparcV9AsmPrinter.cpp
index af86e05..20fbfa3 100644
--- a/lib/Target/SparcV9/SparcV9AsmPrinter.cpp
+++ b/lib/Target/SparcV9/SparcV9AsmPrinter.cpp
@@ -721,7 +721,7 @@
   // Loop over all of the instructions in the basic block...
   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
        MII != MIE; ++MII)
-    emitMachineInst(*MII);
+    emitMachineInst(MII);
   toAsm << "\n";  // Separate BB's with newlines
 }
 
diff --git a/lib/Target/SparcV9/SparcV9CodeEmitter.cpp b/lib/Target/SparcV9/SparcV9CodeEmitter.cpp
index 495f791..753f5d3 100644
--- a/lib/Target/SparcV9/SparcV9CodeEmitter.cpp
+++ b/lib/Target/SparcV9/SparcV9CodeEmitter.cpp
@@ -778,7 +778,7 @@
   currBB = MBB.getBasicBlock();
   BBLocations[currBB] = MCE.getCurrentPCValue();
   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
-    unsigned binCode = getBinaryCodeForInstr(**I);
+    unsigned binCode = getBinaryCodeForInstr(*I);
     if (binCode == (1 << 30)) {
       // this is an invalid call: the addr is out of bounds. that means a code
       // sequence has already been emitted, and this is a no-op
diff --git a/lib/Target/SparcV9/SparcV9PeepholeOpts.cpp b/lib/Target/SparcV9/SparcV9PeepholeOpts.cpp
index 60c7bcb..a69171c 100644
--- a/lib/Target/SparcV9/SparcV9PeepholeOpts.cpp
+++ b/lib/Target/SparcV9/SparcV9PeepholeOpts.cpp
@@ -31,14 +31,14 @@
   // Check if this instruction is in a delay slot of its predecessor.
   if (BBI != mvec.begin()) {
       const TargetInstrInfo& mii = target.getInstrInfo();
-      MachineInstr* predMI = *(BBI-1);
+      MachineBasicBlock::iterator predMI = BBI; --predMI;
       if (unsigned ndelay = mii.getNumDelaySlots(predMI->getOpcode())) {
         // This instruction is in a delay slot of its predecessor, so
         // replace it with a nop. By replacing in place, we save having
         // to update the I-I maps.
         // 
         assert(ndelay == 1 && "Not yet handling multiple-delay-slot targets");
-        (*BBI)->replace(mii.getNOPOpCode(), 0);
+        BBI->replace(mii.getNOPOpCode(), 0);
         return;
       }
   }
@@ -99,7 +99,7 @@
 RemoveUselessCopies(MachineBasicBlock& mvec,
                     MachineBasicBlock::iterator& BBI,
                     const TargetMachine& target) {
-  if (IsUselessCopy(target, *BBI)) {
+  if (IsUselessCopy(target, BBI)) {
     DeleteInstruction(mvec, BBI, target);
     return true;
   }
@@ -148,16 +148,8 @@
   assert(MBB && "MachineBasicBlock object not found for specified block!");
   MachineBasicBlock &mvec = *MBB;
 
-  // Iterate over all machine instructions in the BB
-  // Use a reverse iterator to allow deletion of MI or any instruction after it.
-  // Insertions or deletions *before* MI are not safe.
-  // 
-  for (MachineBasicBlock::reverse_iterator RI=mvec.rbegin(),
-         RE=mvec.rend(); RI != RE; ) {
-    MachineBasicBlock::iterator BBI = RI.base()-1; // save before incr
-    ++RI;             // pre-increment to delete MI or after it
-    visit(mvec, BBI);
-  }
+  for (MachineBasicBlock::iterator I = mvec.begin(), E = mvec.end(); I != E; )
+    visit(mvec, I++);
 
   return true;
 }
diff --git a/lib/Target/SparcV9/SparcV9PrologEpilogInserter.cpp b/lib/Target/SparcV9/SparcV9PrologEpilogInserter.cpp
index 4398f6b..55db233 100644
--- a/lib/Target/SparcV9/SparcV9PrologEpilogInserter.cpp
+++ b/lib/Target/SparcV9/SparcV9PrologEpilogInserter.cpp
@@ -157,12 +157,12 @@
       unsigned numNOPs = 0;
       while (termMvec.back()->getOpcode() == V9::NOP)
       {
-        assert( termMvec.back() == MBB.back());
-        delete MBB.pop_back();
+        assert( termMvec.back() == &MBB.back());
         termMvec.pop_back();
+        MBB.erase(&MBB.back());
         ++numNOPs;
       }
-      assert(termMvec.back() == MBB.back());
+      assert(termMvec.back() == &MBB.back());
         
       // Check that we found the right number of NOPs and have the right
       // number of instructions to replace them.
diff --git a/lib/Target/X86/FloatingPoint.cpp b/lib/Target/X86/FloatingPoint.cpp
index 0a0fe9b..53f6ec0 100644
--- a/lib/Target/X86/FloatingPoint.cpp
+++ b/lib/Target/X86/FloatingPoint.cpp
@@ -118,7 +118,7 @@
 
 	// Emit an fxch to update the runtime processors version of the state
 	MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
-	I = 1+MBB->insert(I, MI);
+	MBB->insert(I, MI);
 	NumFXCH++;
       }
     }
@@ -129,7 +129,7 @@
       pushReg(AsReg);   // New register on top of stack
 
       MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
-      I = 1+MBB->insert(I, MI);
+      MBB->insert(I, MI);
     }
 
     // popStackAfter - Pop the current value off of the top of the FP stack
@@ -193,12 +193,17 @@
   MBB = &BB;
   
   for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
-    MachineInstr *MI = *I;
+    MachineInstr *MI = I;
     unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
     if ((Flags & X86II::FPTypeMask) == X86II::NotFP)
       continue;  // Efficiently ignore non-fp insts!
 
-    MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
+    MachineInstr *PrevMI = 0;
+    if (I != BB.begin()) {
+        MachineBasicBlock::iterator tmp = I;
+        --tmp;
+        PrevMI = tmp;
+    }
 
     ++NumFP;  // Keep track of # of pseudo instrs
     DEBUG(std::cerr << "\nFPInst:\t";
@@ -242,15 +247,17 @@
     }
     
     // Print out all of the instructions expanded to if -debug
-    DEBUG(if (*I == PrevMI) {
+    DEBUG(if (&*I == PrevMI) {
             std::cerr<< "Just deleted pseudo instruction\n";
           } else {
 	    MachineBasicBlock::iterator Start = I;
 	    // Rewind to first instruction newly inserted.
-	    while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
+	    while (Start != BB.begin() &&
+                   --Start != MachineBasicBlock::iterator(PrevMI));
+            ++Start;
 	    std::cerr << "Inserted instructions:\n\t";
-	    (*Start)->print(std::cerr, MF.getTarget());
-	    while (++Start != I+1);
+	    Start->print(std::cerr, MF.getTarget());
+	    while (++Start != I); ++Start;
 	  }
 	  dumpStack();
 	  );
@@ -344,15 +351,15 @@
   RegMap[Stack[--StackTop]] = ~0;     // Update state
 
   // Check to see if there is a popping version of this instruction...
-  int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
+  int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), I->getOpcode());
   if (Opcode != -1) {
-    (*I)->setOpcode(Opcode);
+    I->setOpcode(Opcode);
     if (Opcode == X86::FUCOMPPr)
-      (*I)->RemoveOperand(0);
+      I->RemoveOperand(0);
 
   } else {    // Insert an explicit pop
     MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
-    I = MBB->insert(I+1, MI);
+    I = MBB->insert(++I, MI);
   }
 }
 
@@ -371,7 +378,7 @@
 /// handleZeroArgFP - ST(0) = fld0    ST(0) = flds <mem>
 ///
 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   unsigned DestReg = getFPReg(MI->getOperand(0));
   MI->RemoveOperand(0);   // Remove the explicit ST(0) operand
 
@@ -382,7 +389,7 @@
 /// handleOneArgFP - fst <mem>, ST(0)
 ///
 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   assert((MI->getNumOperands() == 5 || MI->getNumOperands() == 1) &&
          "Can only handle fst* & ftst instructions!");
 
@@ -418,7 +425,7 @@
 /// handleOneArgFPRW - fchs - ST(0) = -ST(0)
 ///
 void FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   assert(MI->getNumOperands() == 2 && "Can only handle fst* instructions!");
 
   // Is this the last use of the source register?
@@ -503,7 +510,7 @@
 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
   ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
   ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
 
   unsigned NumOperands = MI->getNumOperands();
   assert(NumOperands == 3 ||
@@ -588,7 +595,8 @@
   unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
 
   // Replace the old instruction with a new instruction
-  *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
+  MBB->remove(I);
+  I = MBB->insert(I, BuildMI(Opcode, 1).addReg(getSTReg(NotTOS)));
 
   // If both operands are killed, pop one off of the stack in addition to
   // overwriting the other one.
@@ -617,7 +625,7 @@
 	Stack[--StackTop] = ~0;
 	
 	MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
-	I = MBB->insert(I+1, MI);
+	I = MBB->insert(++I, MI);
       }
     }
   }
@@ -639,7 +647,7 @@
 /// instructions.
 ///
 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   switch (MI->getOpcode()) {
   default: assert(0 && "Unknown SpecialFP instruction!");
   case X86::FpGETRESULT:  // Appears immediately after a call returning FP type!
@@ -675,6 +683,6 @@
   }
   }
 
-  I = MBB->erase(I)-1;  // Remove the pseudo instruction
-  delete MI;
+  I = MBB->erase(I);  // Remove the pseudo instruction
+  --I;
 }
diff --git a/lib/Target/X86/InstSelectSimple.cpp b/lib/Target/X86/InstSelectSimple.cpp
index af2544f..9df7697 100644
--- a/lib/Target/X86/InstSelectSimple.cpp
+++ b/lib/Target/X86/InstSelectSimple.cpp
@@ -37,23 +37,21 @@
 /// instruction at as well as a basic block.  This is the version for when you
 /// have a destination register in mind.
 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
-                                      MachineBasicBlock::iterator &I,
+                                      MachineBasicBlock::iterator I,
                                       int Opcode, unsigned NumOperands,
                                       unsigned DestReg) {
-  assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
-  I = MBB->insert(I, MI)+1;
+  MBB->insert(I, MI);
   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
 }
 
 /// BMI - A special BuildMI variant that takes an iterator to insert the
 /// instruction at as well as a basic block.
 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
-                                      MachineBasicBlock::iterator &I,
+                                      MachineBasicBlock::iterator I,
                                       int Opcode, unsigned NumOperands) {
-  assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
-  I = MBB->insert(I, MI)+1;
+  MBB->insert(I, MI);
   return MachineInstrBuilder(MI);
 }
 
@@ -541,19 +539,19 @@
     MachineBasicBlock *MBB = MBBMap[I];
 
     // Loop over all of the PHI nodes in the LLVM basic block...
-    unsigned NumPHIs = 0;
+    MachineInstr* instr = MBB->begin();
     for (BasicBlock::const_iterator I = BB->begin();
          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
 
       // Create a new machine instr PHI node, and insert it.
       unsigned PHIReg = getReg(*PN);
       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
-      MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
+      MBB->insert(instr, PhiMI);
 
       MachineInstr *LongPhiMI = 0;
       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
-        MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
+        MBB->insert(instr, LongPhiMI);
       }
 
       // PHIValues - Map of blocks to incoming virtual registers.  We use this
@@ -588,7 +586,7 @@
             MachineBasicBlock::iterator PI = PredMBB->begin();
 
             // Skip over any PHI nodes though!
-            while (PI != PredMBB->end() && (*PI)->getOpcode() == X86::PHI)
+            while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
               ++PI;
 
             ValReg = getReg(Val, PredMBB, PI);
diff --git a/lib/Target/X86/PeepholeOptimizer.cpp b/lib/Target/X86/PeepholeOptimizer.cpp
index 59ebb15..f09e8d7 100644
--- a/lib/Target/X86/PeepholeOptimizer.cpp
+++ b/lib/Target/X86/PeepholeOptimizer.cpp
@@ -50,8 +50,11 @@
 
 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
 			  MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
-  MachineInstr *Next = (I+1 != MBB.end()) ? *(I+1) : 0;
+  assert(I != MBB.end());
+  MachineBasicBlock::iterator NextI = I; ++NextI;
+
+  MachineInstr *MI = I;
+  MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
   unsigned Size = 0;
   switch (MI->getOpcode()) {
   case X86::MOVrr8:
@@ -59,7 +62,6 @@
   case X86::MOVrr32:   // Destroy X = X copies...
     if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
       I = MBB.erase(I);
-      delete MI;
       return true;
     }
     return false;
@@ -82,8 +84,8 @@
         }
         unsigned R0 = MI->getOperand(0).getReg();
         unsigned R1 = MI->getOperand(1).getReg();
-        *I = BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val);
-        delete MI;
+        I = MBB.insert(MBB.erase(I),
+                       BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
         return true;
       }
     }
@@ -114,8 +116,8 @@
         case X86::XORri32:  Opcode = X86::XORri32b; break;
         }
         unsigned R0 = MI->getOperand(0).getReg();
-        *I = BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val);
-        delete MI;
+        I = MBB.insert(MBB.erase(I),
+                    BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
         return true;
       }
     }
@@ -132,8 +134,8 @@
       if (Val == 0) {                              // mov EAX, 0 -> xor EAX, EAX
 	static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
 	unsigned Reg = MI->getOperand(0).getReg();
-	*I = BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg);
-	delete MI;
+	I = MBB.insert(MBB.erase(I),
+                       BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
 	return true;
       } else if (Val == -1) {                     // mov EAX, -1 -> or EAX, -1
 	// TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
@@ -145,8 +147,6 @@
     if (Next->getOpcode() == X86::BSWAPr32 &&
 	MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
       I = MBB.erase(MBB.erase(I));
-      delete MI;
-      delete Next;
       return true;
     }
     return false;
@@ -189,12 +189,11 @@
     virtual bool runOnMachineFunction(MachineFunction &MF) {
       for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
         for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
-          MachineInstr *MI = *I;
-          for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
-            MachineOperand &MO = MI->getOperand(i);
+          for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
+            MachineOperand &MO = I->getOperand(i);
             if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
                 MRegisterInfo::isVirtualRegister(MO.getReg()))
-              setDefinition(MO.getReg(), MI);
+              setDefinition(MO.getReg(), I);
           }
         }
       return false;
@@ -377,8 +376,10 @@
 
 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
-  MachineInstr *Next = (I+1 != MBB.end()) ? *(I+1) : 0;
+  MachineBasicBlock::iterator NextI = I; ++NextI;
+
+  MachineInstr *MI = I;
+  MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
 
   bool Changed = false;
 
diff --git a/lib/Target/X86/Printer.cpp b/lib/Target/X86/Printer.cpp
index 0cf1273..840aa4a 100644
--- a/lib/Target/X86/Printer.cpp
+++ b/lib/Target/X86/Printer.cpp
@@ -365,7 +365,7 @@
 	 II != E; ++II) {
       // Print the assembly for the instruction.
       O << "\t";
-      printMachineInstruction(*II);
+      printMachineInstruction(II);
     }
   }
 
diff --git a/lib/Target/X86/X86AsmPrinter.cpp b/lib/Target/X86/X86AsmPrinter.cpp
index 0cf1273..840aa4a 100644
--- a/lib/Target/X86/X86AsmPrinter.cpp
+++ b/lib/Target/X86/X86AsmPrinter.cpp
@@ -365,7 +365,7 @@
 	 II != E; ++II) {
       // Print the assembly for the instruction.
       O << "\t";
-      printMachineInstruction(*II);
+      printMachineInstruction(II);
     }
   }
 
diff --git a/lib/Target/X86/X86CodeEmitter.cpp b/lib/Target/X86/X86CodeEmitter.cpp
index 516f1d2..be6319cd 100644
--- a/lib/Target/X86/X86CodeEmitter.cpp
+++ b/lib/Target/X86/X86CodeEmitter.cpp
@@ -212,8 +212,6 @@
 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
                                                   MachineCodeEmitter &MCE) {
   PM.add(new Emitter(MCE));
-  // Delete machine code for this function
-  PM.add(createMachineCodeDeleter());
   return false;
 }
 
@@ -242,7 +240,7 @@
     BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
 
   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
-    emitInstruction(**I);
+    emitInstruction(*I);
 }
 
 
diff --git a/lib/Target/X86/X86FloatingPoint.cpp b/lib/Target/X86/X86FloatingPoint.cpp
index 0a0fe9b..53f6ec0 100644
--- a/lib/Target/X86/X86FloatingPoint.cpp
+++ b/lib/Target/X86/X86FloatingPoint.cpp
@@ -118,7 +118,7 @@
 
 	// Emit an fxch to update the runtime processors version of the state
 	MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
-	I = 1+MBB->insert(I, MI);
+	MBB->insert(I, MI);
 	NumFXCH++;
       }
     }
@@ -129,7 +129,7 @@
       pushReg(AsReg);   // New register on top of stack
 
       MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
-      I = 1+MBB->insert(I, MI);
+      MBB->insert(I, MI);
     }
 
     // popStackAfter - Pop the current value off of the top of the FP stack
@@ -193,12 +193,17 @@
   MBB = &BB;
   
   for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
-    MachineInstr *MI = *I;
+    MachineInstr *MI = I;
     unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
     if ((Flags & X86II::FPTypeMask) == X86II::NotFP)
       continue;  // Efficiently ignore non-fp insts!
 
-    MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
+    MachineInstr *PrevMI = 0;
+    if (I != BB.begin()) {
+        MachineBasicBlock::iterator tmp = I;
+        --tmp;
+        PrevMI = tmp;
+    }
 
     ++NumFP;  // Keep track of # of pseudo instrs
     DEBUG(std::cerr << "\nFPInst:\t";
@@ -242,15 +247,17 @@
     }
     
     // Print out all of the instructions expanded to if -debug
-    DEBUG(if (*I == PrevMI) {
+    DEBUG(if (&*I == PrevMI) {
             std::cerr<< "Just deleted pseudo instruction\n";
           } else {
 	    MachineBasicBlock::iterator Start = I;
 	    // Rewind to first instruction newly inserted.
-	    while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
+	    while (Start != BB.begin() &&
+                   --Start != MachineBasicBlock::iterator(PrevMI));
+            ++Start;
 	    std::cerr << "Inserted instructions:\n\t";
-	    (*Start)->print(std::cerr, MF.getTarget());
-	    while (++Start != I+1);
+	    Start->print(std::cerr, MF.getTarget());
+	    while (++Start != I); ++Start;
 	  }
 	  dumpStack();
 	  );
@@ -344,15 +351,15 @@
   RegMap[Stack[--StackTop]] = ~0;     // Update state
 
   // Check to see if there is a popping version of this instruction...
-  int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
+  int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), I->getOpcode());
   if (Opcode != -1) {
-    (*I)->setOpcode(Opcode);
+    I->setOpcode(Opcode);
     if (Opcode == X86::FUCOMPPr)
-      (*I)->RemoveOperand(0);
+      I->RemoveOperand(0);
 
   } else {    // Insert an explicit pop
     MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
-    I = MBB->insert(I+1, MI);
+    I = MBB->insert(++I, MI);
   }
 }
 
@@ -371,7 +378,7 @@
 /// handleZeroArgFP - ST(0) = fld0    ST(0) = flds <mem>
 ///
 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   unsigned DestReg = getFPReg(MI->getOperand(0));
   MI->RemoveOperand(0);   // Remove the explicit ST(0) operand
 
@@ -382,7 +389,7 @@
 /// handleOneArgFP - fst <mem>, ST(0)
 ///
 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   assert((MI->getNumOperands() == 5 || MI->getNumOperands() == 1) &&
          "Can only handle fst* & ftst instructions!");
 
@@ -418,7 +425,7 @@
 /// handleOneArgFPRW - fchs - ST(0) = -ST(0)
 ///
 void FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   assert(MI->getNumOperands() == 2 && "Can only handle fst* instructions!");
 
   // Is this the last use of the source register?
@@ -503,7 +510,7 @@
 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
   ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
   ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
 
   unsigned NumOperands = MI->getNumOperands();
   assert(NumOperands == 3 ||
@@ -588,7 +595,8 @@
   unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
 
   // Replace the old instruction with a new instruction
-  *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
+  MBB->remove(I);
+  I = MBB->insert(I, BuildMI(Opcode, 1).addReg(getSTReg(NotTOS)));
 
   // If both operands are killed, pop one off of the stack in addition to
   // overwriting the other one.
@@ -617,7 +625,7 @@
 	Stack[--StackTop] = ~0;
 	
 	MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
-	I = MBB->insert(I+1, MI);
+	I = MBB->insert(++I, MI);
       }
     }
   }
@@ -639,7 +647,7 @@
 /// instructions.
 ///
 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
+  MachineInstr *MI = I;
   switch (MI->getOpcode()) {
   default: assert(0 && "Unknown SpecialFP instruction!");
   case X86::FpGETRESULT:  // Appears immediately after a call returning FP type!
@@ -675,6 +683,6 @@
   }
   }
 
-  I = MBB->erase(I)-1;  // Remove the pseudo instruction
-  delete MI;
+  I = MBB->erase(I);  // Remove the pseudo instruction
+  --I;
 }
diff --git a/lib/Target/X86/X86ISelSimple.cpp b/lib/Target/X86/X86ISelSimple.cpp
index af2544f..9df7697 100644
--- a/lib/Target/X86/X86ISelSimple.cpp
+++ b/lib/Target/X86/X86ISelSimple.cpp
@@ -37,23 +37,21 @@
 /// instruction at as well as a basic block.  This is the version for when you
 /// have a destination register in mind.
 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
-                                      MachineBasicBlock::iterator &I,
+                                      MachineBasicBlock::iterator I,
                                       int Opcode, unsigned NumOperands,
                                       unsigned DestReg) {
-  assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
-  I = MBB->insert(I, MI)+1;
+  MBB->insert(I, MI);
   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
 }
 
 /// BMI - A special BuildMI variant that takes an iterator to insert the
 /// instruction at as well as a basic block.
 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
-                                      MachineBasicBlock::iterator &I,
+                                      MachineBasicBlock::iterator I,
                                       int Opcode, unsigned NumOperands) {
-  assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
-  I = MBB->insert(I, MI)+1;
+  MBB->insert(I, MI);
   return MachineInstrBuilder(MI);
 }
 
@@ -541,19 +539,19 @@
     MachineBasicBlock *MBB = MBBMap[I];
 
     // Loop over all of the PHI nodes in the LLVM basic block...
-    unsigned NumPHIs = 0;
+    MachineInstr* instr = MBB->begin();
     for (BasicBlock::const_iterator I = BB->begin();
          PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
 
       // Create a new machine instr PHI node, and insert it.
       unsigned PHIReg = getReg(*PN);
       MachineInstr *PhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg);
-      MBB->insert(MBB->begin()+NumPHIs++, PhiMI);
+      MBB->insert(instr, PhiMI);
 
       MachineInstr *LongPhiMI = 0;
       if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy) {
         LongPhiMI = BuildMI(X86::PHI, PN->getNumOperands(), PHIReg+1);
-        MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
+        MBB->insert(instr, LongPhiMI);
       }
 
       // PHIValues - Map of blocks to incoming virtual registers.  We use this
@@ -588,7 +586,7 @@
             MachineBasicBlock::iterator PI = PredMBB->begin();
 
             // Skip over any PHI nodes though!
-            while (PI != PredMBB->end() && (*PI)->getOpcode() == X86::PHI)
+            while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
               ++PI;
 
             ValReg = getReg(Val, PredMBB, PI);
diff --git a/lib/Target/X86/X86PeepholeOpt.cpp b/lib/Target/X86/X86PeepholeOpt.cpp
index 59ebb15..f09e8d7 100644
--- a/lib/Target/X86/X86PeepholeOpt.cpp
+++ b/lib/Target/X86/X86PeepholeOpt.cpp
@@ -50,8 +50,11 @@
 
 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
 			  MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
-  MachineInstr *Next = (I+1 != MBB.end()) ? *(I+1) : 0;
+  assert(I != MBB.end());
+  MachineBasicBlock::iterator NextI = I; ++NextI;
+
+  MachineInstr *MI = I;
+  MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
   unsigned Size = 0;
   switch (MI->getOpcode()) {
   case X86::MOVrr8:
@@ -59,7 +62,6 @@
   case X86::MOVrr32:   // Destroy X = X copies...
     if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
       I = MBB.erase(I);
-      delete MI;
       return true;
     }
     return false;
@@ -82,8 +84,8 @@
         }
         unsigned R0 = MI->getOperand(0).getReg();
         unsigned R1 = MI->getOperand(1).getReg();
-        *I = BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val);
-        delete MI;
+        I = MBB.insert(MBB.erase(I),
+                       BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
         return true;
       }
     }
@@ -114,8 +116,8 @@
         case X86::XORri32:  Opcode = X86::XORri32b; break;
         }
         unsigned R0 = MI->getOperand(0).getReg();
-        *I = BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val);
-        delete MI;
+        I = MBB.insert(MBB.erase(I),
+                    BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
         return true;
       }
     }
@@ -132,8 +134,8 @@
       if (Val == 0) {                              // mov EAX, 0 -> xor EAX, EAX
 	static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
 	unsigned Reg = MI->getOperand(0).getReg();
-	*I = BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg);
-	delete MI;
+	I = MBB.insert(MBB.erase(I),
+                       BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
 	return true;
       } else if (Val == -1) {                     // mov EAX, -1 -> or EAX, -1
 	// TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
@@ -145,8 +147,6 @@
     if (Next->getOpcode() == X86::BSWAPr32 &&
 	MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
       I = MBB.erase(MBB.erase(I));
-      delete MI;
-      delete Next;
       return true;
     }
     return false;
@@ -189,12 +189,11 @@
     virtual bool runOnMachineFunction(MachineFunction &MF) {
       for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
         for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
-          MachineInstr *MI = *I;
-          for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
-            MachineOperand &MO = MI->getOperand(i);
+          for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
+            MachineOperand &MO = I->getOperand(i);
             if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
                 MRegisterInfo::isVirtualRegister(MO.getReg()))
-              setDefinition(MO.getReg(), MI);
+              setDefinition(MO.getReg(), I);
           }
         }
       return false;
@@ -377,8 +376,10 @@
 
 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator &I) {
-  MachineInstr *MI = *I;
-  MachineInstr *Next = (I+1 != MBB.end()) ? *(I+1) : 0;
+  MachineBasicBlock::iterator NextI = I; ++NextI;
+
+  MachineInstr *MI = I;
+  MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
 
   bool Changed = false;
 
diff --git a/lib/Target/X86/X86RegisterInfo.cpp b/lib/Target/X86/X86RegisterInfo.cpp
index 9b362be..99f834d 100644
--- a/lib/Target/X86/X86RegisterInfo.cpp
+++ b/lib/Target/X86/X86RegisterInfo.cpp
@@ -47,37 +47,35 @@
 }
 
 int X86RegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
-                                         MachineBasicBlock::iterator &MBBI,
+                                         MachineInstr* MI,
                                          unsigned SrcReg, int FrameIdx,
                                          const TargetRegisterClass *RC) const {
   static const unsigned Opcode[] =
     { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32, X86::FSTPr80 };
-  MachineInstr *MI = addFrameReference(BuildMI(Opcode[getIdx(RC)], 5),
+  MachineInstr *I = addFrameReference(BuildMI(Opcode[getIdx(RC)], 5),
 				       FrameIdx).addReg(SrcReg);
-  MBBI = MBB.insert(MBBI, MI)+1;
+  MBB.insert(MI, I);
   return 1;
 }
 
 int X86RegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
-                                          MachineBasicBlock::iterator &MBBI,
+                                          MachineInstr* MI,
                                           unsigned DestReg, int FrameIdx,
                                           const TargetRegisterClass *RC) const{
   static const unsigned Opcode[] =
     { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32, X86::FLDr80 };
-  MachineInstr *MI = addFrameReference(BuildMI(Opcode[getIdx(RC)], 4, DestReg),
-				       FrameIdx);
-  MBBI = MBB.insert(MBBI, MI)+1;
+  unsigned OC = Opcode[getIdx(RC)];
+  MBB.insert(MI, addFrameReference(BuildMI(OC, 4, DestReg), FrameIdx));
   return 1;
 }
 
 int X86RegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
-                                  MachineBasicBlock::iterator &MBBI,
+                                  MachineInstr* MI,
                                   unsigned DestReg, unsigned SrcReg,
                                   const TargetRegisterClass *RC) const {
   static const unsigned Opcode[] =
     { X86::MOVrr8, X86::MOVrr16, X86::MOVrr32, X86::FpMOV };
-  MachineInstr *MI = BuildMI(Opcode[getIdx(RC)],1,DestReg).addReg(SrcReg);
-  MBBI = MBB.insert(MBBI, MI)+1;
+  MBB.insert(MI, BuildMI(Opcode[getIdx(RC)],1,DestReg).addReg(SrcReg));
   return 1;
 }
 
@@ -95,8 +93,8 @@
 
 int X86RegisterInfo::eliminateCallFramePseudoInstr(MachineFunction &MF,
                                                    MachineBasicBlock &MBB,
-	                                 MachineBasicBlock::iterator &I) const {
-  MachineInstr *New = 0, *Old = *I;;
+                                                   MachineInstr* I) const {
+  MachineInstr *New = 0, *Old = I;
   if (hasFP(MF)) {
     // If we have a frame pointer, turn the adjcallstackup instruction into a
     // 'sub ESP, <amt>' and the adjcallstackdown instruction into 'add ESP,
@@ -119,20 +117,19 @@
   }
 
   if (New) {
-    *I = New;        // Replace the pseudo instruction with a new instruction...
-    delete Old;
+    // Replace the pseudo instruction with a new instruction...
+    MBB.insert(MBB.erase(I), New);
     return 0;
   } else {
-    I = MBB.erase(I);// Just delete the pseudo instruction...
-    delete Old;
+    MBB.erase(I);
     return -1;
   }
 }
 
 int X86RegisterInfo::eliminateFrameIndex(MachineFunction &MF,
-                                        MachineBasicBlock::iterator &II) const {
+                                         MachineInstr* II) const {
   unsigned i = 0;
-  MachineInstr &MI = **II;
+  MachineInstr &MI = *II;
   while (!MI.getOperand(i).isFrameIndex()) {
     ++i;
     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
@@ -182,13 +179,13 @@
 
     if (NumBytes) {   // adjust stack pointer: ESP -= numbytes
       MI= BuildMI(X86::SUBri32, 1, X86::ESP, MOTy::UseAndDef).addZImm(NumBytes);
-      MBBI = MBB.insert(MBBI, MI)+1;
+      MBB.insert(MBBI, MI);
     }
 
     // Save EBP into the appropriate stack slot...
     MI = addRegOffset(BuildMI(X86::MOVrm32, 5),    // mov [ESP-<offset>], EBP
 		      X86::ESP, EBPOffset+NumBytes).addReg(X86::EBP);
-    MBBI = MBB.insert(MBBI, MI)+1;
+    MBB.insert(MBBI, MI);
 
     // Update EBP with the new base value...
     if (NumBytes == 0)    // mov EBP, ESP
@@ -196,7 +193,7 @@
     else                  // lea EBP, [ESP+StackSize]
       MI = addRegOffset(BuildMI(X86::LEAr32, 5, X86::EBP), X86::ESP, NumBytes);
 
-    MBBI = MBB.insert(MBBI, MI)+1;
+    MBB.insert(MBBI, MI);
 
   } else {
     // When we have no frame pointer, we reserve argument space for call sites
@@ -226,9 +223,9 @@
                                   MachineBasicBlock &MBB) const {
   unsigned oldSize = MBB.size();
   const MachineFrameInfo *MFI = MF.getFrameInfo();
-  MachineBasicBlock::iterator MBBI = MBB.end()-1;
+  MachineBasicBlock::iterator MBBI = MBB.end(); --MBBI;
   MachineInstr *MI;
-  assert((*MBBI)->getOpcode() == X86::RET &&
+  assert(MBBI->getOpcode() == X86::RET &&
          "Can only insert epilog into returning blocks");
 
   if (hasFP(MF)) {
@@ -238,18 +235,18 @@
     
     // mov ESP, EBP
     MI = BuildMI(X86::MOVrr32, 1,X86::ESP).addReg(X86::EBP);
-    MBBI = 1+MBB.insert(MBBI, MI);
+    MBB.insert(MBBI, MI);
 
     // mov EBP, [ESP-<offset>]
     MI = addRegOffset(BuildMI(X86::MOVmr32, 5, X86::EBP), X86::ESP, EBPOffset);
-    MBBI = 1+MBB.insert(MBBI, MI);
+    MBB.insert(MBBI, MI);
   } else {
     // Get the number of bytes allocated from the FrameInfo...
     unsigned NumBytes = MFI->getStackSize();
 
     if (NumBytes) {    // adjust stack pointer back: ESP += numbytes
       MI =BuildMI(X86::ADDri32, 1, X86::ESP, MOTy::UseAndDef).addZImm(NumBytes);
-      MBBI = 1+MBB.insert(MBBI, MI);
+      MBB.insert(MBBI, MI);
     }
   }
   return MBB.size() - oldSize;
diff --git a/lib/Target/X86/X86RegisterInfo.h b/lib/Target/X86/X86RegisterInfo.h
index 77a8a1a..0087d25 100644
--- a/lib/Target/X86/X86RegisterInfo.h
+++ b/lib/Target/X86/X86RegisterInfo.h
@@ -28,25 +28,26 @@
 
   /// Code Generation virtual methods...
   int storeRegToStackSlot(MachineBasicBlock &MBB,
-                          MachineBasicBlock::iterator &MBBI,
+                          MachineInstr* MI,
                           unsigned SrcReg, int FrameIndex,
                           const TargetRegisterClass *RC) const;
 
   int loadRegFromStackSlot(MachineBasicBlock &MBB,
-                           MachineBasicBlock::iterator &MBBI,
+                           MachineInstr* MI,
                            unsigned DestReg, int FrameIndex,
                            const TargetRegisterClass *RC) const;
   
-  int copyRegToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
+  int copyRegToReg(MachineBasicBlock &MBB,
+                   MachineInstr* MI,
 		   unsigned DestReg, unsigned SrcReg,
 		   const TargetRegisterClass *RC) const;
 
   int eliminateCallFramePseudoInstr(MachineFunction &MF,
                                     MachineBasicBlock &MBB,
-                                    MachineBasicBlock::iterator &I) const;
+                                    MachineInstr* MI) const;
 
   int eliminateFrameIndex(MachineFunction &MF,
-                          MachineBasicBlock::iterator &II) const;
+                          MachineInstr* MI) const;
 
   int processFunctionBeforeFrameFinalized(MachineFunction &MF) const;
 
diff --git a/lib/Target/X86/X86TargetMachine.cpp b/lib/Target/X86/X86TargetMachine.cpp
index 83a390e..c411f86 100644
--- a/lib/Target/X86/X86TargetMachine.cpp
+++ b/lib/Target/X86/X86TargetMachine.cpp
@@ -104,9 +104,6 @@
   if (!DisableOutput)
     PM.add(createX86CodePrinterPass(Out, *this));
 
-  // Delete machine code for this function
-  PM.add(createMachineCodeDeleter());
-
   return false; // success!
 }