1. Made things node-centric (from operand).
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===-- ScheduleDAG.cpp - Implement a trivial DAG scheduler ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/SelectionDAGISel.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include <iostream>
28 using namespace llvm;
29
30 namespace {
31   // Style of scheduling to use.
32   enum ScheduleChoices {
33     noScheduling,
34     simpleScheduling,
35   };
36 } // namespace
37
38 cl::opt<ScheduleChoices> ScheduleStyle("sched",
39   cl::desc("Choose scheduling style"),
40   cl::init(noScheduling),
41   cl::values(
42     clEnumValN(noScheduling, "none",
43               "Trivial emission with no analysis"),
44     clEnumValN(simpleScheduling, "simple",
45               "Minimize critical path and maximize processor utilization"),
46    clEnumValEnd));
47
48
49 #ifndef NDEBUG
50 static cl::opt<bool>
51 ViewDAGs("view-sched-dags", cl::Hidden,
52          cl::desc("Pop up a window to show sched dags as they are processed"));
53 #else
54 static const bool ViewDAGs = 0;
55 #endif
56
57 namespace {
58 //===----------------------------------------------------------------------===//
59 ///
60 /// BitsIterator - Provides iteration through individual bits in a bit vector.
61 ///
62 template<class T>
63 class BitsIterator {
64 private:
65   T Bits;                               // Bits left to iterate through
66
67 public:
68   /// Ctor.
69   BitsIterator(T Initial) : Bits(Initial) {}
70   
71   /// Next - Returns the next bit set or zero if exhausted.
72   inline T Next() {
73     // Get the rightmost bit set
74     T Result = Bits & -Bits;
75     // Remove from rest
76     Bits &= ~Result;
77     // Return single bit or zero
78     return Result;
79   }
80 };
81   
82 //===----------------------------------------------------------------------===//
83
84
85 //===----------------------------------------------------------------------===//
86 ///
87 /// ResourceTally - Manages the use of resources over time intervals.  Each
88 /// item (slot) in the tally vector represents the resources used at a given
89 /// moment.  A bit set to 1 indicates that a resource is in use, otherwise
90 /// available.  An assumption is made that the tally is large enough to schedule 
91 /// all current instructions (asserts otherwise.)
92 ///
93 template<class T>
94 class ResourceTally {
95 private:
96   std::vector<T> Tally;                 // Resources used per slot
97   typedef typename std::vector<T>::iterator Iter;
98                                         // Tally iterator 
99   
100   /// AllInUse - Test to see if all of the resources in the slot are busy (set.)
101   inline bool AllInUse(Iter Cursor, unsigned ResourceSet) {
102     return (*Cursor & ResourceSet) == ResourceSet;
103   }
104
105   /// Skip - Skip over slots that use all of the specified resource (all are
106   /// set.)
107   Iter Skip(Iter Cursor, unsigned ResourceSet) {
108     assert(ResourceSet && "At least one resource bit needs to bet set");
109     
110     // Continue to the end
111     while (true) {
112       // Break out if one of the resource bits is not set
113       if (!AllInUse(Cursor, ResourceSet)) return Cursor;
114       // Try next slot
115       Cursor++;
116       assert(Cursor < Tally.end() && "Tally is not large enough for schedule");
117     }
118   }
119   
120   /// FindSlots - Starting from Begin, locate N consecutive slots where at least 
121   /// one of the resource bits is available.  Returns the address of first slot.
122   Iter FindSlots(Iter Begin, unsigned N, unsigned ResourceSet,
123                                          unsigned &Resource) {
124     // Track position      
125     Iter Cursor = Begin;
126     
127     // Try all possible slots forward
128     while (true) {
129       // Skip full slots
130       Cursor = Skip(Cursor, ResourceSet);
131       // Determine end of interval
132       Iter End = Cursor + N;
133       assert(End <= Tally.end() && "Tally is not large enough for schedule");
134       
135       // Iterate thru each resource
136       BitsIterator<T> Resources(ResourceSet & ~*Cursor);
137       while (unsigned Res = Resources.Next()) {
138         // Check if resource is available for next N slots
139         // Break out if resource is busy
140         Iter Interval = Cursor;
141         for (; Interval < End && !(*Interval & Res); Interval++) {}
142         
143         // If available for interval, return where and which resource
144         if (Interval == End) {
145           Resource = Res;
146           return Cursor;
147         }
148         // Otherwise, check if worth checking other resources
149         if (AllInUse(Interval, ResourceSet)) {
150           // Start looking beyond interval
151           Cursor = Interval;
152           break;
153         }
154       }
155       Cursor++;
156     }
157   }
158   
159   /// Reserve - Mark busy (set) the specified N slots.
160   void Reserve(Iter Begin, unsigned N, unsigned Resource) {
161     // Determine end of interval
162     Iter End = Begin + N;
163     assert(End <= Tally.end() && "Tally is not large enough for schedule");
164  
165     // Set resource bit in each slot
166     for (; Begin < End; Begin++)
167       *Begin |= Resource;
168   }
169
170 public:
171   /// Initialize - Resize and zero the tally to the specified number of time
172   /// slots.
173   inline void Initialize(unsigned N) {
174     Tally.assign(N, 0);   // Initialize tally to all zeros.
175   }
176   
177   // FindAndReserve - Locate and mark busy (set) N bits started at slot I, using
178   // ResourceSet for choices.
179   unsigned FindAndReserve(unsigned I, unsigned N, unsigned ResourceSet) {
180     // Which resource used
181     unsigned Resource;
182     // Find slots for instruction.
183     Iter Where = FindSlots(Tally.begin() + I, N, ResourceSet, Resource);
184     // Reserve the slots
185     Reserve(Where, N, Resource);
186     // Return time slot (index)
187     return Where - Tally.begin();
188   }
189
190 };
191 //===----------------------------------------------------------------------===//
192
193
194 //===----------------------------------------------------------------------===//
195 ///
196 /// Node group -  This struct is used to manage flagged node groups.
197 ///
198 class NodeInfo;
199 class NodeGroup : public std::vector<NodeInfo *> {
200 private:
201   int           Pending;                // Number of visits pending before
202                                         //    adding to order  
203
204 public:
205   // Ctor.
206   NodeGroup() : Pending(0) {}
207   
208   // Accessors
209   inline NodeInfo *getLeader() { return empty() ? NULL : front(); }
210   inline int getPending() const { return Pending; }
211   inline void setPending(int P)  { Pending = P; }
212   inline int addPending(int I)  { return Pending += I; }
213
214   static void Add(NodeInfo *D, NodeInfo *U);
215   static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U);
216 };
217 //===----------------------------------------------------------------------===//
218
219
220 //===----------------------------------------------------------------------===//
221 ///
222 /// NodeInfo - This struct tracks information used to schedule the a node.
223 ///
224 class NodeInfo {
225 private:
226   int           Pending;                // Number of visits pending before
227                                         //    adding to order
228 public:
229   SDNode        *Node;                  // DAG node
230   unsigned      Latency;                // Cycles to complete instruction
231   unsigned      ResourceSet;            // Bit vector of usable resources
232   unsigned      Slot;                   // Node's time slot
233   NodeGroup     *Group;                 // Grouping information
234   unsigned      VRBase;                 // Virtual register base
235   
236   // Ctor.
237   NodeInfo(SDNode *N = NULL)
238   : Pending(0)
239   , Node(N)
240   , Latency(0)
241   , ResourceSet(0)
242   , Slot(0)
243   , Group(NULL)
244   , VRBase(0)
245   {}
246   
247   // Accessors
248   inline bool isInGroup() const {
249     assert(!Group || !Group->empty() && "Group with no members");
250     return Group != NULL;
251   }
252   inline bool isGroupLeader() const {
253      return isInGroup() && Group->getLeader() == this;
254   }
255   inline int getPending() const {
256     return Group ? Group->getPending() : Pending;
257   }
258   inline void setPending(int P) {
259     if (Group) Group->setPending(P);
260     else       Pending = P;
261   }
262   inline int addPending(int I) {
263     if (Group) return Group->addPending(I);
264     else       return Pending += I;
265   }
266 };
267 typedef std::vector<NodeInfo *>::iterator NIIterator;
268 //===----------------------------------------------------------------------===//
269
270
271 //===----------------------------------------------------------------------===//
272 ///
273 /// NodeGroupIterator - Iterates over all the nodes indicated by the node info.
274 /// If the node is in a group then iterate over the members of the group,
275 /// otherwise just the node info.
276 ///
277 class NodeGroupIterator {
278 private:
279   NodeInfo   *NI;                       // Node info
280   NIIterator NGI;                       // Node group iterator
281   NIIterator NGE;                       // Node group iterator end
282   
283 public:
284   // Ctor.
285   NodeGroupIterator(NodeInfo *N) : NI(N) {
286     // If the node is in a group then set up the group iterator.  Otherwise
287     // the group iterators will trip first time out.
288     if (N->isInGroup()) {
289       // get Group
290       NodeGroup *Group = NI->Group;
291       NGI = Group->begin();
292       NGE = Group->end();
293       // Prevent this node from being used (will be in members list
294       NI = NULL;
295     }
296   }
297   
298   /// next - Return the next node info, otherwise NULL.
299   ///
300   NodeInfo *next() {
301     // If members list
302     if (NGI != NGE) return *NGI++;
303     // Use node as the result (may be NULL)
304     NodeInfo *Result = NI;
305     // Only use once
306     NI = NULL;
307     // Return node or NULL
308     return Result;
309   }
310 };
311 //===----------------------------------------------------------------------===//
312
313
314 //===----------------------------------------------------------------------===//
315 ///
316 /// NodeGroupOpIterator - Iterates over all the operands of a node.  If the node
317 /// is a member of a group, this iterates over all the operands of all the
318 /// members of the group.
319 ///
320 class NodeGroupOpIterator {
321 private:
322   NodeInfo            *NI;              // Node containing operands
323   NodeGroupIterator   GI;               // Node group iterator
324   SDNode::op_iterator OI;               // Operand iterator
325   SDNode::op_iterator OE;               // Operand iterator end
326   
327   /// CheckNode - Test if node has more operands.  If not get the next node
328   /// skipping over nodes that have no operands.
329   void CheckNode() {
330     // Only if operands are exhausted first
331     while (OI == OE) {
332       // Get next node info
333       NodeInfo *NI = GI.next();
334       // Exit if nodes are exhausted
335       if (!NI) return;
336       // Get node itself
337       SDNode *Node = NI->Node;
338       // Set up the operand iterators
339       OI = Node->op_begin();
340       OE = Node->op_end();
341     }
342   }
343   
344 public:
345   // Ctor.
346   NodeGroupOpIterator(NodeInfo *N) : NI(N), GI(N) {}
347   
348   /// isEnd - Returns true when not more operands are available.
349   ///
350   inline bool isEnd() { CheckNode(); return OI == OE; }
351   
352   /// next - Returns the next available operand.
353   ///
354   inline SDOperand next() {
355     assert(OI != OE && "Not checking for end of NodeGroupOpIterator correctly");
356     return *OI++;
357   }
358 };
359 //===----------------------------------------------------------------------===//
360
361
362 //===----------------------------------------------------------------------===//
363 ///
364 /// SimpleSched - Simple two pass scheduler.
365 ///
366 class SimpleSched {
367 private:
368   // TODO - get ResourceSet from TII
369   enum {
370     RSInteger = 0x3,                    // Two integer units
371     RSFloat = 0xC,                      // Two float units
372     RSLoadStore = 0x30,                 // Two load store units
373     RSOther = 0                         // Processing unit independent
374   };
375   
376   MachineBasicBlock *BB;                // Current basic block
377   SelectionDAG &DAG;                    // DAG of the current basic block
378   const TargetMachine &TM;              // Target processor
379   const TargetInstrInfo &TII;           // Target instruction information
380   const MRegisterInfo &MRI;             // Target processor register information
381   SSARegMap *RegMap;                    // Virtual/real register map
382   MachineConstantPool *ConstPool;       // Target constant pool
383   unsigned NodeCount;                   // Number of nodes in DAG
384   NodeInfo *Info;                       // Info for nodes being scheduled
385   std::map<SDNode *, NodeInfo *> Map;   // Map nodes to info
386   std::vector<NodeInfo*> Ordering;      // Emit ordering of nodes
387   ResourceTally<unsigned> Tally;        // Resource usage tally
388   unsigned NSlots;                      // Total latency
389   std::map<SDNode *, unsigned> VRMap;   // Node to VR map
390   static const unsigned NotFound = ~0U; // Search marker
391   
392 public:
393
394   // Ctor.
395   SimpleSched(SelectionDAG &D, MachineBasicBlock *bb)
396     : BB(bb), DAG(D), TM(D.getTarget()), TII(*TM.getInstrInfo()),
397       MRI(*TM.getRegisterInfo()), RegMap(BB->getParent()->getSSARegMap()),
398       ConstPool(BB->getParent()->getConstantPool()),
399       NSlots(0) {
400     assert(&TII && "Target doesn't provide instr info?");
401     assert(&MRI && "Target doesn't provide register info?");
402   }
403   
404   // Run - perform scheduling.
405   MachineBasicBlock *Run() {
406     Schedule();
407     return BB;
408   }
409   
410 private:
411   /// getNI - Returns the node info for the specified node.
412   ///
413   inline NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
414   
415   /// getVR - Returns the virtual register number of the node.
416   ///
417   inline unsigned getVR(SDOperand Op) {
418     NodeInfo *NI = getNI(Op.Val);
419     assert(NI->VRBase != 0 && "Node emitted out of order - late");
420     return NI->VRBase + Op.ResNo;
421   }
422
423   static bool isFlagDefiner(SDNode *A);
424   static bool isFlagUser(SDNode *A);
425   static bool isDefiner(NodeInfo *A, NodeInfo *B);
426   static bool isPassiveNode(SDNode *Node);
427   void IncludeNode(NodeInfo *NI);
428   void VisitAll();
429   void Schedule();
430   void GatherNodeInfo();
431   bool isStrongDependency(NodeInfo *A, NodeInfo *B);
432   bool isWeakDependency(NodeInfo *A, NodeInfo *B);
433   void ScheduleBackward();
434   void ScheduleForward();
435   void EmitAll();
436   void EmitNode(NodeInfo *NI);
437   static unsigned CountResults(SDNode *Node);
438   static unsigned CountOperands(SDNode *Node);
439   unsigned CreateVirtualRegisters(MachineInstr *MI,
440                                   unsigned NumResults,
441                                   const TargetInstrDescriptor &II);
442   unsigned EmitDAG(SDOperand A);
443
444   void printSI(std::ostream &O, NodeInfo *NI) const;
445   void print(std::ostream &O) const;
446   inline void dump(const char *tag) const { std::cerr << tag; dump(); }
447   void dump() const;
448 };
449 //===----------------------------------------------------------------------===//
450
451
452 //===----------------------------------------------------------------------===//
453 class FlagUserIterator {
454 private:
455   SDNode               *Definer;        // Node defining flag
456   SDNode::use_iterator UI;              // User node iterator
457   SDNode::use_iterator E;               // End of user nodes
458   unsigned             MinRes;          // Minimum flag result
459
460 public:
461   // Ctor.
462   FlagUserIterator(SDNode *D)
463   : Definer(D)
464   , UI(D->use_begin())
465   , E(D->use_end())
466   , MinRes(D->getNumValues()) {
467     // Find minimum flag result.
468     while (MinRes && D->getValueType(MinRes - 1) == MVT::Flag) --MinRes;
469   }
470   
471   /// isFlagUser - Return true if  node uses definer's flag.
472   bool isFlagUser(SDNode *U) {
473     // For each operand (in reverse to only look at flags)
474     for (unsigned N = U->getNumOperands(); 0 < N--;) {
475       // Get operand
476       SDOperand Op = U->getOperand(N);
477       // Not user if there are no flags
478       if (Op.getValueType() != MVT::Flag) return false;
479       // Return true if it is one of the flag results 
480       if (Op.Val == Definer && Op.ResNo >= MinRes) return true;
481     }
482     // Not a flag user
483     return false;
484   }
485   
486   SDNode *next() {
487     // Continue to next user
488     while (UI != E) {
489       // Next user node
490       SDNode *User = *UI++;
491       // Return true if is a flag user
492       if (isFlagUser(User)) return User;
493     }
494     
495     // No more user nodes
496     return NULL;
497   }
498 };
499
500 } // namespace
501 //===----------------------------------------------------------------------===//
502
503
504 //===----------------------------------------------------------------------===//
505 /// Add - Adds a definer and user pair to a node group.
506 ///
507 void NodeGroup::Add(NodeInfo *D, NodeInfo *U) {
508   // Get current groups
509   NodeGroup *DGroup = D->Group;
510   NodeGroup *UGroup = U->Group;
511   // If both are members of groups
512   if (DGroup && UGroup) {
513     // There may have been another edge connecting 
514     if (DGroup == UGroup) return;
515     // Add the pending users count
516     DGroup->addPending(UGroup->getPending());
517     // For each member of the users group
518     NodeGroupIterator UNGI(U);
519     while (NodeInfo *UNI = UNGI.next() ) {
520       // Change the group
521       UNI->Group = DGroup;
522       // For each member of the definers group
523       NodeGroupIterator DNGI(D);
524       while (NodeInfo *DNI = DNGI.next() ) {
525         // Remove internal edges
526         DGroup->addPending(-CountInternalUses(DNI, UNI));
527       }
528     }
529     // Merge the two lists
530     DGroup->insert(DGroup->end(), UGroup->begin(), UGroup->end());
531   } else if (DGroup) {
532     // Make user member of definers group
533     U->Group = DGroup;
534     // Add users uses to definers group pending
535     DGroup->addPending(U->Node->use_size());
536     // For each member of the definers group
537     NodeGroupIterator DNGI(D);
538     while (NodeInfo *DNI = DNGI.next() ) {
539       // Remove internal edges
540       DGroup->addPending(-CountInternalUses(DNI, U));
541     }
542     DGroup->push_back(U);
543   } else if (UGroup) {
544     // Make definer member of users group
545     D->Group = UGroup;
546     // Add definers uses to users group pending
547     UGroup->addPending(D->Node->use_size());
548     // For each member of the users group
549     NodeGroupIterator UNGI(U);
550     while (NodeInfo *UNI = UNGI.next() ) {
551       // Remove internal edges
552       UGroup->addPending(-CountInternalUses(D, UNI));
553     }
554     UGroup->insert(UGroup->begin(), D);
555   } else {
556     D->Group = U->Group = DGroup = new NodeGroup();
557     DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
558                        CountInternalUses(D, U));
559     DGroup->push_back(D);
560     DGroup->push_back(U);
561   }
562 }
563
564 /// CountInternalUses - Returns the number of edges between the two nodes.
565 ///
566 unsigned NodeGroup::CountInternalUses(NodeInfo *D, NodeInfo *U) {
567   unsigned N = 0;
568   for (SDNode:: use_iterator UI = D->Node->use_begin(),
569                              E = D->Node->use_end(); UI != E; UI++) {
570     if (*UI == U->Node) N++;
571   }
572   return N;
573 }
574 //===----------------------------------------------------------------------===//
575
576
577 //===----------------------------------------------------------------------===//
578 /// isFlagDefiner - Returns true if the node defines a flag result.
579 bool SimpleSched::isFlagDefiner(SDNode *A) {
580   unsigned N = A->getNumValues();
581   return N && A->getValueType(N - 1) == MVT::Flag;
582 }
583
584 /// isFlagUser - Returns true if the node uses a flag result.
585 ///
586 bool SimpleSched::isFlagUser(SDNode *A) {
587   unsigned N = A->getNumOperands();
588   return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
589 }
590
591 /// isDefiner - Return true if node A is a definer for B.
592 ///
593 bool SimpleSched::isDefiner(NodeInfo *A, NodeInfo *B) {
594   // While there are A nodes
595   NodeGroupIterator NII(A);
596   while (NodeInfo *NI = NII.next()) {
597     // Extract node
598     SDNode *Node = NI->Node;
599     // While there operands in nodes of B
600     NodeGroupOpIterator NGOI(B);
601     while (!NGOI.isEnd()) {
602       SDOperand Op = NGOI.next();
603       // If node from A defines a node in B
604       if (Node == Op.Val) return true;
605     }
606   }
607   return false;
608 }
609
610 /// isPassiveNode - Return true if the node is a non-scheduled leaf.
611 ///
612 bool SimpleSched::isPassiveNode(SDNode *Node) {
613   if (isa<ConstantSDNode>(Node))       return true;
614   if (isa<RegisterSDNode>(Node))       return true;
615   if (isa<GlobalAddressSDNode>(Node))  return true;
616   if (isa<BasicBlockSDNode>(Node))     return true;
617   if (isa<FrameIndexSDNode>(Node))     return true;
618   if (isa<ConstantPoolSDNode>(Node))   return true;
619   if (isa<ExternalSymbolSDNode>(Node)) return true;
620   return false;
621 }
622
623 /// IncludeNode - Add node to NodeInfo vector.
624 ///
625 void SimpleSched::IncludeNode(NodeInfo *NI) {
626   // Get node
627   SDNode *Node = NI->Node;
628   // Ignore entry node
629 if (Node->getOpcode() == ISD::EntryToken) return;
630   // Check current count for node
631   int Count = NI->getPending();
632   // If the node is already in list
633   if (Count < 0) return;
634   // Decrement count to indicate a visit
635   Count--;
636   // If count has gone to zero then add node to list
637   if (!Count) {
638     // Add node
639     if (NI->isInGroup()) {
640       Ordering.push_back(NI->Group->getLeader());
641     } else {
642       Ordering.push_back(NI);
643     }
644     // indicate node has been added
645     Count--;
646   }
647   // Mark as visited with new count 
648   NI->setPending(Count);
649 }
650
651 /// VisitAll - Visit each node breadth-wise to produce an initial ordering.
652 /// Note that the ordering in the Nodes vector is reversed.
653 void SimpleSched::VisitAll() {
654   // Add first element to list
655   Ordering.push_back(getNI(DAG.getRoot().Val));
656   
657   // Iterate through all nodes that have been added
658   for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
659     // Visit all operands
660     NodeGroupOpIterator NGI(Ordering[i]);
661     while (!NGI.isEnd()) {
662       // Get next operand
663       SDOperand Op = NGI.next();
664       // Get node
665       SDNode *Node = Op.Val;
666       // Ignore passive nodes
667       if (isPassiveNode(Node)) continue;
668       // Check out node
669       IncludeNode(getNI(Node));
670     }
671   }
672
673   // Add entry node last (IncludeNode filters entry nodes)
674   if (DAG.getEntryNode().Val != DAG.getRoot().Val)
675     Ordering.push_back(getNI(DAG.getEntryNode().Val));
676     
677   // FIXME - Reverse the order
678   for (unsigned i = 0, N = Ordering.size(), Half = N >> 1; i < Half; i++) {
679     unsigned j = N - i - 1;
680     NodeInfo *tmp = Ordering[i];
681     Ordering[i] = Ordering[j];
682     Ordering[j] = tmp;
683   }
684 }
685
686 /// GatherNodeInfo - Get latency and resource information about each node.
687 /// 
688 void SimpleSched::GatherNodeInfo() {
689   // Allocate node information
690   Info = new NodeInfo[NodeCount];
691   // Get base of all nodes table
692   SelectionDAG::allnodes_iterator AllNodes = DAG.allnodes_begin();
693   
694   // For each node being scheduled
695   for (unsigned i = 0, N = NodeCount; i < N; i++) {
696     // Get next node from DAG all nodes table
697     SDNode *Node = AllNodes[i];
698     // Fast reference to node schedule info
699     NodeInfo* NI = &Info[i];
700     // Set up map
701     Map[Node] = NI;
702     // Set node
703     NI->Node = Node;
704     // Set pending visit count
705     NI->setPending(Node->use_size());    
706     
707     MVT::ValueType VT = Node->getValueType(0);
708     if (Node->isTargetOpcode()) {
709       MachineOpCode TOpc = Node->getTargetOpcode();
710       // FIXME: This is an ugly (but temporary!) hack to test the scheduler
711       // before we have real target info.
712       // FIXME NI->Latency = std::max(1, TII.maxLatency(TOpc));
713       // FIXME NI->ResourceSet = TII.resources(TOpc);
714       if (TII.isCall(TOpc)) {
715         NI->ResourceSet = RSInteger;
716         NI->Latency = 40;
717       } else if (TII.isLoad(TOpc)) {
718         NI->ResourceSet = RSLoadStore;
719         NI->Latency = 5;
720       } else if (TII.isStore(TOpc)) {
721         NI->ResourceSet = RSLoadStore;
722         NI->Latency = 2;
723       } else if (MVT::isInteger(VT)) {
724         NI->ResourceSet = RSInteger;
725         NI->Latency = 2;
726       } else if (MVT::isFloatingPoint(VT)) {
727         NI->ResourceSet = RSFloat;
728         NI->Latency = 3;
729       } else {
730         NI->ResourceSet = RSOther;
731         NI->Latency = 0;
732       }
733     } else {
734       if (MVT::isInteger(VT)) {
735         NI->ResourceSet = RSInteger;
736         NI->Latency = 2;
737       } else if (MVT::isFloatingPoint(VT)) {
738         NI->ResourceSet = RSFloat;
739         NI->Latency = 3;
740       } else {
741         NI->ResourceSet = RSOther;
742         NI->Latency = 0;
743       }
744     }
745     
746     // Add one slot for the instruction itself
747     NI->Latency++;
748     
749     // Sum up all the latencies for max tally size
750     NSlots += NI->Latency;
751   }
752   
753   // Put flagged nodes into groups
754   for (unsigned i = 0, N = NodeCount; i < N; i++) {
755     NodeInfo* NI = &Info[i];
756     SDNode *Node = NI->Node;
757     if (isFlagDefiner(Node)) {
758       FlagUserIterator FI(Node);
759       while (SDNode *User = FI.next()) NodeGroup::Add(NI, getNI(User));
760     }
761   }
762 }
763
764 /// isStrongDependency - Return true if node A has results used by node B. 
765 /// I.E., B must wait for latency of A.
766 bool SimpleSched::isStrongDependency(NodeInfo *A, NodeInfo *B) {
767   // If A defines for B then it's a strong dependency
768   return isDefiner(A, B);
769 }
770
771 /// isWeakDependency Return true if node A produces a result that will
772 /// conflict with operands of B.
773 bool SimpleSched::isWeakDependency(NodeInfo *A, NodeInfo *B) {
774   // TODO check for conflicting real registers and aliases
775 #if 0 // FIXME - Since we are in SSA form and not checking register aliasing
776   return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
777 #else
778   return A->Node->getOpcode() == ISD::EntryToken;
779 #endif
780 }
781
782 /// ScheduleBackward - Schedule instructions so that any long latency
783 /// instructions and the critical path get pushed back in time. Time is run in
784 /// reverse to allow code reuse of the Tally and eliminate the overhead of
785 /// biasing every slot indices against NSlots.
786 void SimpleSched::ScheduleBackward() {
787   // Size and clear the resource tally
788   Tally.Initialize(NSlots);
789   // Get number of nodes to schedule
790   unsigned N = Ordering.size();
791   
792   // For each node being scheduled
793   for (unsigned i = N; 0 < i--;) {
794     NodeInfo *NI = Ordering[i];
795     // Track insertion
796     unsigned Slot = NotFound;
797     
798     // Compare against those previously scheduled nodes
799     unsigned j = i + 1;
800     for (; j < N; j++) {
801       // Get following instruction
802       NodeInfo *Other = Ordering[j];
803       
804       // Check dependency against previously inserted nodes
805       if (isStrongDependency(NI, Other)) {
806         Slot = Other->Slot + Other->Latency;
807         break;
808       } else if (isWeakDependency(NI, Other)) {
809         Slot = Other->Slot;
810         break;
811       }
812     }
813     
814     // If independent of others (or first entry)
815     if (Slot == NotFound) Slot = 0;
816     
817     // Find a slot where the needed resources are available
818     if (NI->ResourceSet)
819       Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
820       
821     // Set node slot
822     NI->Slot = Slot;
823     
824     // Insert sort based on slot
825     j = i + 1;
826     for (; j < N; j++) {
827       // Get following instruction
828       NodeInfo *Other = Ordering[j];
829       // Should we look further
830       if (Slot >= Other->Slot) break;
831       // Shuffle other into ordering
832       Ordering[j - 1] = Other;
833     }
834     // Insert node in proper slot
835     if (j != i + 1) Ordering[j - 1] = NI;
836   }
837 }
838
839 /// ScheduleForward - Schedule instructions to maximize packing.
840 ///
841 void SimpleSched::ScheduleForward() {
842   // Size and clear the resource tally
843   Tally.Initialize(NSlots);
844   // Get number of nodes to schedule
845   unsigned N = Ordering.size();
846   
847   // For each node being scheduled
848   for (unsigned i = 0; i < N; i++) {
849     NodeInfo *NI = Ordering[i];
850     // Track insertion
851     unsigned Slot = NotFound;
852     
853     // Compare against those previously scheduled nodes
854     unsigned j = i;
855     for (; 0 < j--;) {
856       // Get following instruction
857       NodeInfo *Other = Ordering[j];
858       
859       // Check dependency against previously inserted nodes
860       if (isStrongDependency(Other, NI)) {
861         Slot = Other->Slot + Other->Latency;
862         break;
863       } else if (isWeakDependency(Other, NI)) {
864         Slot = Other->Slot;
865         break;
866       }
867     }
868     
869     // If independent of others (or first entry)
870     if (Slot == NotFound) Slot = 0;
871     
872     // Find a slot where the needed resources are available
873     if (NI->ResourceSet)
874       Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
875       
876     // Set node slot
877     NI->Slot = Slot;
878     
879     // Insert sort based on slot
880     j = i;
881     for (; 0 < j--;) {
882       // Get following instruction
883       NodeInfo *Other = Ordering[j];
884       // Should we look further
885       if (Slot >= Other->Slot) break;
886       // Shuffle other into ordering
887       Ordering[j + 1] = Other;
888     }
889     // Insert node in proper slot
890     if (j != i) Ordering[j + 1] = NI;
891   }
892 }
893
894 /// EmitAll - Emit all nodes in schedule sorted order.
895 ///
896 void SimpleSched::EmitAll() {
897   // For each node in the ordering
898   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
899     // Get the scheduling info
900     NodeInfo *NI = Ordering[i];
901 #if 0
902     // Iterate through nodes
903     NodeGroupIterator NGI(Ordering[i]);
904     while (NodeInfo *NI = NGI.next()) EmitNode(NI);
905 #else
906     if (NI->isInGroup()) {
907       if (NI->isGroupLeader()) {
908         NodeGroupIterator NGI(Ordering[i]);
909         while (NodeInfo *NI = NGI.next()) EmitNode(NI);
910       }
911     } else {
912       EmitNode(NI);
913     }
914 #endif
915   }
916 }
917
918 /// CountResults - The results of target nodes have register or immediate
919 /// operands first, then an optional chain, and optional flag operands (which do
920 /// not go into the machine instrs.)
921 unsigned SimpleSched::CountResults(SDNode *Node) {
922   unsigned N = Node->getNumValues();
923   while (N && Node->getValueType(N - 1) == MVT::Flag)
924     --N;
925   if (N && Node->getValueType(N - 1) == MVT::Other)
926     --N;    // Skip over chain result.
927   return N;
928 }
929
930 /// CountOperands  The inputs to target nodes have any actual inputs first,
931 /// followed by an optional chain operand, then flag operands.  Compute the
932 /// number of actual operands that  will go into the machine instr.
933 unsigned SimpleSched::CountOperands(SDNode *Node) {
934   unsigned N = Node->getNumOperands();
935   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
936     --N;
937   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
938     --N; // Ignore chain if it exists.
939   return N;
940 }
941
942 /// CreateVirtualRegisters - Add result register values for things that are
943 /// defined by this instruction.
944 unsigned SimpleSched::CreateVirtualRegisters(MachineInstr *MI,
945                                              unsigned NumResults,
946                                              const TargetInstrDescriptor &II) {
947   // Create the result registers for this node and add the result regs to
948   // the machine instruction.
949   const TargetOperandInfo *OpInfo = II.OpInfo;
950   unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
951   MI->addRegOperand(ResultReg, MachineOperand::Def);
952   for (unsigned i = 1; i != NumResults; ++i) {
953     assert(OpInfo[i].RegClass && "Isn't a register operand!");
954     MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[0].RegClass),
955                       MachineOperand::Def);
956   }
957   return ResultReg;
958 }
959
960 /// EmitNode - Generate machine code for an node and needed dependencies.
961 ///
962 void SimpleSched::EmitNode(NodeInfo *NI) {
963   unsigned VRBase = 0;                 // First virtual register for node
964   SDNode *Node = NI->Node;
965   
966   // If machine instruction
967   if (Node->isTargetOpcode()) {
968     unsigned Opc = Node->getTargetOpcode();
969     const TargetInstrDescriptor &II = TII.get(Opc);
970
971     unsigned NumResults = CountResults(Node);
972     unsigned NodeOperands = CountOperands(Node);
973     unsigned NumMIOperands = NodeOperands + NumResults;
974 #ifndef NDEBUG
975     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
976            "#operands for dag node doesn't match .td file!"); 
977 #endif
978
979     // Create the new machine instruction.
980     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
981     
982     // Add result register values for things that are defined by this
983     // instruction.
984     if (NumResults) VRBase = CreateVirtualRegisters(MI, NumResults, II);
985     
986     // Emit all of the actual operands of this instruction, adding them to the
987     // instruction as appropriate.
988     for (unsigned i = 0; i != NodeOperands; ++i) {
989       if (Node->getOperand(i).isTargetOpcode()) {
990         // Note that this case is redundant with the final else block, but we
991         // include it because it is the most common and it makes the logic
992         // simpler here.
993         assert(Node->getOperand(i).getValueType() != MVT::Other &&
994                Node->getOperand(i).getValueType() != MVT::Flag &&
995                "Chain and flag operands should occur at end of operand list!");
996         
997         MI->addRegOperand(getVR(Node->getOperand(i)), MachineOperand::Use);
998       } else if (ConstantSDNode *C =
999                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1000         MI->addZeroExtImm64Operand(C->getValue());
1001       } else if (RegisterSDNode*R =
1002                  dyn_cast<RegisterSDNode>(Node->getOperand(i))) {
1003         MI->addRegOperand(R->getReg(), MachineOperand::Use);
1004       } else if (GlobalAddressSDNode *TGA =
1005                        dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
1006         MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0);
1007       } else if (BasicBlockSDNode *BB =
1008                        dyn_cast<BasicBlockSDNode>(Node->getOperand(i))) {
1009         MI->addMachineBasicBlockOperand(BB->getBasicBlock());
1010       } else if (FrameIndexSDNode *FI =
1011                        dyn_cast<FrameIndexSDNode>(Node->getOperand(i))) {
1012         MI->addFrameIndexOperand(FI->getIndex());
1013       } else if (ConstantPoolSDNode *CP = 
1014                     dyn_cast<ConstantPoolSDNode>(Node->getOperand(i))) {
1015         unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
1016         MI->addConstantPoolIndexOperand(Idx);
1017       } else if (ExternalSymbolSDNode *ES = 
1018                  dyn_cast<ExternalSymbolSDNode>(Node->getOperand(i))) {
1019         MI->addExternalSymbolOperand(ES->getSymbol(), false);
1020       } else {
1021         assert(Node->getOperand(i).getValueType() != MVT::Other &&
1022                Node->getOperand(i).getValueType() != MVT::Flag &&
1023                "Chain and flag operands should occur at end of operand list!");
1024         MI->addRegOperand(getVR(Node->getOperand(i)), MachineOperand::Use);
1025       }
1026     }
1027     
1028     // Now that we have emitted all operands, emit this instruction itself.
1029     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
1030       BB->insert(BB->end(), MI);
1031     } else {
1032       // Insert this instruction into the end of the basic block, potentially
1033       // taking some custom action.
1034       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
1035     }
1036   } else {
1037     switch (Node->getOpcode()) {
1038     default:
1039       Node->dump(); 
1040       assert(0 && "This target-independent node should have been selected!");
1041     case ISD::EntryToken: // fall thru
1042     case ISD::TokenFactor:
1043       break;
1044     case ISD::CopyToReg: {
1045       unsigned Val = getVR(Node->getOperand(2));
1046       MRI.copyRegToReg(*BB, BB->end(),
1047                        cast<RegisterSDNode>(Node->getOperand(1))->getReg(), Val,
1048                        RegMap->getRegClass(Val));
1049       break;
1050     }
1051     case ISD::CopyFromReg: {
1052       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1053       
1054       // Figure out the register class to create for the destreg.
1055       const TargetRegisterClass *TRC = 0;
1056       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
1057         TRC = RegMap->getRegClass(SrcReg);
1058       } else {
1059         // FIXME: we don't know what register class to generate this for.  Do
1060         // a brute force search and pick the first match. :(
1061         for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(),
1062                E = MRI.regclass_end(); I != E; ++I)
1063           if ((*I)->contains(SrcReg)) {
1064             TRC = *I;
1065             break;
1066           }
1067         assert(TRC && "Couldn't find register class for reg copy!");
1068       }
1069       
1070       // Create the reg, emit the copy.
1071       VRBase = RegMap->createVirtualRegister(TRC);
1072       MRI.copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
1073       break;
1074     }
1075     }
1076   }
1077
1078   assert(NI->VRBase == 0 && "Node emitted out of order - early");
1079   NI->VRBase = VRBase;
1080 }
1081
1082 /// EmitDag - Generate machine code for an operand and needed dependencies.
1083 ///
1084 unsigned SimpleSched::EmitDAG(SDOperand Op) {
1085   std::map<SDNode *, unsigned>::iterator OpI = VRMap.lower_bound(Op.Val);
1086   if (OpI != VRMap.end() && OpI->first == Op.Val)
1087     return OpI->second + Op.ResNo;
1088   unsigned &OpSlot = VRMap.insert(OpI, std::make_pair(Op.Val, 0))->second;
1089   
1090   unsigned ResultReg = 0;
1091   if (Op.isTargetOpcode()) {
1092     unsigned Opc = Op.getTargetOpcode();
1093     const TargetInstrDescriptor &II = TII.get(Opc);
1094
1095     unsigned NumResults = CountResults(Op.Val);
1096     unsigned NodeOperands = CountOperands(Op.Val);
1097     unsigned NumMIOperands = NodeOperands + NumResults;
1098 #ifndef NDEBUG
1099     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
1100            "#operands for dag node doesn't match .td file!"); 
1101 #endif
1102
1103     // Create the new machine instruction.
1104     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
1105     
1106     // Add result register values for things that are defined by this
1107     // instruction.
1108     if (NumResults) ResultReg = CreateVirtualRegisters(MI, NumResults, II);
1109     
1110     // If there is a token chain operand, emit it first, as a hack to get avoid
1111     // really bad cases.
1112     if (Op.getNumOperands() > NodeOperands &&
1113         Op.getOperand(NodeOperands).getValueType() == MVT::Other) {
1114       EmitDAG(Op.getOperand(NodeOperands));
1115     }
1116     
1117     // Emit all of the actual operands of this instruction, adding them to the
1118     // instruction as appropriate.
1119     for (unsigned i = 0; i != NodeOperands; ++i) {
1120       if (Op.getOperand(i).isTargetOpcode()) {
1121         // Note that this case is redundant with the final else block, but we
1122         // include it because it is the most common and it makes the logic
1123         // simpler here.
1124         assert(Op.getOperand(i).getValueType() != MVT::Other &&
1125                Op.getOperand(i).getValueType() != MVT::Flag &&
1126                "Chain and flag operands should occur at end of operand list!");
1127         
1128         MI->addRegOperand(EmitDAG(Op.getOperand(i)), MachineOperand::Use);
1129       } else if (ConstantSDNode *C =
1130                                    dyn_cast<ConstantSDNode>(Op.getOperand(i))) {
1131         MI->addZeroExtImm64Operand(C->getValue());
1132       } else if (RegisterSDNode*R =dyn_cast<RegisterSDNode>(Op.getOperand(i))) {
1133         MI->addRegOperand(R->getReg(), MachineOperand::Use);
1134       } else if (GlobalAddressSDNode *TGA =
1135                        dyn_cast<GlobalAddressSDNode>(Op.getOperand(i))) {
1136         MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0);
1137       } else if (BasicBlockSDNode *BB =
1138                        dyn_cast<BasicBlockSDNode>(Op.getOperand(i))) {
1139         MI->addMachineBasicBlockOperand(BB->getBasicBlock());
1140       } else if (FrameIndexSDNode *FI =
1141                        dyn_cast<FrameIndexSDNode>(Op.getOperand(i))) {
1142         MI->addFrameIndexOperand(FI->getIndex());
1143       } else if (ConstantPoolSDNode *CP = 
1144                     dyn_cast<ConstantPoolSDNode>(Op.getOperand(i))) {
1145         unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
1146         MI->addConstantPoolIndexOperand(Idx);
1147       } else if (ExternalSymbolSDNode *ES = 
1148                  dyn_cast<ExternalSymbolSDNode>(Op.getOperand(i))) {
1149         MI->addExternalSymbolOperand(ES->getSymbol(), false);
1150       } else {
1151         assert(Op.getOperand(i).getValueType() != MVT::Other &&
1152                Op.getOperand(i).getValueType() != MVT::Flag &&
1153                "Chain and flag operands should occur at end of operand list!");
1154         MI->addRegOperand(EmitDAG(Op.getOperand(i)), MachineOperand::Use);
1155       }
1156     }
1157
1158     // Finally, if this node has any flag operands, we *must* emit them last, to
1159     // avoid emitting operations that might clobber the flags.
1160     if (Op.getNumOperands() > NodeOperands) {
1161       unsigned i = NodeOperands;
1162       if (Op.getOperand(i).getValueType() == MVT::Other)
1163         ++i;  // the chain is already selected.
1164       for (unsigned N = Op.getNumOperands(); i < N; i++) {
1165         assert(Op.getOperand(i).getValueType() == MVT::Flag &&
1166                "Must be flag operands!");
1167         EmitDAG(Op.getOperand(i));
1168       }
1169     }
1170     
1171     // Now that we have emitted all operands, emit this instruction itself.
1172     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
1173       BB->insert(BB->end(), MI);
1174     } else {
1175       // Insert this instruction into the end of the basic block, potentially
1176       // taking some custom action.
1177       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
1178     }
1179   } else {
1180     switch (Op.getOpcode()) {
1181     default:
1182       Op.Val->dump(); 
1183       assert(0 && "This target-independent node should have been selected!");
1184     case ISD::EntryToken: break;
1185     case ISD::TokenFactor:
1186       for (unsigned i = 0, N = Op.getNumOperands(); i < N; i++) {
1187         EmitDAG(Op.getOperand(i));
1188       }
1189       break;
1190     case ISD::CopyToReg: {
1191       SDOperand FlagOp;
1192       if (Op.getNumOperands() == 4) {
1193         FlagOp = Op.getOperand(3);
1194       }
1195       if (Op.getOperand(0).Val != FlagOp.Val) {
1196         EmitDAG(Op.getOperand(0));   // Emit the chain.
1197       }
1198       unsigned Val = EmitDAG(Op.getOperand(2));
1199       if (FlagOp.Val) {
1200         EmitDAG(FlagOp);
1201       }
1202       MRI.copyRegToReg(*BB, BB->end(),
1203                        cast<RegisterSDNode>(Op.getOperand(1))->getReg(), Val,
1204                        RegMap->getRegClass(Val));
1205       break;
1206     }
1207     case ISD::CopyFromReg: {
1208       EmitDAG(Op.getOperand(0));   // Emit the chain.
1209       unsigned SrcReg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1210       
1211       // Figure out the register class to create for the destreg.
1212       const TargetRegisterClass *TRC = 0;
1213       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
1214         TRC = RegMap->getRegClass(SrcReg);
1215       } else {
1216         // FIXME: we don't know what register class to generate this for.  Do
1217         // a brute force search and pick the first match. :(
1218         for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(),
1219                E = MRI.regclass_end(); I != E; ++I)
1220           if ((*I)->contains(SrcReg)) {
1221             TRC = *I;
1222             break;
1223           }
1224         assert(TRC && "Couldn't find register class for reg copy!");
1225       }
1226       
1227       // Create the reg, emit the copy.
1228       ResultReg = RegMap->createVirtualRegister(TRC);
1229       MRI.copyRegToReg(*BB, BB->end(), ResultReg, SrcReg, TRC);
1230       break;
1231     }
1232     }
1233   }
1234
1235   OpSlot = ResultReg;
1236   return ResultReg+Op.ResNo;
1237 }
1238
1239 /// Schedule - Order nodes according to selected style.
1240 ///
1241 void SimpleSched::Schedule() {
1242   switch (ScheduleStyle) {
1243   case simpleScheduling:
1244     // Number the nodes
1245     NodeCount = DAG.allnodes_size();
1246     // Don't waste time if is only entry and return
1247     if (NodeCount > 3) {
1248       // Get latency and resource requirements
1249       GatherNodeInfo();
1250       // Breadth first walk of DAG
1251       VisitAll();
1252       DEBUG(dump("Pre-"));
1253       // Push back long instructions and critical path
1254       ScheduleBackward();
1255       DEBUG(dump("Mid-"));
1256       // Pack instructions to maximize resource utilization
1257       ScheduleForward();
1258       DEBUG(dump("Post-"));
1259       // Emit in scheduled order
1260       EmitAll();
1261       break;
1262     } // fall thru
1263   case noScheduling:
1264     // Emit instructions in using a DFS from the exit root
1265     EmitDAG(DAG.getRoot());
1266     break;
1267   }
1268 }
1269
1270 /// printSI - Print schedule info.
1271 ///
1272 void SimpleSched::printSI(std::ostream &O, NodeInfo *NI) const {
1273 #ifndef NDEBUG
1274   using namespace std;
1275   SDNode *Node = NI->Node;
1276   O << " "
1277     << hex << Node
1278     << ", RS=" << NI->ResourceSet
1279     << ", Lat=" << NI->Latency
1280     << ", Slot=" << NI->Slot
1281     << ", ARITY=(" << Node->getNumOperands() << ","
1282                    << Node->getNumValues() << ")"
1283     << " " << Node->getOperationName(&DAG);
1284   if (isFlagDefiner(Node)) O << "<#";
1285   if (isFlagUser(Node)) O << ">#";
1286 #endif
1287 }
1288
1289 /// print - Print ordering to specified output stream.
1290 ///
1291 void SimpleSched::print(std::ostream &O) const {
1292 #ifndef NDEBUG
1293   using namespace std;
1294   O << "Ordering\n";
1295   for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1296     printSI(O, Ordering[i]);
1297     O << "\n";
1298   }
1299 #endif
1300 }
1301
1302 /// dump - Print ordering to std::cerr.
1303 ///
1304 void SimpleSched::dump() const {
1305   print(std::cerr);
1306 }
1307 //===----------------------------------------------------------------------===//
1308
1309
1310 //===----------------------------------------------------------------------===//
1311 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1312 /// target node in the graph.
1313 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &SD) {
1314   if (ViewDAGs) SD.viewGraph();
1315   BB = SimpleSched(SD, BB).Run();  
1316 }