dd2f45dabda1ed784696bd0faf8e098650c79b86
[oota-llvm.git] / lib / CodeGen / InstrSched / InstrScheduling.cpp
1 //===- InstrScheduling.cpp - Generic Instruction Scheduling support -------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the llvm/CodeGen/InstrScheduling.h interface, along with
11 // generic support routines for instruction scheduling.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SchedPriorities.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "../../Target/SparcV9/LiveVar/FunctionLiveVarInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/BasicBlock.h"
22 #include "Support/CommandLine.h"
23 #include <algorithm>
24 #include <iostream>
25
26 namespace llvm {
27
28 SchedDebugLevel_t SchedDebugLevel;
29
30 static cl::opt<bool> EnableFillingDelaySlots("sched-fill-delay-slots",
31               cl::desc("Fill branch delay slots during local scheduling"));
32
33 static cl::opt<SchedDebugLevel_t, true>
34 SDL_opt("dsched", cl::Hidden, cl::location(SchedDebugLevel),
35         cl::desc("enable instruction scheduling debugging information"),
36         cl::values(
37  clEnumValN(Sched_NoDebugInfo,      "n", "disable debug output"),
38  clEnumValN(Sched_PrintMachineCode, "y", "print machine code after scheduling"),
39  clEnumValN(Sched_PrintSchedTrace,  "t", "print trace of scheduling actions"),
40  clEnumValN(Sched_PrintSchedGraphs, "g", "print scheduling graphs"),
41                    clEnumValEnd));
42
43
44 //************************* Internal Data Types *****************************/
45
46 class InstrSchedule;
47 class SchedulingManager;
48
49
50 //----------------------------------------------------------------------
51 // class InstrGroup:
52 // 
53 // Represents a group of instructions scheduled to be issued
54 // in a single cycle.
55 //----------------------------------------------------------------------
56
57 class InstrGroup {
58   InstrGroup(const InstrGroup&);       // DO NOT IMPLEMENT
59   void operator=(const InstrGroup&);   // DO NOT IMPLEMENT
60   
61 public:
62   inline const SchedGraphNode* operator[](unsigned int slotNum) const {
63     assert(slotNum  < group.size());
64     return group[slotNum];
65   }
66   
67 private:
68   friend class InstrSchedule;
69   
70   inline void   addInstr(const SchedGraphNode* node, unsigned int slotNum) {
71     assert(slotNum < group.size());
72     group[slotNum] = node;
73   }
74   
75   /*ctor*/      InstrGroup(unsigned int nslots)
76     : group(nslots, NULL) {}
77   
78   /*ctor*/      InstrGroup();           // disable: DO NOT IMPLEMENT
79   
80 private:
81   std::vector<const SchedGraphNode*> group;
82 };
83
84
85 //----------------------------------------------------------------------
86 // class ScheduleIterator:
87 // 
88 // Iterates over the machine instructions in the for a single basic block.
89 // The schedule is represented by an InstrSchedule object.
90 //----------------------------------------------------------------------
91
92 template<class _NodeType>
93 class ScheduleIterator : public forward_iterator<_NodeType, ptrdiff_t> {
94 private:
95   unsigned cycleNum;
96   unsigned slotNum;
97   const InstrSchedule& S;
98 public:
99   typedef ScheduleIterator<_NodeType> _Self;
100   
101   /*ctor*/ inline ScheduleIterator(const InstrSchedule& _schedule,
102                                    unsigned _cycleNum,
103                                    unsigned _slotNum)
104     : cycleNum(_cycleNum), slotNum(_slotNum), S(_schedule) {
105     skipToNextInstr(); 
106   }
107   
108   /*ctor*/ inline ScheduleIterator(const _Self& x)
109     : cycleNum(x.cycleNum), slotNum(x.slotNum), S(x.S) {}
110   
111   inline bool operator==(const _Self& x) const {
112     return (slotNum == x.slotNum && cycleNum== x.cycleNum && &S==&x.S);
113   }
114   
115   inline bool operator!=(const _Self& x) const { return !operator==(x); }
116   
117   inline _NodeType* operator*() const;
118   inline _NodeType* operator->() const { return operator*(); }
119   
120          _Self& operator++();                           // Preincrement
121   inline _Self operator++(int) {                        // Postincrement
122     _Self tmp(*this); ++*this; return tmp; 
123   }
124   
125   static _Self begin(const InstrSchedule& _schedule);
126   static _Self end(  const InstrSchedule& _schedule);
127   
128 private:
129   inline _Self& operator=(const _Self& x); // DISABLE -- DO NOT IMPLEMENT
130   void  skipToNextInstr();
131 };
132
133
134 //----------------------------------------------------------------------
135 // class InstrSchedule:
136 // 
137 // Represents the schedule of machine instructions for a single basic block.
138 //----------------------------------------------------------------------
139
140 class InstrSchedule {
141   const unsigned int nslots;
142   unsigned int numInstr;
143   std::vector<InstrGroup*> groups;              // indexed by cycle number
144   std::vector<cycles_t> startTime;              // indexed by node id
145
146   InstrSchedule(InstrSchedule&);   // DO NOT IMPLEMENT
147   void operator=(InstrSchedule&);  // DO NOT IMPLEMENT
148   
149 public: // iterators
150   typedef ScheduleIterator<SchedGraphNode> iterator;
151   typedef ScheduleIterator<const SchedGraphNode> const_iterator;
152   
153         iterator begin()       { return iterator::begin(*this); }
154   const_iterator begin() const { return const_iterator::begin(*this); }
155         iterator end()         { return iterator::end(*this); }
156   const_iterator end() const   { return const_iterator::end(*this); }
157   
158 public: // constructors and destructor
159   /*ctor*/              InstrSchedule   (unsigned int _nslots,
160                                          unsigned int _numNodes);
161   /*dtor*/              ~InstrSchedule  ();
162   
163 public: // accessor functions to query chosen schedule
164   const SchedGraphNode* getInstr        (unsigned int slotNum,
165                                          cycles_t c) const {
166     const InstrGroup* igroup = this->getIGroup(c);
167     return (igroup == NULL)? NULL : (*igroup)[slotNum];
168   }
169   
170   inline InstrGroup*    getIGroup       (cycles_t c) {
171     if ((unsigned)c >= groups.size())
172       groups.resize(c+1);
173     if (groups[c] == NULL)
174       groups[c] = new InstrGroup(nslots);
175     return groups[c];
176   }
177   
178   inline const InstrGroup* getIGroup    (cycles_t c) const {
179     assert((unsigned)c < groups.size());
180     return groups[c];
181   }
182   
183   inline cycles_t       getStartTime    (unsigned int nodeId) const {
184     assert(nodeId < startTime.size());
185     return startTime[nodeId];
186   }
187   
188   unsigned int          getNumInstructions() const {
189     return numInstr;
190   }
191   
192   inline void           scheduleInstr   (const SchedGraphNode* node,
193                                          unsigned int slotNum,
194                                          cycles_t cycle) {
195     InstrGroup* igroup = this->getIGroup(cycle);
196     assert((*igroup)[slotNum] == NULL &&  "Slot already filled?");
197     igroup->addInstr(node, slotNum);
198     assert(node->getNodeId() < startTime.size());
199     startTime[node->getNodeId()] = cycle;
200     ++numInstr;
201   }
202   
203 private:
204   friend class ScheduleIterator<SchedGraphNode>;
205   friend class ScheduleIterator<const SchedGraphNode>;
206   /*ctor*/      InstrSchedule   ();     // Disable: DO NOT IMPLEMENT.
207 };
208
209 template<class NodeType>
210 inline NodeType *ScheduleIterator<NodeType>::operator*() const {
211   assert(cycleNum < S.groups.size());
212   return (*S.groups[cycleNum])[slotNum];
213 }
214
215
216 /*ctor*/
217 InstrSchedule::InstrSchedule(unsigned int _nslots, unsigned int _numNodes)
218   : nslots(_nslots),
219     numInstr(0),
220     groups(2 * _numNodes / _nslots),            // 2 x lower-bound for #cycles
221     startTime(_numNodes, (cycles_t) -1)         // set all to -1
222 {
223 }
224
225
226 /*dtor*/
227 InstrSchedule::~InstrSchedule()
228 {
229   for (unsigned c=0, NC=groups.size(); c < NC; c++)
230     if (groups[c] != NULL)
231       delete groups[c];                 // delete InstrGroup objects
232 }
233
234
235 template<class _NodeType>
236 inline 
237 void
238 ScheduleIterator<_NodeType>::skipToNextInstr()
239 {
240   while(cycleNum < S.groups.size() && S.groups[cycleNum] == NULL)
241     ++cycleNum;                 // skip cycles with no instructions
242   
243   while (cycleNum < S.groups.size() &&
244          (*S.groups[cycleNum])[slotNum] == NULL)
245   {
246     ++slotNum;
247     if (slotNum == S.nslots) {
248       ++cycleNum;
249       slotNum = 0;
250       while(cycleNum < S.groups.size() && S.groups[cycleNum] == NULL)
251         ++cycleNum;                     // skip cycles with no instructions
252     }
253   }
254 }
255
256 template<class _NodeType>
257 inline 
258 ScheduleIterator<_NodeType>&
259 ScheduleIterator<_NodeType>::operator++()       // Preincrement
260 {
261   ++slotNum;
262   if (slotNum == S.nslots) {
263     ++cycleNum;
264     slotNum = 0;
265   }
266   skipToNextInstr(); 
267   return *this;
268 }
269
270 template<class _NodeType>
271 ScheduleIterator<_NodeType>
272 ScheduleIterator<_NodeType>::begin(const InstrSchedule& _schedule)
273 {
274   return _Self(_schedule, 0, 0);
275 }
276
277 template<class _NodeType>
278 ScheduleIterator<_NodeType>
279 ScheduleIterator<_NodeType>::end(const InstrSchedule& _schedule)
280 {
281   return _Self(_schedule, _schedule.groups.size(), 0);
282 }
283
284
285 //----------------------------------------------------------------------
286 // class DelaySlotInfo:
287 // 
288 // Record information about delay slots for a single branch instruction.
289 // Delay slots are simply indexed by slot number 1 ... numDelaySlots
290 //----------------------------------------------------------------------
291
292 class DelaySlotInfo {
293   const SchedGraphNode* brNode;
294   unsigned ndelays;
295   std::vector<const SchedGraphNode*> delayNodeVec;
296   cycles_t delayedNodeCycle;
297   unsigned delayedNodeSlotNum;
298   
299   DelaySlotInfo(const DelaySlotInfo &);  // DO NOT IMPLEMENT
300   void operator=(const DelaySlotInfo&);  // DO NOT IMPLEMENT
301 public:
302   /*ctor*/      DelaySlotInfo           (const SchedGraphNode* _brNode,
303                                          unsigned _ndelays)
304     : brNode(_brNode), ndelays(_ndelays),
305       delayedNodeCycle(0), delayedNodeSlotNum(0) {}
306   
307   inline unsigned getNumDelays  () {
308     return ndelays;
309   }
310   
311   inline const std::vector<const SchedGraphNode*>& getDelayNodeVec() {
312     return delayNodeVec;
313   }
314   
315   inline void   addDelayNode            (const SchedGraphNode* node) {
316     delayNodeVec.push_back(node);
317     assert(delayNodeVec.size() <= ndelays && "Too many delay slot instrs!");
318   }
319   
320   inline void   recordChosenSlot        (cycles_t cycle, unsigned slotNum) {
321     delayedNodeCycle = cycle;
322     delayedNodeSlotNum = slotNum;
323   }
324   
325   unsigned      scheduleDelayedNode     (SchedulingManager& S);
326 };
327
328
329 //----------------------------------------------------------------------
330 // class SchedulingManager:
331 // 
332 // Represents the schedule of machine instructions for a single basic block.
333 //----------------------------------------------------------------------
334
335 class SchedulingManager {
336   SchedulingManager(SchedulingManager &);    // DO NOT IMPLEMENT
337   void operator=(const SchedulingManager &); // DO NOT IMPLEMENT
338 public: // publicly accessible data members
339   const unsigned nslots;
340   const TargetSchedInfo& schedInfo;
341   SchedPriorities& schedPrio;
342   InstrSchedule isched;
343   
344 private:
345   unsigned totalInstrCount;
346   cycles_t curTime;
347   cycles_t nextEarliestIssueTime;               // next cycle we can issue
348   // indexed by slot#
349   std::vector<hash_set<const SchedGraphNode*> > choicesForSlot;
350   std::vector<const SchedGraphNode*> choiceVec; // indexed by node ptr
351   std::vector<int> numInClass;                  // indexed by sched class
352   std::vector<cycles_t> nextEarliestStartTime;  // indexed by opCode
353   hash_map<const SchedGraphNode*, DelaySlotInfo*> delaySlotInfoForBranches;
354                                                 // indexed by branch node ptr 
355   
356 public:
357   SchedulingManager(const TargetMachine& _target, const SchedGraph* graph,
358                     SchedPriorities& schedPrio);
359   ~SchedulingManager() {
360     for (hash_map<const SchedGraphNode*,
361            DelaySlotInfo*>::iterator I = delaySlotInfoForBranches.begin(),
362            E = delaySlotInfoForBranches.end(); I != E; ++I)
363       delete I->second;
364   }
365   
366   //----------------------------------------------------------------------
367   // Simplify access to the machine instruction info
368   //----------------------------------------------------------------------
369   
370   inline const TargetInstrInfo& getInstrInfo    () const {
371     return schedInfo.getInstrInfo();
372   }
373   
374   //----------------------------------------------------------------------
375   // Interface for checking and updating the current time
376   //----------------------------------------------------------------------
377   
378   inline cycles_t       getTime                 () const {
379     return curTime;
380   }
381   
382   inline cycles_t       getEarliestIssueTime() const {
383     return nextEarliestIssueTime;
384   }
385   
386   inline cycles_t       getEarliestStartTimeForOp(MachineOpCode opCode) const {
387     assert(opCode < (int) nextEarliestStartTime.size());
388     return nextEarliestStartTime[opCode];
389   }
390   
391   // Update current time to specified cycle
392   inline void   updateTime              (cycles_t c) {
393     curTime = c;
394     schedPrio.updateTime(c);
395   }
396   
397   //----------------------------------------------------------------------
398   // Functions to manage the choices for the current cycle including:
399   // -- a vector of choices by priority (choiceVec)
400   // -- vectors of the choices for each instruction slot (choicesForSlot[])
401   // -- number of choices in each sched class, used to check issue conflicts
402   //    between choices for a single cycle
403   //----------------------------------------------------------------------
404   
405   inline unsigned int getNumChoices     () const {
406     return choiceVec.size();
407   }
408   
409   inline unsigned getNumChoicesInClass  (const InstrSchedClass& sc) const {
410     assert(sc < numInClass.size() && "Invalid op code or sched class!");
411     return numInClass[sc];
412   }
413   
414   inline const SchedGraphNode* getChoice(unsigned int i) const {
415     // assert(i < choiceVec.size());    don't check here.
416     return choiceVec[i];
417   }
418   
419   inline hash_set<const SchedGraphNode*>& getChoicesForSlot(unsigned slotNum) {
420     assert(slotNum < nslots);
421     return choicesForSlot[slotNum];
422   }
423   
424   inline void   addChoice               (const SchedGraphNode* node) {
425     // Append the instruction to the vector of choices for current cycle.
426     // Increment numInClass[c] for the sched class to which the instr belongs.
427     choiceVec.push_back(node);
428     const InstrSchedClass& sc = schedInfo.getSchedClass(node->getOpcode());
429     assert(sc < numInClass.size());
430     numInClass[sc]++;
431   }
432   
433   inline void   addChoiceToSlot         (unsigned int slotNum,
434                                          const SchedGraphNode* node) {
435     // Add the instruction to the choice set for the specified slot
436     assert(slotNum < nslots);
437     choicesForSlot[slotNum].insert(node);
438   }
439   
440   inline void   resetChoices            () {
441     choiceVec.clear();
442     for (unsigned int s=0; s < nslots; s++)
443       choicesForSlot[s].clear();
444     for (unsigned int c=0; c < numInClass.size(); c++)
445       numInClass[c] = 0;
446   }
447   
448   //----------------------------------------------------------------------
449   // Code to query and manage the partial instruction schedule so far
450   //----------------------------------------------------------------------
451   
452   inline unsigned int   getNumScheduled () const {
453     return isched.getNumInstructions();
454   }
455   
456   inline unsigned int   getNumUnscheduled() const {
457     return totalInstrCount - isched.getNumInstructions();
458   }
459   
460   inline bool           isScheduled     (const SchedGraphNode* node) const {
461     return (isched.getStartTime(node->getNodeId()) >= 0);
462   }
463   
464   inline void   scheduleInstr           (const SchedGraphNode* node,
465                                          unsigned int slotNum,
466                                          cycles_t cycle)
467   {
468     assert(! isScheduled(node) && "Instruction already scheduled?");
469     
470     // add the instruction to the schedule
471     isched.scheduleInstr(node, slotNum, cycle);
472     
473     // update the earliest start times of all nodes that conflict with `node'
474     // and the next-earliest time anything can issue if `node' causes bubbles
475     updateEarliestStartTimes(node, cycle);
476     
477     // remove the instruction from the choice sets for all slots
478     for (unsigned s=0; s < nslots; s++)
479       choicesForSlot[s].erase(node);
480     
481     // and decrement the instr count for the sched class to which it belongs
482     const InstrSchedClass& sc = schedInfo.getSchedClass(node->getOpcode());
483     assert(sc < numInClass.size());
484     numInClass[sc]--;
485   }
486
487   //----------------------------------------------------------------------
488   // Create and retrieve delay slot info for delayed instructions
489   //----------------------------------------------------------------------
490   
491   inline DelaySlotInfo* getDelaySlotInfoForInstr(const SchedGraphNode* bn,
492                                                  bool createIfMissing=false)
493   {
494     hash_map<const SchedGraphNode*, DelaySlotInfo*>::const_iterator
495       I = delaySlotInfoForBranches.find(bn);
496     if (I != delaySlotInfoForBranches.end())
497       return I->second;
498
499     if (!createIfMissing) return 0;
500
501     DelaySlotInfo *dinfo =
502       new DelaySlotInfo(bn, getInstrInfo().getNumDelaySlots(bn->getOpcode()));
503     return delaySlotInfoForBranches[bn] = dinfo;
504   }
505   
506 private:
507   SchedulingManager();     // DISABLED: DO NOT IMPLEMENT
508   void updateEarliestStartTimes(const SchedGraphNode* node, cycles_t schedTime);
509 };
510
511
512 /*ctor*/
513 SchedulingManager::SchedulingManager(const TargetMachine& target,
514                                      const SchedGraph* graph,
515                                      SchedPriorities& _schedPrio)
516   : nslots(target.getSchedInfo()->getMaxNumIssueTotal()),
517     schedInfo(*target.getSchedInfo()),
518     schedPrio(_schedPrio),
519     isched(nslots, graph->getNumNodes()),
520     totalInstrCount(graph->getNumNodes() - 2),
521     nextEarliestIssueTime(0),
522     choicesForSlot(nslots),
523     numInClass(target.getSchedInfo()->getNumSchedClasses(), 0), // set all to 0
524     nextEarliestStartTime(target.getInstrInfo()->getNumOpcodes(),
525                           (cycles_t) 0)                         // set all to 0
526 {
527   updateTime(0);
528   
529   // Note that an upper bound on #choices for each slot is = nslots since
530   // we use this vector to hold a feasible set of instructions, and more
531   // would be infeasible. Reserve that much memory since it is probably small.
532   for (unsigned int i=0; i < nslots; i++)
533     choicesForSlot[i].resize(nslots);
534 }
535
536
537 void
538 SchedulingManager::updateEarliestStartTimes(const SchedGraphNode* node,
539                                             cycles_t schedTime)
540 {
541   if (schedInfo.numBubblesAfter(node->getOpcode()) > 0)
542     { // Update next earliest time before which *nothing* can issue.
543       nextEarliestIssueTime = std::max(nextEarliestIssueTime,
544                   curTime + 1 + schedInfo.numBubblesAfter(node->getOpcode()));
545     }
546   
547   const std::vector<MachineOpCode>&
548     conflictVec = schedInfo.getConflictList(node->getOpcode());
549   
550   for (unsigned i=0; i < conflictVec.size(); i++)
551     {
552       MachineOpCode toOp = conflictVec[i];
553       cycles_t est=schedTime + schedInfo.getMinIssueGap(node->getOpcode(),toOp);
554       assert(toOp < (int) nextEarliestStartTime.size());
555       if (nextEarliestStartTime[toOp] < est)
556         nextEarliestStartTime[toOp] = est;
557     }
558 }
559
560 //************************* Internal Functions *****************************/
561
562
563 static void
564 AssignInstructionsToSlots(class SchedulingManager& S, unsigned maxIssue)
565 {
566   // find the slot to start from, in the current cycle
567   unsigned int startSlot = 0;
568   cycles_t curTime = S.getTime();
569   
570   assert(maxIssue > 0 && maxIssue <= S.nslots - startSlot);
571   
572   // If only one instruction can be issued, do so.
573   if (maxIssue == 1)
574     for (unsigned s=startSlot; s < S.nslots; s++)
575       if (S.getChoicesForSlot(s).size() > 0) {
576         // found the one instruction
577         S.scheduleInstr(*S.getChoicesForSlot(s).begin(), s, curTime);
578         return;
579       }
580   
581   // Otherwise, choose from the choices for each slot
582   // 
583   InstrGroup* igroup = S.isched.getIGroup(S.getTime());
584   assert(igroup != NULL && "Group creation failed?");
585   
586   // Find a slot that has only a single choice, and take it.
587   // If all slots have 0 or multiple choices, pick the first slot with
588   // choices and use its last instruction (just to avoid shifting the vector).
589   unsigned numIssued;
590   for (numIssued = 0; numIssued < maxIssue; numIssued++) {
591     int chosenSlot = -1;
592     for (unsigned s=startSlot; s < S.nslots; s++)
593       if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() == 1) {
594         chosenSlot = (int) s;
595         break;
596       }
597       
598     if (chosenSlot == -1)
599       for (unsigned s=startSlot; s < S.nslots; s++)
600         if ((*igroup)[s] == NULL && S.getChoicesForSlot(s).size() > 0) {
601           chosenSlot = (int) s;
602           break;
603         }
604       
605     if (chosenSlot != -1) {
606       // Insert the chosen instr in the chosen slot and
607       // erase it from all slots.
608       const SchedGraphNode* node= *S.getChoicesForSlot(chosenSlot).begin();
609       S.scheduleInstr(node, chosenSlot, curTime);
610     }
611   }
612   
613   assert(numIssued > 0 && "Should not happen when maxIssue > 0!");
614 }
615
616
617 // 
618 // For now, just assume we are scheduling within a single basic block.
619 // Get the machine instruction vector for the basic block and clear it,
620 // then append instructions in scheduled order.
621 // Also, re-insert the dummy PHI instructions that were at the beginning
622 // of the basic block, since they are not part of the schedule.
623 //   
624 static void
625 RecordSchedule(MachineBasicBlock &MBB, const SchedulingManager& S)
626 {
627   const TargetInstrInfo& mii = S.schedInfo.getInstrInfo();
628   
629 #ifndef NDEBUG
630   // Lets make sure we didn't lose any instructions, except possibly
631   // some NOPs from delay slots.  Also, PHIs are not included in the schedule.
632   unsigned numInstr = 0;
633   for (MachineBasicBlock::iterator I=MBB.begin(); I != MBB.end(); ++I)
634     if (! mii.isNop(I->getOpcode()) &&
635         ! mii.isDummyPhiInstr(I->getOpcode()))
636       ++numInstr;
637   assert(S.isched.getNumInstructions() >= numInstr &&
638          "Lost some non-NOP instructions during scheduling!");
639 #endif
640   
641   if (S.isched.getNumInstructions() == 0)
642     return;                             // empty basic block!
643   
644   // First find the dummy instructions at the start of the basic block
645   MachineBasicBlock::iterator I = MBB.begin();
646   for ( ; I != MBB.end(); ++I)
647     if (! mii.isDummyPhiInstr(I->getOpcode()))
648       break;
649   
650   // Remove all except the dummy PHI instructions from MBB, and
651   // pre-allocate create space for the ones we will put back in.
652   while (I != MBB.end())
653     MBB.remove(I++);
654   
655   InstrSchedule::const_iterator NIend = S.isched.end();
656   for (InstrSchedule::const_iterator NI = S.isched.begin(); NI != NIend; ++NI)
657     MBB.push_back(const_cast<MachineInstr*>((*NI)->getMachineInstr()));
658 }
659
660
661
662 static void
663 MarkSuccessorsReady(SchedulingManager& S, const SchedGraphNode* node)
664 {
665   // Check if any successors are now ready that were not already marked
666   // ready before, and that have not yet been scheduled.
667   // 
668   for (sg_succ_const_iterator SI = succ_begin(node); SI !=succ_end(node); ++SI)
669     if (! (*SI)->isDummyNode()
670         && ! S.isScheduled(*SI)
671         && ! S.schedPrio.nodeIsReady(*SI))
672     {
673       // successor not scheduled and not marked ready; check *its* preds.
674         
675       bool succIsReady = true;
676       for (sg_pred_const_iterator P=pred_begin(*SI); P != pred_end(*SI); ++P)
677         if (! (*P)->isDummyNode() && ! S.isScheduled(*P)) {
678           succIsReady = false;
679           break;
680         }
681         
682       if (succIsReady)  // add the successor to the ready list
683         S.schedPrio.insertReady(*SI);
684     }
685 }
686
687
688 // Choose up to `nslots' FEASIBLE instructions and assign each
689 // instruction to all possible slots that do not violate feasibility.
690 // FEASIBLE means it should be guaranteed that the set
691 // of chosen instructions can be issued in a single group.
692 // 
693 // Return value:
694 //      maxIssue : total number of feasible instructions
695 //      S.choicesForSlot[i=0..nslots] : set of instructions feasible in slot i
696 // 
697 static unsigned
698 FindSlotChoices(SchedulingManager& S,
699                 DelaySlotInfo*& getDelaySlotInfo)
700 {
701   // initialize result vectors to empty
702   S.resetChoices();
703   
704   // find the slot to start from, in the current cycle
705   unsigned int startSlot = 0;
706   InstrGroup* igroup = S.isched.getIGroup(S.getTime());
707   for (int s = S.nslots - 1; s >= 0; s--)
708     if ((*igroup)[s] != NULL) {
709       startSlot = s+1;
710       break;
711     }
712   
713   // Make sure we pick at most one instruction that would break the group.
714   // Also, if we do pick one, remember which it was.
715   unsigned int indexForBreakingNode = S.nslots;
716   unsigned int indexForDelayedInstr = S.nslots;
717   DelaySlotInfo* delaySlotInfo = NULL;
718
719   getDelaySlotInfo = NULL;
720   
721   // Choose instructions in order of priority.
722   // Add choices to the choice vector in the SchedulingManager class as
723   // we choose them so that subsequent choices will be correctly tested
724   // for feasibility, w.r.t. higher priority choices for the same cycle.
725   // 
726   while (S.getNumChoices() < S.nslots - startSlot) {
727     const SchedGraphNode* nextNode=S.schedPrio.getNextHighest(S,S.getTime());
728     if (nextNode == NULL)
729       break;                    // no more instructions for this cycle
730       
731     if (S.getInstrInfo().getNumDelaySlots(nextNode->getOpcode()) > 0) {
732       delaySlotInfo = S.getDelaySlotInfoForInstr(nextNode);
733       if (delaySlotInfo != NULL) {
734         if (indexForBreakingNode < S.nslots)
735           // cannot issue a delayed instr in the same cycle as one
736           // that breaks the issue group or as another delayed instr
737           nextNode = NULL;
738         else
739           indexForDelayedInstr = S.getNumChoices();
740       }
741     } else if (S.schedInfo.breaksIssueGroup(nextNode->getOpcode())) {
742       if (indexForBreakingNode < S.nslots)
743         // have a breaking instruction already so throw this one away
744         nextNode = NULL;
745       else
746         indexForBreakingNode = S.getNumChoices();
747     }
748       
749     if (nextNode != NULL) {
750       S.addChoice(nextNode);
751       
752       if (S.schedInfo.isSingleIssue(nextNode->getOpcode())) {
753         assert(S.getNumChoices() == 1 &&
754                "Prioritizer returned invalid instr for this cycle!");
755         break;
756       }
757     }
758           
759     if (indexForDelayedInstr < S.nslots)
760       break;                    // leave the rest for delay slots
761   }
762   
763   assert(S.getNumChoices() <= S.nslots);
764   assert(! (indexForDelayedInstr < S.nslots &&
765             indexForBreakingNode < S.nslots) && "Cannot have both in a cycle");
766   
767   // Assign each chosen instruction to all possible slots for that instr.
768   // But if only one instruction was chosen, put it only in the first
769   // feasible slot; no more analysis will be needed.
770   // 
771   if (indexForDelayedInstr >= S.nslots && 
772       indexForBreakingNode >= S.nslots)
773   { // No instructions that break the issue group or that have delay slots.
774     // This is the common case, so handle it separately for efficiency.
775       
776     if (S.getNumChoices() == 1) {
777       MachineOpCode opCode = S.getChoice(0)->getOpcode();
778       unsigned int s;
779       for (s=startSlot; s < S.nslots; s++)
780         if (S.schedInfo.instrCanUseSlot(opCode, s))
781           break;
782       assert(s < S.nslots && "No feasible slot for this opCode?");
783       S.addChoiceToSlot(s, S.getChoice(0));
784     } else {
785       for (unsigned i=0; i < S.getNumChoices(); i++) {
786         MachineOpCode opCode = S.getChoice(i)->getOpcode();
787         for (unsigned int s=startSlot; s < S.nslots; s++)
788           if (S.schedInfo.instrCanUseSlot(opCode, s))
789             S.addChoiceToSlot(s, S.getChoice(i));
790       }
791     }
792   } else if (indexForDelayedInstr < S.nslots) {
793     // There is an instruction that needs delay slots.
794     // Try to assign that instruction to a higher slot than any other
795     // instructions in the group, so that its delay slots can go
796     // right after it.
797     //  
798
799     assert(indexForDelayedInstr == S.getNumChoices() - 1 &&
800            "Instruction with delay slots should be last choice!");
801     assert(delaySlotInfo != NULL && "No delay slot info for instr?");
802       
803     const SchedGraphNode* delayedNode = S.getChoice(indexForDelayedInstr);
804     MachineOpCode delayOpCode = delayedNode->getOpcode();
805     unsigned ndelays= S.getInstrInfo().getNumDelaySlots(delayOpCode);
806       
807     unsigned delayedNodeSlot = S.nslots;
808     int highestSlotUsed;
809       
810     // Find the last possible slot for the delayed instruction that leaves
811     // at least `d' slots vacant after it (d = #delay slots)
812     for (int s = S.nslots-ndelays-1; s >= (int) startSlot; s--)
813       if (S.schedInfo.instrCanUseSlot(delayOpCode, s)) {
814         delayedNodeSlot = s;
815         break;
816       }
817       
818     highestSlotUsed = -1;
819     for (unsigned i=0; i < S.getNumChoices() - 1; i++) {
820       // Try to assign every other instruction to a lower numbered
821       // slot than delayedNodeSlot.
822       MachineOpCode opCode =S.getChoice(i)->getOpcode();
823       bool noSlotFound = true;
824       unsigned int s;
825       for (s=startSlot; s < delayedNodeSlot; s++)
826         if (S.schedInfo.instrCanUseSlot(opCode, s)) {
827           S.addChoiceToSlot(s, S.getChoice(i));
828           noSlotFound = false;
829         }
830           
831       // No slot before `delayedNodeSlot' was found for this opCode
832       // Use a later slot, and allow some delay slots to fall in
833       // the next cycle.
834       if (noSlotFound)
835         for ( ; s < S.nslots; s++)
836           if (S.schedInfo.instrCanUseSlot(opCode, s)) {
837             S.addChoiceToSlot(s, S.getChoice(i));
838             break;
839           }
840           
841       assert(s < S.nslots && "No feasible slot for instruction?");
842           
843       highestSlotUsed = std::max(highestSlotUsed, (int) s);
844     }
845       
846     assert(highestSlotUsed <= (int) S.nslots-1 && "Invalid slot used?");
847       
848     // We will put the delayed node in the first slot after the
849     // highest slot used.  But we just mark that for now, and
850     // schedule it separately because we want to schedule the delay
851     // slots for the node at the same time.
852     cycles_t dcycle = S.getTime();
853     unsigned int dslot = highestSlotUsed + 1;
854     if (dslot == S.nslots) {
855       dslot = 0;
856       ++dcycle;
857     }
858     delaySlotInfo->recordChosenSlot(dcycle, dslot);
859     getDelaySlotInfo = delaySlotInfo;
860   } else {
861     // There is an instruction that breaks the issue group.
862     // For such an instruction, assign to the last possible slot in
863     // the current group, and then don't assign any other instructions
864     // to later slots.
865     assert(indexForBreakingNode < S.nslots);
866     const SchedGraphNode* breakingNode=S.getChoice(indexForBreakingNode);
867     unsigned breakingSlot = INT_MAX;
868     unsigned int nslotsToUse = S.nslots;
869           
870     // Find the last possible slot for this instruction.
871     for (int s = S.nslots-1; s >= (int) startSlot; s--)
872       if (S.schedInfo.instrCanUseSlot(breakingNode->getOpcode(), s)) {
873         breakingSlot = s;
874         break;
875       }
876     assert(breakingSlot < S.nslots &&
877            "No feasible slot for `breakingNode'?");
878       
879     // Higher priority instructions than the one that breaks the group:
880     // These can be assigned to all slots, but will be assigned only
881     // to earlier slots if possible.
882     for (unsigned i=0;
883          i < S.getNumChoices() && i < indexForBreakingNode; i++)
884     {
885       MachineOpCode opCode =S.getChoice(i)->getOpcode();
886           
887       // If a higher priority instruction cannot be assigned to
888       // any earlier slots, don't schedule the breaking instruction.
889       // 
890       bool foundLowerSlot = false;
891       nslotsToUse = S.nslots;       // May be modified in the loop
892       for (unsigned int s=startSlot; s < nslotsToUse; s++)
893         if (S.schedInfo.instrCanUseSlot(opCode, s)) {
894           if (breakingSlot < S.nslots && s < breakingSlot) {
895             foundLowerSlot = true;
896             nslotsToUse = breakingSlot; // RESETS LOOP UPPER BOUND!
897           }
898                     
899           S.addChoiceToSlot(s, S.getChoice(i));
900         }
901               
902       if (!foundLowerSlot)
903         breakingSlot = INT_MAX;         // disable breaking instr
904     }
905       
906     // Assign the breaking instruction (if any) to a single slot
907     // Otherwise, just ignore the instruction.  It will simply be
908     // scheduled in a later cycle.
909     if (breakingSlot < S.nslots) {
910       S.addChoiceToSlot(breakingSlot, breakingNode);
911       nslotsToUse = breakingSlot;
912     } else
913       nslotsToUse = S.nslots;
914           
915     // For lower priority instructions than the one that breaks the
916     // group, only assign them to slots lower than the breaking slot.
917     // Otherwise, just ignore the instruction.
918     for (unsigned i=indexForBreakingNode+1; i < S.getNumChoices(); i++) {
919       MachineOpCode opCode = S.getChoice(i)->getOpcode();
920       for (unsigned int s=startSlot; s < nslotsToUse; s++)
921         if (S.schedInfo.instrCanUseSlot(opCode, s))
922           S.addChoiceToSlot(s, S.getChoice(i));
923     }
924   } // endif (no delay slots and no breaking slots)
925   
926   return S.getNumChoices();
927 }
928
929
930 static unsigned
931 ChooseOneGroup(SchedulingManager& S)
932 {
933   assert(S.schedPrio.getNumReady() > 0
934          && "Don't get here without ready instructions.");
935   
936   cycles_t firstCycle = S.getTime();
937   DelaySlotInfo* getDelaySlotInfo = NULL;
938   
939   // Choose up to `nslots' feasible instructions and their possible slots.
940   unsigned numIssued = FindSlotChoices(S, getDelaySlotInfo);
941   
942   while (numIssued == 0) {
943     S.updateTime(S.getTime()+1);
944     numIssued = FindSlotChoices(S, getDelaySlotInfo);
945   }
946   
947   AssignInstructionsToSlots(S, numIssued);
948   
949   if (getDelaySlotInfo != NULL)
950     numIssued += getDelaySlotInfo->scheduleDelayedNode(S); 
951   
952   // Print trace of scheduled instructions before newly ready ones
953   if (SchedDebugLevel >= Sched_PrintSchedTrace) {
954     for (cycles_t c = firstCycle; c <= S.getTime(); c++) {
955       std::cerr << "    Cycle " << (long)c <<" : Scheduled instructions:\n";
956       const InstrGroup* igroup = S.isched.getIGroup(c);
957       for (unsigned int s=0; s < S.nslots; s++) {
958         std::cerr << "        ";
959         if ((*igroup)[s] != NULL)
960           std::cerr << * ((*igroup)[s])->getMachineInstr() << "\n";
961         else
962           std::cerr << "<none>\n";
963       }
964     }
965   }
966   
967   return numIssued;
968 }
969
970
971 static void
972 ForwardListSchedule(SchedulingManager& S)
973 {
974   unsigned N;
975   const SchedGraphNode* node;
976   
977   S.schedPrio.initialize();
978   
979   while ((N = S.schedPrio.getNumReady()) > 0) {
980     cycles_t nextCycle = S.getTime();
981       
982     // Choose one group of instructions for a cycle, plus any delay slot
983     // instructions (which may overflow into successive cycles).
984     // This will advance S.getTime() to the last cycle in which
985     // instructions are actually issued.
986     // 
987     unsigned numIssued = ChooseOneGroup(S);
988     assert(numIssued > 0 && "Deadlock in list scheduling algorithm?");
989       
990     // Notify the priority manager of scheduled instructions and mark
991     // any successors that may now be ready
992     // 
993     for (cycles_t c = nextCycle; c <= S.getTime(); c++) {
994       const InstrGroup* igroup = S.isched.getIGroup(c);
995       for (unsigned int s=0; s < S.nslots; s++)
996         if ((node = (*igroup)[s]) != NULL) {
997           S.schedPrio.issuedReadyNodeAt(S.getTime(), node);
998           MarkSuccessorsReady(S, node);
999         }
1000     }
1001       
1002     // Move to the next the next earliest cycle for which
1003     // an instruction can be issued, or the next earliest in which
1004     // one will be ready, or to the next cycle, whichever is latest.
1005     // 
1006     S.updateTime(std::max(S.getTime() + 1,
1007                           std::max(S.getEarliestIssueTime(),
1008                                    S.schedPrio.getEarliestReadyTime())));
1009   }
1010 }
1011
1012
1013 //---------------------------------------------------------------------
1014 // Code for filling delay slots for delayed terminator instructions
1015 // (e.g., BRANCH and RETURN).  Delay slots for non-terminator
1016 // instructions (e.g., CALL) are not handled here because they almost
1017 // always can be filled with instructions from the call sequence code
1018 // before a call.  That's preferable because we incur many tradeoffs here
1019 // when we cannot find single-cycle instructions that can be reordered.
1020 //----------------------------------------------------------------------
1021
1022 static bool
1023 NodeCanFillDelaySlot(const SchedulingManager& S,
1024                      const SchedGraphNode* node,
1025                      const SchedGraphNode* brNode,
1026                      bool nodeIsPredecessor)
1027 {
1028   assert(! node->isDummyNode());
1029   
1030   // don't put a branch in the delay slot of another branch
1031   if (S.getInstrInfo().isBranch(node->getOpcode()))
1032     return false;
1033   
1034   // don't put a single-issue instruction in the delay slot of a branch
1035   if (S.schedInfo.isSingleIssue(node->getOpcode()))
1036     return false;
1037   
1038   // don't put a load-use dependence in the delay slot of a branch
1039   const TargetInstrInfo& mii = S.getInstrInfo();
1040   
1041   for (SchedGraphNode::const_iterator EI = node->beginInEdges();
1042        EI != node->endInEdges(); ++EI)
1043     if (! ((SchedGraphNode*)(*EI)->getSrc())->isDummyNode()
1044         && mii.isLoad(((SchedGraphNode*)(*EI)->getSrc())->getOpcode())
1045         && (*EI)->getDepType() == SchedGraphEdge::CtrlDep)
1046       return false;
1047   
1048   // Finally, if the instruction precedes the branch, we make sure the
1049   // instruction can be reordered relative to the branch.  We simply check
1050   // if the instr. has only 1 outgoing edge, viz., a CD edge to the branch.
1051   // 
1052   if (nodeIsPredecessor) {
1053     bool onlyCDEdgeToBranch = true;
1054     for (SchedGraphNode::const_iterator OEI = node->beginOutEdges();
1055          OEI != node->endOutEdges(); ++OEI)
1056       if (! ((SchedGraphNode*)(*OEI)->getSink())->isDummyNode()
1057           && ((*OEI)->getSink() != brNode
1058               || (*OEI)->getDepType() != SchedGraphEdge::CtrlDep))
1059       {
1060         onlyCDEdgeToBranch = false;
1061         break;
1062       }
1063       
1064     if (!onlyCDEdgeToBranch)
1065       return false;
1066   }
1067   
1068   return true;
1069 }
1070
1071
1072 static void
1073 MarkNodeForDelaySlot(SchedulingManager& S,
1074                      SchedGraph* graph,
1075                      SchedGraphNode* node,
1076                      const SchedGraphNode* brNode,
1077                      bool nodeIsPredecessor)
1078 {
1079   if (nodeIsPredecessor) {
1080     // If node is in the same basic block (i.e., precedes brNode),
1081     // remove it and all its incident edges from the graph.  Make sure we
1082     // add dummy edges for pred/succ nodes that become entry/exit nodes.
1083     graph->eraseIncidentEdges(node, /*addDummyEdges*/ true);
1084   } else { 
1085     // If the node was from a target block, add the node to the graph
1086     // and add a CD edge from brNode to node.
1087     assert(0 && "NOT IMPLEMENTED YET");
1088   }
1089   
1090   DelaySlotInfo* dinfo = S.getDelaySlotInfoForInstr(brNode, /*create*/ true);
1091   dinfo->addDelayNode(node);
1092 }
1093
1094
1095 void
1096 FindUsefulInstructionsForDelaySlots(SchedulingManager& S,
1097                                     SchedGraphNode* brNode,
1098                                     std::vector<SchedGraphNode*>& sdelayNodeVec)
1099 {
1100   const TargetInstrInfo& mii = S.getInstrInfo();
1101   unsigned ndelays =
1102     mii.getNumDelaySlots(brNode->getOpcode());
1103   
1104   if (ndelays == 0)
1105     return;
1106   
1107   sdelayNodeVec.reserve(ndelays);
1108   
1109   // Use a separate vector to hold the feasible multi-cycle nodes.
1110   // These will be used if not enough single-cycle nodes are found.
1111   // 
1112   std::vector<SchedGraphNode*> mdelayNodeVec;
1113   
1114   for (sg_pred_iterator P = pred_begin(brNode);
1115        P != pred_end(brNode) && sdelayNodeVec.size() < ndelays; ++P)
1116     if (! (*P)->isDummyNode() &&
1117         ! mii.isNop((*P)->getOpcode()) &&
1118         NodeCanFillDelaySlot(S, *P, brNode, /*pred*/ true))
1119     {
1120       if (mii.maxLatency((*P)->getOpcode()) > 1)
1121         mdelayNodeVec.push_back(*P);
1122       else
1123         sdelayNodeVec.push_back(*P);
1124     }
1125   
1126   // If not enough single-cycle instructions were found, select the
1127   // lowest-latency multi-cycle instructions and use them.
1128   // Note that this is the most efficient code when only 1 (or even 2)
1129   // values need to be selected.
1130   // 
1131   while (sdelayNodeVec.size() < ndelays && mdelayNodeVec.size() > 0) {
1132     unsigned lmin =
1133       mii.maxLatency(mdelayNodeVec[0]->getOpcode());
1134     unsigned minIndex   = 0;
1135     for (unsigned i=1; i < mdelayNodeVec.size(); i++)
1136     {
1137       unsigned li = 
1138         mii.maxLatency(mdelayNodeVec[i]->getOpcode());
1139       if (lmin >= li)
1140       {
1141         lmin = li;
1142         minIndex = i;
1143       }
1144     }
1145     sdelayNodeVec.push_back(mdelayNodeVec[minIndex]);
1146     if (sdelayNodeVec.size() < ndelays) // avoid the last erase!
1147       mdelayNodeVec.erase(mdelayNodeVec.begin() + minIndex);
1148   }
1149 }
1150
1151
1152 // Remove the NOPs currently in delay slots from the graph.
1153 // Mark instructions specified in sdelayNodeVec to replace them.
1154 // If not enough useful instructions were found, mark the NOPs to be used
1155 // for filling delay slots, otherwise, otherwise just discard them.
1156 // 
1157 static void ReplaceNopsWithUsefulInstr(SchedulingManager& S,
1158                                        SchedGraphNode* node,
1159                                        // FIXME: passing vector BY VALUE!!!
1160                                      std::vector<SchedGraphNode*> sdelayNodeVec,
1161                                        SchedGraph* graph)
1162 {
1163   std::vector<SchedGraphNode*> nopNodeVec;   // this will hold unused NOPs
1164   const TargetInstrInfo& mii = S.getInstrInfo();
1165   const MachineInstr* brInstr = node->getMachineInstr();
1166   unsigned ndelays= mii.getNumDelaySlots(brInstr->getOpcode());
1167   assert(ndelays > 0 && "Unnecessary call to replace NOPs");
1168   
1169   // Remove the NOPs currently in delay slots from the graph.
1170   // If not enough useful instructions were found, use the NOPs to
1171   // fill delay slots, otherwise, just discard them.
1172   //  
1173   unsigned int firstDelaySlotIdx = node->getOrigIndexInBB() + 1;
1174   MachineBasicBlock& MBB = node->getMachineBasicBlock();
1175   MachineBasicBlock::iterator MBBI = MBB.begin();
1176   std::advance(MBBI, firstDelaySlotIdx - 1);
1177   assert(&*MBBI++ == brInstr &&
1178          "Incorrect instr. index in basic block for brInstr");
1179   
1180   // First find all useful instructions already in the delay slots
1181   // and USE THEM.  We'll throw away the unused alternatives below
1182   // 
1183   MachineBasicBlock::iterator Tmp = MBBI;
1184   for (unsigned i = 0; i != ndelays; ++i, ++MBBI)
1185     if (!mii.isNop(MBBI->getOpcode()))
1186       sdelayNodeVec.insert(sdelayNodeVec.begin(),
1187                            graph->getGraphNodeForInstr(MBBI));
1188   MBBI = Tmp;
1189
1190   // Then find the NOPs and keep only as many as are needed.
1191   // Put the rest in nopNodeVec to be deleted.
1192   for (unsigned i=firstDelaySlotIdx; i < firstDelaySlotIdx+ndelays; ++i, ++MBBI)
1193     if (mii.isNop(MBBI->getOpcode()))
1194       if (sdelayNodeVec.size() < ndelays)
1195         sdelayNodeVec.push_back(graph->getGraphNodeForInstr(MBBI));
1196       else {
1197         nopNodeVec.push_back(graph->getGraphNodeForInstr(MBBI));
1198           
1199         //remove the MI from the Machine Code For Instruction
1200         const TerminatorInst *TI = MBB.getBasicBlock()->getTerminator();
1201         MachineCodeForInstruction& llvmMvec = 
1202           MachineCodeForInstruction::get((const Instruction *)TI);
1203           
1204         for(MachineCodeForInstruction::iterator mciI=llvmMvec.begin(), 
1205               mciE=llvmMvec.end(); mciI!=mciE; ++mciI){
1206           if (*mciI == MBBI)
1207             llvmMvec.erase(mciI);
1208         }
1209       }
1210
1211   assert(sdelayNodeVec.size() >= ndelays);
1212   
1213   // If some delay slots were already filled, throw away that many new choices
1214   if (sdelayNodeVec.size() > ndelays)
1215     sdelayNodeVec.resize(ndelays);
1216   
1217   // Mark the nodes chosen for delay slots.  This removes them from the graph.
1218   for (unsigned i=0; i < sdelayNodeVec.size(); i++)
1219     MarkNodeForDelaySlot(S, graph, sdelayNodeVec[i], node, true);
1220   
1221   // And remove the unused NOPs from the graph.
1222   for (unsigned i=0; i < nopNodeVec.size(); i++)
1223     graph->eraseIncidentEdges(nopNodeVec[i], /*addDummyEdges*/ true);
1224 }
1225
1226
1227 // For all delayed instructions, choose instructions to put in the delay
1228 // slots and pull those out of the graph.  Mark them for the delay slots
1229 // in the DelaySlotInfo object for that graph node.  If no useful work
1230 // is found for a delay slot, use the NOP that is currently in that slot.
1231 // 
1232 // We try to fill the delay slots with useful work for all instructions
1233 // EXCEPT CALLS AND RETURNS.
1234 // For CALLs and RETURNs, it is nearly always possible to use one of the
1235 // call sequence instrs and putting anything else in the delay slot could be
1236 // suboptimal.  Also, it complicates generating the calling sequence code in
1237 // regalloc.
1238 // 
1239 static void
1240 ChooseInstructionsForDelaySlots(SchedulingManager& S, MachineBasicBlock &MBB,
1241                                 SchedGraph *graph)
1242 {
1243   const TargetInstrInfo& mii = S.getInstrInfo();
1244
1245   Instruction *termInstr = (Instruction*)MBB.getBasicBlock()->getTerminator();
1246   MachineCodeForInstruction &termMvec=MachineCodeForInstruction::get(termInstr);
1247   std::vector<SchedGraphNode*> delayNodeVec;
1248   const MachineInstr* brInstr = NULL;
1249   
1250   if (EnableFillingDelaySlots &&
1251       termInstr->getOpcode() != Instruction::Ret)
1252   {
1253     // To find instructions that need delay slots without searching the full
1254     // machine code, we assume that the only delayed instructions are CALLs
1255     // or instructions generated for the terminator inst.
1256     // Find the first branch instr in the sequence of machine instrs for term
1257     // 
1258     unsigned first = 0;
1259     while (first < termMvec.size() &&
1260            ! mii.isBranch(termMvec[first]->getOpcode()))
1261     {
1262       ++first;
1263     }
1264     assert(first < termMvec.size() &&
1265            "No branch instructions for BR?  Ok, but weird!  Delete assertion.");
1266       
1267     brInstr = (first < termMvec.size())? termMvec[first] : NULL;
1268       
1269     // Compute a vector of the nodes chosen for delay slots and then
1270     // mark delay slots to replace NOPs with these useful instructions.
1271     // 
1272     if (brInstr != NULL) {
1273       SchedGraphNode* brNode = graph->getGraphNodeForInstr(brInstr);
1274       FindUsefulInstructionsForDelaySlots(S, brNode, delayNodeVec);
1275       ReplaceNopsWithUsefulInstr(S, brNode, delayNodeVec, graph);
1276     }
1277   }
1278   
1279   // Also mark delay slots for other delayed instructions to hold NOPs. 
1280   // Simply passing in an empty delayNodeVec will have this effect.
1281   // If brInstr is not handled above (EnableFillingDelaySlots == false),
1282   // brInstr will be NULL so this will handle the branch instrs. as well.
1283   // 
1284   delayNodeVec.clear();
1285   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
1286     if (I != brInstr && mii.getNumDelaySlots(I->getOpcode()) > 0) {
1287       SchedGraphNode* node = graph->getGraphNodeForInstr(I);
1288       ReplaceNopsWithUsefulInstr(S, node, delayNodeVec, graph);
1289     }
1290 }
1291
1292
1293 // 
1294 // Schedule the delayed branch and its delay slots
1295 // 
1296 unsigned
1297 DelaySlotInfo::scheduleDelayedNode(SchedulingManager& S)
1298 {
1299   assert(delayedNodeSlotNum < S.nslots && "Illegal slot for branch");
1300   assert(S.isched.getInstr(delayedNodeSlotNum, delayedNodeCycle) == NULL
1301          && "Slot for branch should be empty");
1302   
1303   unsigned int nextSlot = delayedNodeSlotNum;
1304   cycles_t nextTime = delayedNodeCycle;
1305   
1306   S.scheduleInstr(brNode, nextSlot, nextTime);
1307   
1308   for (unsigned d=0; d < ndelays; d++) {
1309     ++nextSlot;
1310     if (nextSlot == S.nslots) {
1311       nextSlot = 0;
1312       nextTime++;
1313     }
1314       
1315     // Find the first feasible instruction for this delay slot
1316     // Note that we only check for issue restrictions here.
1317     // We do *not* check for flow dependences but rely on pipeline
1318     // interlocks to resolve them.  Machines without interlocks
1319     // will require this code to be modified.
1320     for (unsigned i=0; i < delayNodeVec.size(); i++) {
1321       const SchedGraphNode* dnode = delayNodeVec[i];
1322       if ( ! S.isScheduled(dnode)
1323            && S.schedInfo.instrCanUseSlot(dnode->getOpcode(), nextSlot)
1324            && instrIsFeasible(S, dnode->getOpcode())) {
1325         S.scheduleInstr(dnode, nextSlot, nextTime);
1326         break;
1327       }
1328     }
1329   }
1330   
1331   // Update current time if delay slots overflowed into later cycles.
1332   // Do this here because we know exactly which cycle is the last cycle
1333   // that contains delay slots.  The next loop doesn't compute that.
1334   if (nextTime > S.getTime())
1335     S.updateTime(nextTime);
1336   
1337   // Now put any remaining instructions in the unfilled delay slots.
1338   // This could lead to suboptimal performance but needed for correctness.
1339   nextSlot = delayedNodeSlotNum;
1340   nextTime = delayedNodeCycle;
1341   for (unsigned i=0; i < delayNodeVec.size(); i++)
1342     if (! S.isScheduled(delayNodeVec[i])) {
1343       do { // find the next empty slot
1344         ++nextSlot;
1345         if (nextSlot == S.nslots) {
1346           nextSlot = 0;
1347           nextTime++;
1348         }
1349       } while (S.isched.getInstr(nextSlot, nextTime) != NULL);
1350         
1351       S.scheduleInstr(delayNodeVec[i], nextSlot, nextTime);
1352       break;
1353     }
1354
1355   return 1 + ndelays;
1356 }
1357
1358
1359 // Check if the instruction would conflict with instructions already
1360 // chosen for the current cycle
1361 // 
1362 static inline bool
1363 ConflictsWithChoices(const SchedulingManager& S,
1364                      MachineOpCode opCode)
1365 {
1366   // Check if the instruction must issue by itself, and some feasible
1367   // choices have already been made for this cycle
1368   if (S.getNumChoices() > 0 && S.schedInfo.isSingleIssue(opCode))
1369     return true;
1370   
1371   // For each class that opCode belongs to, check if there are too many
1372   // instructions of that class.
1373   // 
1374   const InstrSchedClass sc = S.schedInfo.getSchedClass(opCode);
1375   return (S.getNumChoicesInClass(sc) == S.schedInfo.getMaxIssueForClass(sc));
1376 }
1377
1378
1379 //************************* External Functions *****************************/
1380
1381
1382 //---------------------------------------------------------------------------
1383 // Function: ViolatesMinimumGap
1384 // 
1385 // Purpose:
1386 //   Check minimum gap requirements relative to instructions scheduled in
1387 //   previous cycles.
1388 //   Note that we do not need to consider `nextEarliestIssueTime' here because
1389 //   that is also captured in the earliest start times for each opcode.
1390 //---------------------------------------------------------------------------
1391
1392 static inline bool
1393 ViolatesMinimumGap(const SchedulingManager& S,
1394                    MachineOpCode opCode,
1395                    const cycles_t inCycle)
1396 {
1397   return (inCycle < S.getEarliestStartTimeForOp(opCode));
1398 }
1399
1400
1401 //---------------------------------------------------------------------------
1402 // Function: instrIsFeasible
1403 // 
1404 // Purpose:
1405 //   Check if any issue restrictions would prevent the instruction from
1406 //   being issued in the current cycle
1407 //---------------------------------------------------------------------------
1408
1409 bool
1410 instrIsFeasible(const SchedulingManager& S,
1411                 MachineOpCode opCode)
1412 {
1413   // skip the instruction if it cannot be issued due to issue restrictions
1414   // caused by previously issued instructions
1415   if (ViolatesMinimumGap(S, opCode, S.getTime()))
1416     return false;
1417   
1418   // skip the instruction if it cannot be issued due to issue restrictions
1419   // caused by previously chosen instructions for the current cycle
1420   if (ConflictsWithChoices(S, opCode))
1421     return false;
1422   
1423   return true;
1424 }
1425
1426 //---------------------------------------------------------------------------
1427 // Function: ScheduleInstructionsWithSSA
1428 // 
1429 // Purpose:
1430 //   Entry point for instruction scheduling on SSA form.
1431 //   Schedules the machine instructions generated by instruction selection.
1432 //   Assumes that register allocation has not been done, i.e., operands
1433 //   are still in SSA form.
1434 //---------------------------------------------------------------------------
1435
1436 namespace {
1437   class InstructionSchedulingWithSSA : public FunctionPass {
1438     const TargetMachine &target;
1439   public:
1440     inline InstructionSchedulingWithSSA(const TargetMachine &T) : target(T) {}
1441
1442     const char *getPassName() const { return "Instruction Scheduling"; }
1443   
1444     // getAnalysisUsage - We use LiveVarInfo...
1445     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1446       AU.addRequired<FunctionLiveVarInfo>();
1447       AU.setPreservesCFG();
1448     }
1449     
1450     bool runOnFunction(Function &F);
1451   };
1452 } // end anonymous namespace
1453
1454
1455 bool InstructionSchedulingWithSSA::runOnFunction(Function &F)
1456 {
1457   SchedGraphSet graphSet(&F, target);   
1458   
1459   if (SchedDebugLevel >= Sched_PrintSchedGraphs) {
1460       std::cerr << "\n*** SCHEDULING GRAPHS FOR INSTRUCTION SCHEDULING\n";
1461       graphSet.dump();
1462     }
1463   
1464   for (SchedGraphSet::const_iterator GI=graphSet.begin(), GE=graphSet.end();
1465        GI != GE; ++GI)
1466   {
1467     SchedGraph* graph = (*GI);
1468     MachineBasicBlock &MBB = graph->getBasicBlock();
1469       
1470     if (SchedDebugLevel >= Sched_PrintSchedTrace)
1471       std::cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
1472       
1473     // expensive!
1474     SchedPriorities schedPrio(&F, graph, getAnalysis<FunctionLiveVarInfo>());
1475     SchedulingManager S(target, graph, schedPrio);
1476           
1477     ChooseInstructionsForDelaySlots(S, MBB, graph); // modifies graph
1478     ForwardListSchedule(S);               // computes schedule in S
1479     RecordSchedule(MBB, S);                // records schedule in BB
1480   }
1481   
1482   if (SchedDebugLevel >= Sched_PrintMachineCode) {
1483     std::cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
1484     MachineFunction::get(&F).dump();
1485   }
1486   
1487   return false;
1488 }
1489
1490
1491 FunctionPass *createInstructionSchedulingWithSSAPass(const TargetMachine &tgt) {
1492   return new InstructionSchedulingWithSSA(tgt);
1493 }
1494
1495 } // End llvm namespace
1496