1 //===-- ScheduleDAGSimple.cpp - Implement a trivial DAG scheduler ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a simple two pass scheduler. The first pass attempts to push
11 // backward any lengthy instructions and critical paths. The second pass packs
12 // instructions into semi-optimal time slots.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
28 typedef NodeInfo *NodeInfoPtr;
29 typedef std::vector<NodeInfoPtr> NIVector;
30 typedef std::vector<NodeInfoPtr>::iterator NIIterator;
32 //===--------------------------------------------------------------------===//
34 /// Node group - This struct is used to manage flagged node groups.
40 NIVector Members; // Group member nodes
41 NodeInfo *Dominator; // Node with highest latency
42 unsigned Latency; // Total latency of the group
43 int Pending; // Number of visits pending before
48 NodeGroup() : Next(NULL), Dominator(NULL), Pending(0) {}
51 inline void setDominator(NodeInfo *D) { Dominator = D; }
52 inline NodeInfo *getTop() { return Members.front(); }
53 inline NodeInfo *getBottom() { return Members.back(); }
54 inline NodeInfo *getDominator() { return Dominator; }
55 inline void setLatency(unsigned L) { Latency = L; }
56 inline unsigned getLatency() { return Latency; }
57 inline int getPending() const { return Pending; }
58 inline void setPending(int P) { Pending = P; }
59 inline int addPending(int I) { return Pending += I; }
62 inline bool group_empty() { return Members.empty(); }
63 inline NIIterator group_begin() { return Members.begin(); }
64 inline NIIterator group_end() { return Members.end(); }
65 inline void group_push_back(const NodeInfoPtr &NI) {
66 Members.push_back(NI);
68 inline NIIterator group_insert(NIIterator Pos, const NodeInfoPtr &NI) {
69 return Members.insert(Pos, NI);
71 inline void group_insert(NIIterator Pos, NIIterator First,
73 Members.insert(Pos, First, Last);
76 static void Add(NodeInfo *D, NodeInfo *U);
79 //===--------------------------------------------------------------------===//
81 /// NodeInfo - This struct tracks information used to schedule the a node.
85 int Pending; // Number of visits pending before
88 SDNode *Node; // DAG node
89 InstrStage *StageBegin; // First stage in itinerary
90 InstrStage *StageEnd; // Last+1 stage in itinerary
91 unsigned Latency; // Total cycles to complete instr
92 bool IsCall : 1; // Is function call
93 bool IsLoad : 1; // Is memory load
94 bool IsStore : 1; // Is memory store
95 unsigned Slot; // Node's time slot
96 NodeGroup *Group; // Grouping information
98 unsigned Preorder; // Index before scheduling
102 NodeInfo(SDNode *N = NULL)
117 inline bool isInGroup() const {
118 assert(!Group || !Group->group_empty() && "Group with no members");
119 return Group != NULL;
121 inline bool isGroupDominator() const {
122 return isInGroup() && Group->getDominator() == this;
124 inline int getPending() const {
125 return Group ? Group->getPending() : Pending;
127 inline void setPending(int P) {
128 if (Group) Group->setPending(P);
131 inline int addPending(int I) {
132 if (Group) return Group->addPending(I);
133 else return Pending += I;
137 //===--------------------------------------------------------------------===//
139 /// NodeGroupIterator - Iterates over all the nodes indicated by the node
140 /// info. If the node is in a group then iterate over the members of the
141 /// group, otherwise just the node info.
143 class NodeGroupIterator {
145 NodeInfo *NI; // Node info
146 NIIterator NGI; // Node group iterator
147 NIIterator NGE; // Node group iterator end
151 NodeGroupIterator(NodeInfo *N) : NI(N) {
152 // If the node is in a group then set up the group iterator. Otherwise
153 // the group iterators will trip first time out.
154 if (N->isInGroup()) {
156 NodeGroup *Group = NI->Group;
157 NGI = Group->group_begin();
158 NGE = Group->group_end();
159 // Prevent this node from being used (will be in members list
164 /// next - Return the next node info, otherwise NULL.
168 if (NGI != NGE) return *NGI++;
169 // Use node as the result (may be NULL)
170 NodeInfo *Result = NI;
173 // Return node or NULL
177 //===--------------------------------------------------------------------===//
180 //===--------------------------------------------------------------------===//
182 /// NodeGroupOpIterator - Iterates over all the operands of a node. If the
183 /// node is a member of a group, this iterates over all the operands of all
184 /// the members of the group.
186 class NodeGroupOpIterator {
188 NodeInfo *NI; // Node containing operands
189 NodeGroupIterator GI; // Node group iterator
190 SDNode::op_iterator OI; // Operand iterator
191 SDNode::op_iterator OE; // Operand iterator end
193 /// CheckNode - Test if node has more operands. If not get the next node
194 /// skipping over nodes that have no operands.
196 // Only if operands are exhausted first
198 // Get next node info
199 NodeInfo *NI = GI.next();
200 // Exit if nodes are exhausted
203 SDNode *Node = NI->Node;
204 // Set up the operand iterators
205 OI = Node->op_begin();
212 NodeGroupOpIterator(NodeInfo *N)
213 : NI(N), GI(N), OI(SDNode::op_iterator()), OE(SDNode::op_iterator()) {}
215 /// isEnd - Returns true when not more operands are available.
217 inline bool isEnd() { CheckNode(); return OI == OE; }
219 /// next - Returns the next available operand.
221 inline SDOperand next() {
223 "Not checking for end of NodeGroupOpIterator correctly");
229 //===----------------------------------------------------------------------===//
231 /// BitsIterator - Provides iteration through individual bits in a bit vector.
236 T Bits; // Bits left to iterate through
240 BitsIterator(T Initial) : Bits(Initial) {}
242 /// Next - Returns the next bit set or zero if exhausted.
244 // Get the rightmost bit set
245 T Result = Bits & -Bits;
248 // Return single bit or zero
253 //===----------------------------------------------------------------------===//
256 //===----------------------------------------------------------------------===//
258 /// ResourceTally - Manages the use of resources over time intervals. Each
259 /// item (slot) in the tally vector represents the resources used at a given
260 /// moment. A bit set to 1 indicates that a resource is in use, otherwise
261 /// available. An assumption is made that the tally is large enough to schedule
262 /// all current instructions (asserts otherwise.)
265 class ResourceTally {
267 std::vector<T> Tally; // Resources used per slot
268 typedef typename std::vector<T>::iterator Iter;
271 /// SlotsAvailable - Returns true if all units are available.
273 bool SlotsAvailable(Iter Begin, unsigned N, unsigned ResourceSet,
274 unsigned &Resource) {
275 assert(N && "Must check availability with N != 0");
276 // Determine end of interval
277 Iter End = Begin + N;
278 assert(End <= Tally.end() && "Tally is not large enough for schedule");
280 // Iterate thru each resource
281 BitsIterator<T> Resources(ResourceSet & ~*Begin);
282 while (unsigned Res = Resources.Next()) {
283 // Check if resource is available for next N slots
287 if (*Interval & Res) break;
288 } while (Interval != Begin);
290 // If available for N
291 if (Interval == Begin) {
303 /// RetrySlot - Finds a good candidate slot to retry search.
304 Iter RetrySlot(Iter Begin, unsigned N, unsigned ResourceSet) {
305 assert(N && "Must check availability with N != 0");
306 // Determine end of interval
307 Iter End = Begin + N;
308 assert(End <= Tally.end() && "Tally is not large enough for schedule");
310 while (Begin != End--) {
311 // Clear units in use
312 ResourceSet &= ~*End;
313 // If no units left then we should go no further
314 if (!ResourceSet) return End + 1;
316 // Made it all the way through
320 /// FindAndReserveStages - Return true if the stages can be completed. If
322 bool FindAndReserveStages(Iter Begin,
323 InstrStage *Stage, InstrStage *StageEnd) {
324 // If at last stage then we're done
325 if (Stage == StageEnd) return true;
326 // Get number of cycles for current stage
327 unsigned N = Stage->Cycles;
328 // Check to see if N slots are available, if not fail
330 if (!SlotsAvailable(Begin, N, Stage->Units, Resource)) return false;
331 // Check to see if remaining stages are available, if not fail
332 if (!FindAndReserveStages(Begin + N, Stage + 1, StageEnd)) return false;
334 Reserve(Begin, N, Resource);
339 /// Reserve - Mark busy (set) the specified N slots.
340 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
341 // Determine end of interval
342 Iter End = Begin + N;
343 assert(End <= Tally.end() && "Tally is not large enough for schedule");
345 // Set resource bit in each slot
346 for (; Begin < End; Begin++)
350 /// FindSlots - Starting from Begin, locate consecutive slots where all stages
351 /// can be completed. Returns the address of first slot.
352 Iter FindSlots(Iter Begin, InstrStage *StageBegin, InstrStage *StageEnd) {
356 // Try all possible slots forward
358 // Try at cursor, if successful return position.
359 if (FindAndReserveStages(Cursor, StageBegin, StageEnd)) return Cursor;
360 // Locate a better position
361 Cursor = RetrySlot(Cursor + 1, StageBegin->Cycles, StageBegin->Units);
366 /// Initialize - Resize and zero the tally to the specified number of time
368 inline void Initialize(unsigned N) {
369 Tally.assign(N, 0); // Initialize tally to all zeros.
372 // FindAndReserve - Locate an ideal slot for the specified stages and mark
374 unsigned FindAndReserve(unsigned Slot, InstrStage *StageBegin,
375 InstrStage *StageEnd) {
377 Iter Begin = Tally.begin() + Slot;
379 Iter Where = FindSlots(Begin, StageBegin, StageEnd);
380 // Distance is slot number
381 unsigned Final = Where - Tally.begin();
387 //===----------------------------------------------------------------------===//
389 /// ScheduleDAGSimple - Simple two pass scheduler.
391 class ScheduleDAGSimple : public ScheduleDAG {
393 bool NoSched; // Just do a BFS schedule, nothing fancy
394 bool NoItins; // Don't use itineraries?
395 ResourceTally<unsigned> Tally; // Resource usage tally
396 unsigned NSlots; // Total latency
397 static const unsigned NotFound = ~0U; // Search marker
399 unsigned NodeCount; // Number of nodes in DAG
400 std::map<SDNode *, NodeInfo *> Map; // Map nodes to info
401 bool HasGroups; // True if there are any groups
402 NodeInfo *Info; // Info for nodes being scheduled
403 NIVector Ordering; // Emit ordering of nodes
404 NodeGroup *HeadNG, *TailNG; // Keep track of allocated NodeGroups
409 ScheduleDAGSimple(bool noSched, bool noItins, SelectionDAG &dag,
410 MachineBasicBlock *bb, const TargetMachine &tm)
411 : ScheduleDAG(dag, bb, tm), NoSched(noSched), NoItins(noItins), NSlots(0),
412 NodeCount(0), HasGroups(false), Info(NULL), HeadNG(NULL), TailNG(NULL) {
413 assert(&TII && "Target doesn't provide instr info?");
414 assert(&MRI && "Target doesn't provide register info?");
417 virtual ~ScheduleDAGSimple() {
421 NodeGroup *NG = HeadNG;
423 NodeGroup *NextSU = NG->Next;
431 /// getNI - Returns the node info for the specified node.
433 NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
436 static bool isDefiner(NodeInfo *A, NodeInfo *B);
437 void IncludeNode(NodeInfo *NI);
439 void GatherSchedulingInfo();
440 void FakeGroupDominators();
441 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
442 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
443 void ScheduleBackward();
444 void ScheduleForward();
446 void AddToGroup(NodeInfo *D, NodeInfo *U);
447 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
449 void PrepareNodeInfo();
451 /// IdentifyGroups - Put flagged nodes into groups.
453 void IdentifyGroups();
455 /// print - Print ordering to specified output stream.
457 void print(std::ostream &O) const;
459 void dump(const char *tag) const;
461 virtual void dump() const;
463 /// EmitAll - Emit all nodes in schedule sorted order.
467 /// printNI - Print node info.
469 void printNI(std::ostream &O, NodeInfo *NI) const;
471 /// printChanges - Hilight changes in order caused by scheduling.
473 void printChanges(unsigned Index) const;
476 //===----------------------------------------------------------------------===//
477 /// Special case itineraries.
480 CallLatency = 40, // To push calls back in time
482 RSInteger = 0xC0000000, // Two integer units
483 RSFloat = 0x30000000, // Two float units
484 RSLoadStore = 0x0C000000, // Two load store units
485 RSBranch = 0x02000000 // One branch unit
487 static InstrStage CallStage = { CallLatency, RSBranch };
488 static InstrStage LoadStage = { 5, RSLoadStore };
489 static InstrStage StoreStage = { 2, RSLoadStore };
490 static InstrStage IntStage = { 2, RSInteger };
491 static InstrStage FloatStage = { 3, RSFloat };
492 //===----------------------------------------------------------------------===//
496 //===----------------------------------------------------------------------===//
498 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
500 void ScheduleDAGSimple::PrepareNodeInfo() {
501 // Allocate node information
502 Info = new NodeInfo[NodeCount];
505 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
506 E = DAG.allnodes_end(); I != E; ++I, ++i) {
507 // Fast reference to node schedule info
508 NodeInfo* NI = &Info[i];
513 // Set pending visit count
514 NI->setPending(I->use_size());
518 /// IdentifyGroups - Put flagged nodes into groups.
520 void ScheduleDAGSimple::IdentifyGroups() {
521 for (unsigned i = 0, N = NodeCount; i < N; i++) {
522 NodeInfo* NI = &Info[i];
523 SDNode *Node = NI->Node;
525 // For each operand (in reverse to only look at flags)
526 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
528 SDOperand Op = Node->getOperand(N);
529 // No more flags to walk
530 if (Op.getValueType() != MVT::Flag) break;
532 AddToGroup(getNI(Op.Val), NI);
533 // Let everyone else know
539 /// CountInternalUses - Returns the number of edges between the two nodes.
541 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
543 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
544 SDOperand Op = U->Node->getOperand(M);
545 if (Op.Val == D->Node) N++;
551 //===----------------------------------------------------------------------===//
552 /// Add - Adds a definer and user pair to a node group.
554 void ScheduleDAGSimple::AddToGroup(NodeInfo *D, NodeInfo *U) {
555 // Get current groups
556 NodeGroup *DGroup = D->Group;
557 NodeGroup *UGroup = U->Group;
558 // If both are members of groups
559 if (DGroup && UGroup) {
560 // There may have been another edge connecting
561 if (DGroup == UGroup) return;
562 // Add the pending users count
563 DGroup->addPending(UGroup->getPending());
564 // For each member of the users group
565 NodeGroupIterator UNGI(U);
566 while (NodeInfo *UNI = UNGI.next() ) {
569 // For each member of the definers group
570 NodeGroupIterator DNGI(D);
571 while (NodeInfo *DNI = DNGI.next() ) {
572 // Remove internal edges
573 DGroup->addPending(-CountInternalUses(DNI, UNI));
576 // Merge the two lists
577 DGroup->group_insert(DGroup->group_end(),
578 UGroup->group_begin(), UGroup->group_end());
580 // Make user member of definers group
582 // Add users uses to definers group pending
583 DGroup->addPending(U->Node->use_size());
584 // For each member of the definers group
585 NodeGroupIterator DNGI(D);
586 while (NodeInfo *DNI = DNGI.next() ) {
587 // Remove internal edges
588 DGroup->addPending(-CountInternalUses(DNI, U));
590 DGroup->group_push_back(U);
592 // Make definer member of users group
594 // Add definers uses to users group pending
595 UGroup->addPending(D->Node->use_size());
596 // For each member of the users group
597 NodeGroupIterator UNGI(U);
598 while (NodeInfo *UNI = UNGI.next() ) {
599 // Remove internal edges
600 UGroup->addPending(-CountInternalUses(D, UNI));
602 UGroup->group_insert(UGroup->group_begin(), D);
604 D->Group = U->Group = DGroup = new NodeGroup();
605 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
606 CountInternalUses(D, U));
607 DGroup->group_push_back(D);
608 DGroup->group_push_back(U);
613 TailNG->Next = DGroup;
619 /// print - Print ordering to specified output stream.
621 void ScheduleDAGSimple::print(std::ostream &O) const {
624 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
625 NodeInfo *NI = Ordering[i];
628 if (NI->isGroupDominator()) {
629 NodeGroup *Group = NI->Group;
630 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
641 void ScheduleDAGSimple::dump(const char *tag) const {
642 std::cerr << tag; dump();
645 void ScheduleDAGSimple::dump() const {
650 /// EmitAll - Emit all nodes in schedule sorted order.
652 void ScheduleDAGSimple::EmitAll() {
653 std::map<SDNode*, unsigned> VRBaseMap;
655 // For each node in the ordering
656 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
657 // Get the scheduling info
658 NodeInfo *NI = Ordering[i];
659 if (NI->isInGroup()) {
660 NodeGroupIterator NGI(Ordering[i]);
661 while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, VRBaseMap);
663 EmitNode(NI->Node, VRBaseMap);
668 /// isFlagDefiner - Returns true if the node defines a flag result.
669 static bool isFlagDefiner(SDNode *A) {
670 unsigned N = A->getNumValues();
671 return N && A->getValueType(N - 1) == MVT::Flag;
674 /// isFlagUser - Returns true if the node uses a flag result.
676 static bool isFlagUser(SDNode *A) {
677 unsigned N = A->getNumOperands();
678 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
681 /// printNI - Print node info.
683 void ScheduleDAGSimple::printNI(std::ostream &O, NodeInfo *NI) const {
685 SDNode *Node = NI->Node;
687 << std::hex << Node << std::dec
688 << ", Lat=" << NI->Latency
689 << ", Slot=" << NI->Slot
690 << ", ARITY=(" << Node->getNumOperands() << ","
691 << Node->getNumValues() << ")"
692 << " " << Node->getOperationName(&DAG);
693 if (isFlagDefiner(Node)) O << "<#";
694 if (isFlagUser(Node)) O << ">#";
698 /// printChanges - Hilight changes in order caused by scheduling.
700 void ScheduleDAGSimple::printChanges(unsigned Index) const {
702 // Get the ordered node count
703 unsigned N = Ordering.size();
704 // Determine if any changes
707 NodeInfo *NI = Ordering[i];
708 if (NI->Preorder != i) break;
712 std::cerr << Index << ". New Ordering\n";
714 for (i = 0; i < N; i++) {
715 NodeInfo *NI = Ordering[i];
716 std::cerr << " " << NI->Preorder << ". ";
717 printNI(std::cerr, NI);
719 if (NI->isGroupDominator()) {
720 NodeGroup *Group = NI->Group;
721 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
724 printNI(std::cerr, *NII);
730 std::cerr << Index << ". No Changes\n";
735 //===----------------------------------------------------------------------===//
736 /// isDefiner - Return true if node A is a definer for B.
738 bool ScheduleDAGSimple::isDefiner(NodeInfo *A, NodeInfo *B) {
739 // While there are A nodes
740 NodeGroupIterator NII(A);
741 while (NodeInfo *NI = NII.next()) {
743 SDNode *Node = NI->Node;
744 // While there operands in nodes of B
745 NodeGroupOpIterator NGOI(B);
746 while (!NGOI.isEnd()) {
747 SDOperand Op = NGOI.next();
748 // If node from A defines a node in B
749 if (Node == Op.Val) return true;
755 /// IncludeNode - Add node to NodeInfo vector.
757 void ScheduleDAGSimple::IncludeNode(NodeInfo *NI) {
759 SDNode *Node = NI->Node;
761 if (Node->getOpcode() == ISD::EntryToken) return;
762 // Check current count for node
763 int Count = NI->getPending();
764 // If the node is already in list
765 if (Count < 0) return;
766 // Decrement count to indicate a visit
768 // If count has gone to zero then add node to list
771 if (NI->isInGroup()) {
772 Ordering.push_back(NI->Group->getDominator());
774 Ordering.push_back(NI);
776 // indicate node has been added
779 // Mark as visited with new count
780 NI->setPending(Count);
783 /// GatherSchedulingInfo - Get latency and resource information about each node.
785 void ScheduleDAGSimple::GatherSchedulingInfo() {
786 // Get instruction itineraries for the target
787 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
790 for (unsigned i = 0, N = NodeCount; i < N; i++) {
792 NodeInfo* NI = &Info[i];
793 SDNode *Node = NI->Node;
795 // If there are itineraries and it is a machine instruction
796 if (InstrItins.isEmpty() || NoItins) {
798 if (Node->isTargetOpcode()) {
799 // Get return type to guess which processing unit
800 MVT::ValueType VT = Node->getValueType(0);
801 // Get machine opcode
802 MachineOpCode TOpc = Node->getTargetOpcode();
803 NI->IsCall = TII->isCall(TOpc);
804 NI->IsLoad = TII->isLoad(TOpc);
805 NI->IsStore = TII->isStore(TOpc);
807 if (TII->isLoad(TOpc)) NI->StageBegin = &LoadStage;
808 else if (TII->isStore(TOpc)) NI->StageBegin = &StoreStage;
809 else if (MVT::isInteger(VT)) NI->StageBegin = &IntStage;
810 else if (MVT::isFloatingPoint(VT)) NI->StageBegin = &FloatStage;
811 if (NI->StageBegin) NI->StageEnd = NI->StageBegin + 1;
813 } else if (Node->isTargetOpcode()) {
814 // get machine opcode
815 MachineOpCode TOpc = Node->getTargetOpcode();
816 // Check to see if it is a call
817 NI->IsCall = TII->isCall(TOpc);
818 // Get itinerary stages for instruction
819 unsigned II = TII->getSchedClass(TOpc);
820 NI->StageBegin = InstrItins.begin(II);
821 NI->StageEnd = InstrItins.end(II);
824 // One slot for the instruction itself
827 // Add long latency for a call to push it back in time
828 if (NI->IsCall) NI->Latency += CallLatency;
830 // Sum up all the latencies
831 for (InstrStage *Stage = NI->StageBegin, *E = NI->StageEnd;
832 Stage != E; Stage++) {
833 NI->Latency += Stage->Cycles;
836 // Sum up all the latencies for max tally size
837 NSlots += NI->Latency;
840 // Unify metrics if in a group
842 for (unsigned i = 0, N = NodeCount; i < N; i++) {
843 NodeInfo* NI = &Info[i];
845 if (NI->isInGroup()) {
846 NodeGroup *Group = NI->Group;
848 if (!Group->getDominator()) {
849 NIIterator NGI = Group->group_begin(), NGE = Group->group_end();
850 NodeInfo *Dominator = *NGI;
851 unsigned Latency = 0;
853 for (NGI++; NGI != NGE; NGI++) {
854 NodeInfo* NGNI = *NGI;
855 Latency += NGNI->Latency;
856 if (Dominator->Latency < NGNI->Latency) Dominator = NGNI;
859 Dominator->Latency = Latency;
860 Group->setDominator(Dominator);
867 /// VisitAll - Visit each node breadth-wise to produce an initial ordering.
868 /// Note that the ordering in the Nodes vector is reversed.
869 void ScheduleDAGSimple::VisitAll() {
870 // Add first element to list
871 NodeInfo *NI = getNI(DAG.getRoot().Val);
872 if (NI->isInGroup()) {
873 Ordering.push_back(NI->Group->getDominator());
875 Ordering.push_back(NI);
878 // Iterate through all nodes that have been added
879 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
880 // Visit all operands
881 NodeGroupOpIterator NGI(Ordering[i]);
882 while (!NGI.isEnd()) {
884 SDOperand Op = NGI.next();
886 SDNode *Node = Op.Val;
887 // Ignore passive nodes
888 if (isPassiveNode(Node)) continue;
890 IncludeNode(getNI(Node));
894 // Add entry node last (IncludeNode filters entry nodes)
895 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
896 Ordering.push_back(getNI(DAG.getEntryNode().Val));
899 std::reverse(Ordering.begin(), Ordering.end());
902 /// FakeGroupDominators - Set dominators for non-scheduling.
904 void ScheduleDAGSimple::FakeGroupDominators() {
905 for (unsigned i = 0, N = NodeCount; i < N; i++) {
906 NodeInfo* NI = &Info[i];
908 if (NI->isInGroup()) {
909 NodeGroup *Group = NI->Group;
911 if (!Group->getDominator()) {
912 Group->setDominator(NI);
918 /// isStrongDependency - Return true if node A has results used by node B.
919 /// I.E., B must wait for latency of A.
920 bool ScheduleDAGSimple::isStrongDependency(NodeInfo *A, NodeInfo *B) {
921 // If A defines for B then it's a strong dependency or
922 // if a load follows a store (may be dependent but why take a chance.)
923 return isDefiner(A, B) || (A->IsStore && B->IsLoad);
926 /// isWeakDependency Return true if node A produces a result that will
927 /// conflict with operands of B. It is assumed that we have called
928 /// isStrongDependency prior.
929 bool ScheduleDAGSimple::isWeakDependency(NodeInfo *A, NodeInfo *B) {
930 // TODO check for conflicting real registers and aliases
931 #if 0 // FIXME - Since we are in SSA form and not checking register aliasing
932 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
934 return A->Node->getOpcode() == ISD::EntryToken;
938 /// ScheduleBackward - Schedule instructions so that any long latency
939 /// instructions and the critical path get pushed back in time. Time is run in
940 /// reverse to allow code reuse of the Tally and eliminate the overhead of
941 /// biasing every slot indices against NSlots.
942 void ScheduleDAGSimple::ScheduleBackward() {
943 // Size and clear the resource tally
944 Tally.Initialize(NSlots);
945 // Get number of nodes to schedule
946 unsigned N = Ordering.size();
948 // For each node being scheduled
949 for (unsigned i = N; 0 < i--;) {
950 NodeInfo *NI = Ordering[i];
952 unsigned Slot = NotFound;
954 // Compare against those previously scheduled nodes
957 // Get following instruction
958 NodeInfo *Other = Ordering[j];
960 // Check dependency against previously inserted nodes
961 if (isStrongDependency(NI, Other)) {
962 Slot = Other->Slot + Other->Latency;
964 } else if (isWeakDependency(NI, Other)) {
970 // If independent of others (or first entry)
971 if (Slot == NotFound) Slot = 0;
973 #if 0 // FIXME - measure later
974 // Find a slot where the needed resources are available
975 if (NI->StageBegin != NI->StageEnd)
976 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
982 // Insert sort based on slot
985 // Get following instruction
986 NodeInfo *Other = Ordering[j];
987 // Should we look further (remember slots are in reverse time)
988 if (Slot >= Other->Slot) break;
989 // Shuffle other into ordering
990 Ordering[j - 1] = Other;
992 // Insert node in proper slot
993 if (j != i + 1) Ordering[j - 1] = NI;
997 /// ScheduleForward - Schedule instructions to maximize packing.
999 void ScheduleDAGSimple::ScheduleForward() {
1000 // Size and clear the resource tally
1001 Tally.Initialize(NSlots);
1002 // Get number of nodes to schedule
1003 unsigned N = Ordering.size();
1005 // For each node being scheduled
1006 for (unsigned i = 0; i < N; i++) {
1007 NodeInfo *NI = Ordering[i];
1009 unsigned Slot = NotFound;
1011 // Compare against those previously scheduled nodes
1014 // Get following instruction
1015 NodeInfo *Other = Ordering[j];
1017 // Check dependency against previously inserted nodes
1018 if (isStrongDependency(Other, NI)) {
1019 Slot = Other->Slot + Other->Latency;
1021 } else if (Other->IsCall || isWeakDependency(Other, NI)) {
1027 // If independent of others (or first entry)
1028 if (Slot == NotFound) Slot = 0;
1030 // Find a slot where the needed resources are available
1031 if (NI->StageBegin != NI->StageEnd)
1032 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1037 // Insert sort based on slot
1040 // Get prior instruction
1041 NodeInfo *Other = Ordering[j];
1042 // Should we look further
1043 if (Slot >= Other->Slot) break;
1044 // Shuffle other into ordering
1045 Ordering[j + 1] = Other;
1047 // Insert node in proper slot
1048 if (j != i) Ordering[j + 1] = NI;
1052 /// Schedule - Order nodes according to selected style.
1054 void ScheduleDAGSimple::Schedule() {
1056 NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
1058 // Set up minimum info for scheduling
1060 // Construct node groups for flagged nodes
1063 // Test to see if scheduling should occur
1064 bool ShouldSchedule = NodeCount > 3 && !NoSched;
1065 // Don't waste time if is only entry and return
1066 if (ShouldSchedule) {
1067 // Get latency and resource requirements
1068 GatherSchedulingInfo();
1069 } else if (HasGroups) {
1070 // Make sure all the groups have dominators
1071 FakeGroupDominators();
1074 // Breadth first walk of DAG
1078 static unsigned Count = 0;
1080 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1081 NodeInfo *NI = Ordering[i];
1086 // Don't waste time if is only entry and return
1087 if (ShouldSchedule) {
1088 // Push back long instructions and critical path
1091 // Pack instructions to maximize resource utilization
1095 DEBUG(printChanges(Count));
1097 // Emit in scheduled order
1102 /// createSimpleDAGScheduler - This creates a simple two pass instruction
1104 llvm::ScheduleDAG* llvm::createSimpleDAGScheduler(bool NoItins,
1106 MachineBasicBlock *BB) {
1107 return new ScheduleDAGSimple(false, NoItins, DAG, BB, DAG.getTarget());
1110 llvm::ScheduleDAG* llvm::createBFS_DAGScheduler(SelectionDAG &DAG,
1111 MachineBasicBlock *BB) {
1112 return new ScheduleDAGSimple(true, false, DAG, BB, DAG.getTarget());