Rename MachineCodeForBasicBlock to MachineBasicBlock
[oota-llvm.git] / lib / CodeGen / InstrSched / InstrScheduling.cpp
index dafa8353bb3e837a2dee50bf4d5c19e14b9cfcd7..1857f893672a4da39d9c0eb0c245588613063987 100644 (file)
@@ -1,39 +1,34 @@
-// $Id$
-//***************************************************************************
-// File:
-//     InstrScheduling.cpp
-// 
-// Purpose:
-//     
-// History:
-//     7/23/01  -  Vikram Adve  -  Created
-//**************************************************************************/
-
+//===- InstrScheduling.cpp - Generic Instruction Scheduling support -------===//
+//
+// This file implements the llvm/CodeGen/InstrScheduling.h interface, along with
+// generic support routines for instruction scheduling.
+//
+//===----------------------------------------------------------------------===//
 
-#include "llvm/CodeGen/InstrScheduling.h"
+#include "SchedPriorities.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/MachineCodeForInstruction.h"
-#include "llvm/CodeGen/MachineCodeForMethod.h"
-#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h" // FIXME: Remove when AnalysisUsage sets can be symbolic!
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h" // FIXME: Remove when modularized better
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/BasicBlock.h"
-#include "llvm/Instruction.h"
-#include "SchedPriorities.h"
-#include <ext/hash_set>
+#include "Support/CommandLine.h"
 #include <algorithm>
-#include <iterator>
-#include <iostream>
 using std::cerr;
 using std::vector;
 
-//************************* External Data Types *****************************/
+SchedDebugLevel_t SchedDebugLevel;
 
-cl::Enum<enum SchedDebugLevel_t> SchedDebugLevel("dsched", cl::NoFlags,
-  "enable instruction scheduling debugging information",
-  clEnumValN(Sched_NoDebugInfo,      "n", "disable debug output"),
-  clEnumValN(Sched_PrintMachineCode, "y", "print machine code after scheduling"),
-  clEnumValN(Sched_PrintSchedTrace,  "t", "print trace of scheduling actions"),
-  clEnumValN(Sched_PrintSchedGraphs, "g", "print scheduling graphs"), 0);
+static cl::opt<SchedDebugLevel_t, true>
+SDL_opt("dsched", cl::Hidden, cl::location(SchedDebugLevel),
+        cl::desc("enable instruction scheduling debugging information"),
+        cl::values(
+ clEnumValN(Sched_NoDebugInfo,      "n", "disable debug output"),
+ clEnumValN(Sched_PrintMachineCode, "y", "print machine code after scheduling"),
+ clEnumValN(Sched_PrintSchedTrace,  "t", "print trace of scheduling actions"),
+ clEnumValN(Sched_PrintSchedGraphs, "g", "print scheduling graphs"),
+                   0));
 
 
 //************************* Internal Data Types *****************************/
@@ -82,7 +77,7 @@ private:
 //----------------------------------------------------------------------
 
 template<class _NodeType>
-class ScheduleIterator: public std::forward_iterator<_NodeType, ptrdiff_t> {
+class ScheduleIterator : public forward_iterator<_NodeType, ptrdiff_t> {
 private:
   unsigned cycleNum;
   unsigned slotNum;
@@ -355,18 +350,22 @@ private:
   unsigned int totalInstrCount;
   cycles_t curTime;
   cycles_t nextEarliestIssueTime;              // next cycle we can issue
-  vector<std::hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
+  vector<hash_set<const SchedGraphNode*> > choicesForSlot; // indexed by slot#
   vector<const SchedGraphNode*> choiceVec;     // indexed by node ptr
   vector<int> numInClass;                      // indexed by sched class
   vector<cycles_t> nextEarliestStartTime;      // indexed by opCode
-  std::hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
+  hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
                                                // indexed by branch node ptr 
   
 public:
-  /*ctor*/     SchedulingManager       (const TargetMachine& _target,
-                                        const SchedGraph* graph,
-                                        SchedPriorities& schedPrio);
-  /*dtor*/     ~SchedulingManager      () {}
+  SchedulingManager(const TargetMachine& _target, const SchedGraph* graph,
+                    SchedPriorities& schedPrio);
+  ~SchedulingManager() {
+    for (hash_map<const SchedGraphNode*,
+           DelaySlotInfo*>::iterator I = delaySlotInfoForBranches.begin(),
+           E = delaySlotInfoForBranches.end(); I != E; ++I)
+      delete I->second;
+  }
   
   //----------------------------------------------------------------------
   // Simplify access to the machine instruction info
@@ -421,7 +420,7 @@ public:
     return choiceVec[i];
   }
   
-  inline std::hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
+  inline hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
     assert(slotNum < nslots);
     return choicesForSlot[slotNum];
   }
