d5448055a8c866fd1bd7d139be44b3dc1bf59a2f
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
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/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MathExtras.h"
27 using namespace llvm;
28
29 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
30 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
31 /// together nodes with a single SUnit.
32 void ScheduleDAG::BuildSchedUnits() {
33   // Reserve entries in the vector for each of the SUnits we are creating.  This
34   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
35   // invalidated.
36   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
37   
38   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
39   
40   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
41        E = DAG.allnodes_end(); NI != E; ++NI) {
42     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
43       continue;
44     
45     // If this node has already been processed, stop now.
46     if (SUnitMap[NI]) continue;
47     
48     SUnit *NodeSUnit = NewSUnit(NI);
49     
50     // See if anything is flagged to this node, if so, add them to flagged
51     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
52     // are required the be the last operand and result of a node.
53     
54     // Scan up, adding flagged preds to FlaggedNodes.
55     SDNode *N = NI;
56     if (N->getNumOperands() &&
57         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
58       do {
59         N = N->getOperand(N->getNumOperands()-1).Val;
60         NodeSUnit->FlaggedNodes.push_back(N);
61         SUnitMap[N] = NodeSUnit;
62       } while (N->getNumOperands() &&
63                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
64       std::reverse(NodeSUnit->FlaggedNodes.begin(),
65                    NodeSUnit->FlaggedNodes.end());
66     }
67     
68     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
69     // have a user of the flag operand.
70     N = NI;
71     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
72       SDOperand FlagVal(N, N->getNumValues()-1);
73       
74       // There are either zero or one users of the Flag result.
75       bool HasFlagUse = false;
76       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
77            UI != E; ++UI)
78         if (FlagVal.isOperand(*UI)) {
79           HasFlagUse = true;
80           NodeSUnit->FlaggedNodes.push_back(N);
81           SUnitMap[N] = NodeSUnit;
82           N = *UI;
83           break;
84         }
85       if (!HasFlagUse) break;
86     }
87     
88     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
89     // Update the SUnit
90     NodeSUnit->Node = N;
91     SUnitMap[N] = NodeSUnit;
92     
93     // Compute the latency for the node.  We use the sum of the latencies for
94     // all nodes flagged together into this SUnit.
95     if (InstrItins.isEmpty()) {
96       // No latency information.
97       NodeSUnit->Latency = 1;
98     } else {
99       NodeSUnit->Latency = 0;
100       if (N->isTargetOpcode()) {
101         unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
102         InstrStage *S = InstrItins.begin(SchedClass);
103         InstrStage *E = InstrItins.end(SchedClass);
104         for (; S != E; ++S)
105           NodeSUnit->Latency += S->Cycles;
106       }
107       for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
108         SDNode *FNode = NodeSUnit->FlaggedNodes[i];
109         if (FNode->isTargetOpcode()) {
110           unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
111           InstrStage *S = InstrItins.begin(SchedClass);
112           InstrStage *E = InstrItins.end(SchedClass);
113           for (; S != E; ++S)
114             NodeSUnit->Latency += S->Cycles;
115         }
116       }
117     }
118   }
119   
120   // Pass 2: add the preds, succs, etc.
121   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
122     SUnit *SU = &SUnits[su];
123     SDNode *MainNode = SU->Node;
124     
125     if (MainNode->isTargetOpcode()) {
126       unsigned Opc = MainNode->getTargetOpcode();
127       for (unsigned i = 0, ee = TII->getNumOperands(Opc); i != ee; ++i) {
128         if (TII->getOperandConstraint(Opc, i, TOI::TIED_TO) != -1) {
129           SU->isTwoAddress = true;
130           break;
131         }
132       }
133       if (TII->isCommutableInstr(Opc))
134         SU->isCommutable = true;
135     }
136     
137     // Find all predecessors and successors of the group.
138     // Temporarily add N to make code simpler.
139     SU->FlaggedNodes.push_back(MainNode);
140     
141     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
142       SDNode *N = SU->FlaggedNodes[n];
143       
144       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
145         SDNode *OpN = N->getOperand(i).Val;
146         if (isPassiveNode(OpN)) continue;   // Not scheduled.
147         SUnit *OpSU = SUnitMap[OpN];
148         assert(OpSU && "Node has no SUnit!");
149         if (OpSU == SU) continue;           // In the same group.
150
151         MVT::ValueType OpVT = N->getOperand(i).getValueType();
152         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
153         bool isChain = OpVT == MVT::Other;
154         
155         if (SU->addPred(OpSU, isChain)) {
156           if (!isChain) {
157             SU->NumPreds++;
158             SU->NumPredsLeft++;
159           } else {
160             SU->NumChainPredsLeft++;
161           }
162         }
163         if (OpSU->addSucc(SU, isChain)) {
164           if (!isChain) {
165             OpSU->NumSuccs++;
166             OpSU->NumSuccsLeft++;
167           } else {
168             OpSU->NumChainSuccsLeft++;
169           }
170         }
171       }
172     }
173     
174     // Remove MainNode from FlaggedNodes again.
175     SU->FlaggedNodes.pop_back();
176   }
177   
178   return;
179 }
180
181 static void CalculateDepths(SUnit &SU, unsigned Depth) {
182   if (SU.Depth == 0 || Depth > SU.Depth) {
183     SU.Depth = Depth;
184     for (SUnit::succ_iterator I = SU.Succs.begin(), E = SU.Succs.end();
185          I != E; ++I)
186       CalculateDepths(*I->first, Depth+1);
187   }
188 }
189
190 void ScheduleDAG::CalculateDepths() {
191   SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
192   ::CalculateDepths(*Entry, 0U);
193   for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
194     if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
195       ::CalculateDepths(SUnits[i], 0U);
196     }
197 }
198
199 static void CalculateHeights(SUnit &SU, unsigned Height) {
200   if (SU.Height == 0 || Height > SU.Height) {
201     SU.Height = Height;
202     for (SUnit::pred_iterator I = SU.Preds.begin(), E = SU.Preds.end();
203          I != E; ++I)
204       CalculateHeights(*I->first, Height+1);
205   }
206 }
207 void ScheduleDAG::CalculateHeights() {
208   SUnit *Root = SUnitMap[DAG.getRoot().Val];
209   ::CalculateHeights(*Root, 0U);
210 }
211
212 /// CountResults - The results of target nodes have register or immediate
213 /// operands first, then an optional chain, and optional flag operands (which do
214 /// not go into the machine instrs.)
215 unsigned ScheduleDAG::CountResults(SDNode *Node) {
216   unsigned N = Node->getNumValues();
217   while (N && Node->getValueType(N - 1) == MVT::Flag)
218     --N;
219   if (N && Node->getValueType(N - 1) == MVT::Other)
220     --N;    // Skip over chain result.
221   return N;
222 }
223
224 /// CountOperands  The inputs to target nodes have any actual inputs first,
225 /// followed by an optional chain operand, then flag operands.  Compute the
226 /// number of actual operands that  will go into the machine instr.
227 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
228   unsigned N = Node->getNumOperands();
229   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
230     --N;
231   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
232     --N; // Ignore chain if it exists.
233   return N;
234 }
235
236 static const TargetRegisterClass *getInstrOperandRegClass(
237         const MRegisterInfo *MRI, 
238         const TargetInstrInfo *TII,
239         const TargetInstrDescriptor *II,
240         unsigned Op) {
241   if (Op >= II->numOperands) {
242     assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
243     return NULL;
244   }
245   const TargetOperandInfo &toi = II->OpInfo[Op];
246   return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
247          ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
248 }
249
250 static unsigned CreateVirtualRegisters(const MRegisterInfo *MRI,
251                                        MachineInstr *MI,
252                                        unsigned NumResults,
253                                        SSARegMap *RegMap,
254                                        const TargetInstrInfo *TII,
255                                        const TargetInstrDescriptor &II) {
256   // Create the result registers for this node and add the result regs to
257   // the machine instruction.
258   unsigned ResultReg =
259     RegMap->createVirtualRegister(getInstrOperandRegClass(MRI, TII, &II, 0));
260   MI->addRegOperand(ResultReg, true);
261   for (unsigned i = 1; i != NumResults; ++i) {
262     const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
263     assert(RC && "Isn't a register operand!");
264     MI->addRegOperand(RegMap->createVirtualRegister(RC), true);
265   }
266   return ResultReg;
267 }
268
269 /// getVR - Return the virtual register corresponding to the specified result
270 /// of the specified node.
271 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
272   std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
273   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
274   return I->second + Op.ResNo;
275 }
276
277
278 /// AddOperand - Add the specified operand to the specified machine instr.  II
279 /// specifies the instruction information for the node, and IIOpNum is the
280 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
281 /// assertions only.
282 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
283                              unsigned IIOpNum,
284                              const TargetInstrDescriptor *II,
285                              std::map<SDNode*, unsigned> &VRBaseMap) {
286   if (Op.isTargetOpcode()) {
287     // Note that this case is redundant with the final else block, but we
288     // include it because it is the most common and it makes the logic
289     // simpler here.
290     assert(Op.getValueType() != MVT::Other &&
291            Op.getValueType() != MVT::Flag &&
292            "Chain and flag operands should occur at end of operand list!");
293     
294     // Get/emit the operand.
295     unsigned VReg = getVR(Op, VRBaseMap);
296     MI->addRegOperand(VReg, false);
297     
298     // Verify that it is right.
299     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
300     if (II) {
301       const TargetRegisterClass *RC =
302                           getInstrOperandRegClass(MRI, TII, II, IIOpNum);
303       assert(RC && "Don't have operand info for this instruction!");
304       assert(RegMap->getRegClass(VReg) == RC &&
305              "Register class of operand and regclass of use don't agree!");
306     }
307   } else if (ConstantSDNode *C =
308              dyn_cast<ConstantSDNode>(Op)) {
309     MI->addImmOperand(C->getValue());
310   } else if (RegisterSDNode*R =
311              dyn_cast<RegisterSDNode>(Op)) {
312     MI->addRegOperand(R->getReg(), false);
313   } else if (GlobalAddressSDNode *TGA =
314              dyn_cast<GlobalAddressSDNode>(Op)) {
315     MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
316   } else if (BasicBlockSDNode *BB =
317              dyn_cast<BasicBlockSDNode>(Op)) {
318     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
319   } else if (FrameIndexSDNode *FI =
320              dyn_cast<FrameIndexSDNode>(Op)) {
321     MI->addFrameIndexOperand(FI->getIndex());
322   } else if (JumpTableSDNode *JT =
323              dyn_cast<JumpTableSDNode>(Op)) {
324     MI->addJumpTableIndexOperand(JT->getIndex());
325   } else if (ConstantPoolSDNode *CP = 
326              dyn_cast<ConstantPoolSDNode>(Op)) {
327     int Offset = CP->getOffset();
328     unsigned Align = CP->getAlignment();
329     const Type *Type = CP->getType();
330     // MachineConstantPool wants an explicit alignment.
331     if (Align == 0) {
332       if (Type == Type::DoubleTy)
333         Align = 3;  // always 8-byte align doubles.
334       else {
335         Align = TM.getTargetData()->getTypeAlignmentShift(Type);
336         if (Align == 0) {
337           // Alignment of packed types.  FIXME!
338           Align = TM.getTargetData()->getTypeSize(Type);
339           Align = Log2_64(Align);
340         }
341       }
342     }
343     
344     unsigned Idx;
345     if (CP->isMachineConstantPoolEntry())
346       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
347     else
348       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
349     MI->addConstantPoolIndexOperand(Idx, Offset);
350   } else if (ExternalSymbolSDNode *ES = 
351              dyn_cast<ExternalSymbolSDNode>(Op)) {
352     MI->addExternalSymbolOperand(ES->getSymbol());
353   } else {
354     assert(Op.getValueType() != MVT::Other &&
355            Op.getValueType() != MVT::Flag &&
356            "Chain and flag operands should occur at end of operand list!");
357     unsigned VReg = getVR(Op, VRBaseMap);
358     MI->addRegOperand(VReg, false);
359     
360     // Verify that it is right.
361     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
362     if (II) {
363       const TargetRegisterClass *RC =
364                             getInstrOperandRegClass(MRI, TII, II, IIOpNum);
365       assert(RC && "Don't have operand info for this instruction!");
366       assert(RegMap->getRegClass(VReg) == RC &&
367              "Register class of operand and regclass of use don't agree!");
368     }
369   }
370   
371 }
372
373
374 /// EmitNode - Generate machine code for an node and needed dependencies.
375 ///
376 void ScheduleDAG::EmitNode(SDNode *Node, 
377                            std::map<SDNode*, unsigned> &VRBaseMap) {
378   unsigned VRBase = 0;                 // First virtual register for node
379   
380   // If machine instruction
381   if (Node->isTargetOpcode()) {
382     unsigned Opc = Node->getTargetOpcode();
383     const TargetInstrDescriptor &II = TII->get(Opc);
384
385     unsigned NumResults = CountResults(Node);
386     unsigned NodeOperands = CountOperands(Node);
387     unsigned NumMIOperands = NodeOperands + NumResults;
388 #ifndef NDEBUG
389     assert((unsigned(II.numOperands) == NumMIOperands ||
390             (II.Flags & M_VARIABLE_OPS)) &&
391            "#operands for dag node doesn't match .td file!"); 
392 #endif
393
394     // Create the new machine instruction.
395     MachineInstr *MI = new MachineInstr(II);
396     
397     // Add result register values for things that are defined by this
398     // instruction.
399     
400     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
401     // the CopyToReg'd destination register instead of creating a new vreg.
402     if (NumResults == 1) {
403       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
404            UI != E; ++UI) {
405         SDNode *Use = *UI;
406         if (Use->getOpcode() == ISD::CopyToReg && 
407             Use->getOperand(2).Val == Node) {
408           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
409           if (MRegisterInfo::isVirtualRegister(Reg)) {
410             VRBase = Reg;
411             MI->addRegOperand(Reg, true);
412             break;
413           }
414         }
415       }
416     }
417     
418     // Otherwise, create new virtual registers.
419     if (NumResults && VRBase == 0)
420       VRBase = CreateVirtualRegisters(MRI, MI, NumResults, RegMap, TII, II);
421     
422     // Emit all of the actual operands of this instruction, adding them to the
423     // instruction as appropriate.
424     for (unsigned i = 0; i != NodeOperands; ++i)
425       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
426
427     // Commute node if it has been determined to be profitable.
428     if (CommuteSet.count(Node)) {
429       MachineInstr *NewMI = TII->commuteInstruction(MI);
430       if (NewMI == 0)
431         DOUT << "Sched: COMMUTING FAILED!\n";
432       else {
433         DOUT << "Sched: COMMUTED TO: " << *NewMI;
434         if (MI != NewMI) {
435           delete MI;
436           MI = NewMI;
437         }
438       }
439     }
440
441     // Now that we have emitted all operands, emit this instruction itself.
442     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
443       BB->insert(BB->end(), MI);
444     } else {
445       // Insert this instruction into the end of the basic block, potentially
446       // taking some custom action.
447       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
448     }
449   } else {
450     switch (Node->getOpcode()) {
451     default:
452 #ifndef NDEBUG
453       Node->dump();
454 #endif
455       assert(0 && "This target-independent node should have been selected!");
456     case ISD::EntryToken: // fall thru
457     case ISD::TokenFactor:
458       break;
459     case ISD::CopyToReg: {
460       unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
461       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
462       if (InReg != DestReg)   // Coalesced away the copy?
463         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
464                           RegMap->getRegClass(InReg));
465       break;
466     }
467     case ISD::CopyFromReg: {
468       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
469       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
470         VRBase = SrcReg;  // Just use the input register directly!
471         break;
472       }
473
474       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
475       // the CopyToReg'd destination register instead of creating a new vreg.
476       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
477            UI != E; ++UI) {
478         SDNode *Use = *UI;
479         if (Use->getOpcode() == ISD::CopyToReg && 
480             Use->getOperand(2).Val == Node) {
481           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
482           if (MRegisterInfo::isVirtualRegister(DestReg)) {
483             VRBase = DestReg;
484             break;
485           }
486         }
487       }
488
489       // Figure out the register class to create for the destreg.
490       const TargetRegisterClass *TRC = 0;
491       if (VRBase) {
492         TRC = RegMap->getRegClass(VRBase);
493       } else {
494
495         // Pick the register class of the right type that contains this physreg.
496         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
497              E = MRI->regclass_end(); I != E; ++I)
498           if ((*I)->hasType(Node->getValueType(0)) &&
499               (*I)->contains(SrcReg)) {
500             TRC = *I;
501             break;
502           }
503         assert(TRC && "Couldn't find register class for reg copy!");
504       
505         // Create the reg, emit the copy.
506         VRBase = RegMap->createVirtualRegister(TRC);
507       }
508       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
509       break;
510     }
511     case ISD::INLINEASM: {
512       unsigned NumOps = Node->getNumOperands();
513       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
514         --NumOps;  // Ignore the flag operand.
515       
516       // Create the inline asm machine instruction.
517       MachineInstr *MI =
518         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
519
520       // Add the asm string as an external symbol operand.
521       const char *AsmStr =
522         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
523       MI->addExternalSymbolOperand(AsmStr);
524       
525       // Add all of the operand registers to the instruction.
526       for (unsigned i = 2; i != NumOps;) {
527         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
528         unsigned NumVals = Flags >> 3;
529         
530         MI->addImmOperand(Flags);
531         ++i;  // Skip the ID value.
532         
533         switch (Flags & 7) {
534         default: assert(0 && "Bad flags!");
535         case 1:  // Use of register.
536           for (; NumVals; --NumVals, ++i) {
537             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
538             MI->addRegOperand(Reg, false);
539           }
540           break;
541         case 2:   // Def of register.
542           for (; NumVals; --NumVals, ++i) {
543             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
544             MI->addRegOperand(Reg, true);
545           }
546           break;
547         case 3: { // Immediate.
548           assert(NumVals == 1 && "Unknown immediate value!");
549           if (ConstantSDNode *CS=dyn_cast<ConstantSDNode>(Node->getOperand(i))){
550             MI->addImmOperand(CS->getValue());
551           } else {
552             GlobalAddressSDNode *GA = 
553               cast<GlobalAddressSDNode>(Node->getOperand(i));
554             MI->addGlobalAddressOperand(GA->getGlobal(), GA->getOffset());
555           }
556           ++i;
557           break;
558         }
559         case 4:  // Addressing mode.
560           // The addressing mode has been selected, just add all of the
561           // operands to the machine instruction.
562           for (; NumVals; --NumVals, ++i)
563             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
564           break;
565         }
566       }
567       break;
568     }
569     }
570   }
571
572   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
573   VRBaseMap[Node] = VRBase;
574 }
575
576 void ScheduleDAG::EmitNoop() {
577   TII->insertNoop(*BB, BB->end());
578 }
579
580 /// EmitSchedule - Emit the machine code in scheduled order.
581 void ScheduleDAG::EmitSchedule() {
582   // If this is the first basic block in the function, and if it has live ins
583   // that need to be copied into vregs, emit the copies into the top of the
584   // block before emitting the code for the block.
585   MachineFunction &MF = DAG.getMachineFunction();
586   if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
587     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
588          E = MF.livein_end(); LI != E; ++LI)
589       if (LI->second)
590         MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
591                           LI->first, RegMap->getRegClass(LI->second));
592   }
593   
594   
595   // Finally, emit the code for all of the scheduled instructions.
596   std::map<SDNode*, unsigned> VRBaseMap;
597   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
598     if (SUnit *SU = Sequence[i]) {
599       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
600         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
601       EmitNode(SU->Node, VRBaseMap);
602     } else {
603       // Null SUnit* is a noop.
604       EmitNoop();
605     }
606   }
607 }
608
609 /// dump - dump the schedule.
610 void ScheduleDAG::dumpSchedule() const {
611   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
612     if (SUnit *SU = Sequence[i])
613       SU->dump(&DAG);
614     else
615       cerr << "**** NOOP ****\n";
616   }
617 }
618
619
620 /// Run - perform scheduling.
621 ///
622 MachineBasicBlock *ScheduleDAG::Run() {
623   TII = TM.getInstrInfo();
624   MRI = TM.getRegisterInfo();
625   RegMap = BB->getParent()->getSSARegMap();
626   ConstPool = BB->getParent()->getConstantPool();
627
628   Schedule();
629   return BB;
630 }
631
632 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
633 /// a group of nodes flagged together.
634 void SUnit::dump(const SelectionDAG *G) const {
635   cerr << "SU(" << NodeNum << "): ";
636   Node->dump(G);
637   cerr << "\n";
638   if (FlaggedNodes.size() != 0) {
639     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
640       cerr << "    ";
641       FlaggedNodes[i]->dump(G);
642       cerr << "\n";
643     }
644   }
645 }
646
647 void SUnit::dumpAll(const SelectionDAG *G) const {
648   dump(G);
649
650   cerr << "  # preds left       : " << NumPredsLeft << "\n";
651   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
652   cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
653   cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
654   cerr << "  Latency            : " << Latency << "\n";
655   cerr << "  Depth              : " << Depth << "\n";
656   cerr << "  Height             : " << Height << "\n";
657
658   if (Preds.size() != 0) {
659     cerr << "  Predecessors:\n";
660     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
661          I != E; ++I) {
662       if (I->second)
663         cerr << "   ch  #";
664       else
665         cerr << "   val #";
666       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
667     }
668   }
669   if (Succs.size() != 0) {
670     cerr << "  Successors:\n";
671     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
672          I != E; ++I) {
673       if (I->second)
674         cerr << "   ch  #";
675       else
676         cerr << "   val #";
677       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
678     }
679   }
680   cerr << "\n";
681 }