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