@@ -496,30 +495,21 @@ public:
   inline DelaySlotInfo* getDelaySlotInfoForInstr(const SchedGraphNode* bn,
                                                 bool createIfMissing=false)
   {
-    DelaySlotInfo* dinfo;
-    std::hash_map<const SchedGraphNode*, DelaySlotInfo* >::const_iterator
+    hash_map<const SchedGraphNode*, DelaySlotInfo*>::const_iterator
       I = delaySlotInfoForBranches.find(bn);
-    if (I == delaySlotInfoForBranches.end())
-      {
-       if (createIfMissing)
-         {
-           dinfo = new DelaySlotInfo(bn,
-                          getInstrInfo().getNumDelaySlots(bn->getOpCode()));
-           delaySlotInfoForBranches[bn] = dinfo;
-         }
-       else
-         dinfo = NULL;
-      }
-    else
-      dinfo = (*I).second;
-    
-    return dinfo;
+    if (I != delaySlotInfoForBranches.end())
+      return I->second;
+
+    if (!createIfMissing) return 0;
+
+    DelaySlotInfo *dinfo =
+      new DelaySlotInfo(bn, getInstrInfo().getNumDelaySlots(bn->getOpCode()));
+    return delaySlotInfoForBranches[bn] = dinfo;
   }
   
 private:
-  /*ctor*/     SchedulingManager       ();     // Disable: DO NOT IMPLEMENT.
-  void         updateEarliestStartTimes(const SchedGraphNode* node,
-                                        cycles_t schedTime);
+  SchedulingManager();     // DISABLED: DO NOT IMPLEMENT
+  void updateEarliestStartTimes(const SchedGraphNode* node, cycles_t schedTime);
 };
 
 
@@ -558,19 +548,17 @@ SchedulingManager::updateEarliestStartTimes(const SchedGraphNode* node,
                  curTime + 1 + schedInfo.numBubblesAfter(node->getOpCode()));
     }
   
-  const vector<MachineOpCode>*
+  const std::vector<MachineOpCode>&
     conflictVec = schedInfo.getConflictList(node->getOpCode());
   
-  if (conflictVec != NULL)
-    for (unsigned i=0; i < conflictVec->size(); i++)
-      {
-       MachineOpCode toOp = (*conflictVec)[i];
-       cycles_t est = schedTime + schedInfo.getMinIssueGap(node->getOpCode(),
-                                                           toOp);
-       assert(toOp < (int) nextEarliestStartTime.size());
-       if (nextEarliestStartTime[toOp] < est)
-         nextEarliestStartTime[toOp] = est;
-      }
+  for (unsigned i=0; i < conflictVec.size(); i++)
+    {
+      MachineOpCode toOp = conflictVec[i];
+      cycles_t est=schedTime + schedInfo.getMinIssueGap(node->getOpCode(),toOp);
+      assert(toOp < (int) nextEarliestStartTime.size());
+      if (nextEarliestStartTime[toOp] < est)
+        nextEarliestStartTime[toOp] = est;
+    }
 }
 
 //************************* Internal Functions *****************************/
@@ -643,14 +631,14 @@ AssignInstructionsToSlots(class SchedulingManager& S, unsigned maxIssue)
 static void
 RecordSchedule(const BasicBlock* bb, const SchedulingManager& S)
 {
-  MachineCodeForBasicBlock& mvec = bb->getMachineInstrVec();
+  MachineBasicBlock& mvec = MachineBasicBlock::get(bb);
   const MachineInstrInfo& mii = S.schedInfo.getInstrInfo();
   
 #ifndef NDEBUG
   // Lets make sure we didn't lose any instructions, except possibly
   // some NOPs from delay slots.  Also, PHIs are not included in the schedule.
   unsigned numInstr = 0;
-  for (MachineCodeForBasicBlock::iterator I=mvec.begin(); I != mvec.end(); ++I)
+  for (MachineBasicBlock::iterator I=mvec.begin(); I != mvec.end(); ++I)
     if (! mii.isNop((*I)->getOpCode()) &&
        ! mii.isDummyPhiInstr((*I)->getOpCode()))
       ++numInstr;
@@ -662,7 +650,7 @@ RecordSchedule(const BasicBlock* bb, const SchedulingManager& S)
     return;                            // empty basic block!
   
   // First find the dummy instructions at the start of the basic block
-  MachineCodeForBasicBlock::iterator I = mvec.begin();
+  MachineBasicBlock::iterator I = mvec.begin();
   for ( ; I != mvec.end(); ++I)
     if (! mii.isDummyPhiInstr((*I)->getOpCode()))
       break;
@@ -670,7 +658,6 @@ RecordSchedule(const BasicBlock* bb, const SchedulingManager& S)
   // Erase all except the dummy PHI instructions from mvec, and
   // pre-allocate create space for the ones we will put back in.
   mvec.erase(I, mvec.end());
-  mvec.reserve(mvec.size() + S.isched.getNumInstructions());
   
   InstrSchedule::const_iterator NIend = S.isched.end();
   for (InstrSchedule::const_iterator NI = S.isched.begin(); NI != NIend; ++NI)
@@ -1233,7 +1220,7 @@ ReplaceNopsWithUsefulInstr(SchedulingManager& S,
   // fill delay slots, otherwise, just discard them.
   //  
   unsigned int firstDelaySlotIdx = node->getOrigIndexInBB() + 1;
-  MachineCodeForBasicBlock& bbMvec  = node->getBB()->getMachineInstrVec();
+  MachineBasicBlock& bbMvec = MachineBasicBlock::get(node->getBB());
   assert(bbMvec[firstDelaySlotIdx - 1] == brInstr &&
          "Incorrect instr. index in basic block for brInstr");
   
@@ -1252,8 +1239,20 @@ ReplaceNopsWithUsefulInstr(SchedulingManager& S,
       if (sdelayNodeVec.size() < ndelays)
         sdelayNodeVec.push_back(graph->getGraphNodeForInstr(bbMvec[i]));
       else
-        nopNodeVec.push_back(graph->getGraphNodeForInstr(bbMvec[i]));
-  
+       {
+         nopNodeVec.push_back(graph->getGraphNodeForInstr(bbMvec[i]));
+         
+         //remove the MI from the Machine Code For Instruction
+         MachineCodeForInstruction& llvmMvec = 
+           MachineCodeForInstruction::get((Instruction *)
+                                          (node->getBB()->getTerminator()));
+         for(MachineCodeForInstruction::iterator mciI=llvmMvec.begin(), 
+               mciE=llvmMvec.end(); mciI!=mciE; ++mciI){
+           if(*mciI==bbMvec[i])
+             llvmMvec.erase(mciI);
+         }
+       }
+
   assert(sdelayNodeVec.size() >= ndelays);
   
   // If some delay slots were already filled, throw away that many new choices
@@ -1326,8 +1325,8 @@ ChooseInstructionsForDelaySlots(SchedulingManager& S,
   // Simply passing in an empty delayNodeVec will have this effect.
   // 
   delayNodeVec.clear();
-  const MachineCodeForBasicBlock& bbMvec = bb->getMachineInstrVec();
-  for (unsigned i=0; i < bbMvec.size(); i++)
+  const MachineBasicBlock& bbMvec = MachineBasicBlock::get(bb);
+  for (unsigned i=0; i < bbMvec.size(); ++i)
     if (bbMvec[i] != brInstr &&
         mii.getNumDelaySlots(bbMvec[i]->getOpCode()) > 0)
       {
@@ -1490,59 +1489,66 @@ instrIsFeasible(const SchedulingManager& S,
 //---------------------------------------------------------------------------
 
 namespace {
-  class InstructionSchedulingWithSSA : public MethodPass {
-    const TargetMachine &Target;
+  class InstructionSchedulingWithSSA : public FunctionPass {
+    const TargetMachine &target;
   public:
-    inline InstructionSchedulingWithSSA(const TargetMachine &T) : Target(T) {}
+    inline InstructionSchedulingWithSSA(const TargetMachine &T) : target(T) {}
 
-    // getAnalysisUsageInfo - We use LiveVarInfo...
-    virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
-                                      Pass::AnalysisSet &Destroyed,
-                                      Pass::AnalysisSet &Provided) {
-      Requires.push_back(MethodLiveVarInfo::ID);
+    const char *getPassName() const { return "Instruction Scheduling"; }
+  
+    // getAnalysisUsage - We use LiveVarInfo...
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired<FunctionLiveVarInfo>();
+      AU.setPreservesCFG();
     }
+    
+    bool runOnFunction(Function &F);
+  };
+} // end anonymous namespace
+
 
-    bool runOnMethod(Method *M) {
-      cerr << "Instr scheduling failed for method " << ((Value*)M)->getName()
-           << "\n\n";
-      SchedGraphSet graphSet(M, Target);       
+bool InstructionSchedulingWithSSA::runOnFunction(Function &F)
+{
+  SchedGraphSet graphSet(&F, target);  
   
-      if (SchedDebugLevel >= Sched_PrintSchedGraphs) {
-        cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
-        graphSet.dump();
-      }
+  if (SchedDebugLevel >= Sched_PrintSchedGraphs)
+    {
+      cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
+      graphSet.dump();
+    }
   
-      for (SchedGraphSet::const_iterator GI=graphSet.begin();
-           GI != graphSet.end(); ++GI) {
-        SchedGraph* graph = GI->second;
-        const vector<const BasicBlock*> &bbvec = graph->getBasicBlocks();
-        assert(bbvec.size() == 1 && "Cannot schedule multiple basic blocks");
-        const BasicBlock* bb = bbvec[0];
+  for (SchedGraphSet::const_iterator GI=graphSet.begin(), GE=graphSet.end();
+       GI != GE; ++GI)
+    {
+      SchedGraph* graph = (*GI);
+      const vector<const BasicBlock*> &bbvec = graph->getBasicBlocks();
+      assert(bbvec.size() == 1 && "Cannot schedule multiple basic blocks");
+      const BasicBlock* bb = bbvec[0];
       
-        if (SchedDebugLevel >= Sched_PrintSchedTrace)
-          cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
+      if (SchedDebugLevel >= Sched_PrintSchedTrace)
+        cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
       
-        // expensive!
-        SchedPriorities schedPrio(M, graph, getAnalysis<MethodLiveVarInfo>());
-        SchedulingManager S(Target, graph, schedPrio);
-        
-        ChooseInstructionsForDelaySlots(S, bb, graph); // modifies graph
-        
-        ForwardListSchedule(S);                             // computes schedule in S
-        
-        RecordSchedule(GI->first, S);                // records schedule in BB
-      }
-  
-      if (SchedDebugLevel >= Sched_PrintMachineCode) {
-        cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
-        MachineCodeForMethod::get(M).dump();
-      }
+      // expensive!
+      SchedPriorities schedPrio(&F, graph,getAnalysis<FunctionLiveVarInfo>());
+      SchedulingManager S(target, graph, schedPrio);
+          
+      ChooseInstructionsForDelaySlots(S, bb, graph); // modifies graph
+      
+      ForwardListSchedule(S);               // computes schedule in S
+      
+      RecordSchedule(bb, S);                // records schedule in BB
+    }
   
-      return false;
+  if (SchedDebugLevel >= Sched_PrintMachineCode)
+    {
+      cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
+      MachineFunction::get(&F).dump();
     }
-  };
-} // end anonymous namespace
+  
+  return false;
+}
+
 
-MethodPass *createInstructionSchedulingWithSSAPass(const TargetMachine &T) {
-  return new InstructionSchedulingWithSSA(T);
+Pass *createInstructionSchedulingWithSSAPass(const TargetMachine &tgt) {
+  return new InstructionSchedulingWithSSA(tgt);
 }