39285b231a69097b6855a5e278a4055901358dd7
[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;
461       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
462         InReg = R->getReg();
463       else
464         InReg = getVR(Node->getOperand(2), VRBaseMap);
465       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
466       if (InReg != DestReg)   // Coalesced away the copy?
467         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
468                           RegMap->getRegClass(InReg));
469       break;
470     }
471     case ISD::CopyFromReg: {
472       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
473       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
474         VRBase = SrcReg;  // Just use the input register directly!
475         break;
476       }
477
478       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
479       // the CopyToReg'd destination register instead of creating a new vreg.
480       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
481            UI != E; ++UI) {
482         SDNode *Use = *UI;
483         if (Use->getOpcode() == ISD::CopyToReg && 
484             Use->getOperand(2).Val == Node) {
485           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
486           if (MRegisterInfo::isVirtualRegister(DestReg)) {
487             VRBase = DestReg;
488             break;
489           }
490         }
491       }
492
493       // Figure out the register class to create for the destreg.
494       const TargetRegisterClass *TRC = 0;
495       if (VRBase) {
496         TRC = RegMap->getRegClass(VRBase);
497       } else {
498
499         // Pick the register class of the right type that contains this physreg.
500         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
501              E = MRI->regclass_end(); I != E; ++I)
502           if ((*I)->hasType(Node->getValueType(0)) &&
503               (*I)->contains(SrcReg)) {
504             TRC = *I;
505             break;
506           }
507         assert(TRC && "Couldn't find register class for reg copy!");
508       
509         // Create the reg, emit the copy.
510         VRBase = RegMap->createVirtualRegister(TRC);
511       }
512       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
513       break;
514     }
515     case ISD::INLINEASM: {
516       unsigned NumOps = Node->getNumOperands();
517       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
518         --NumOps;  // Ignore the flag operand.
519       
520       // Create the inline asm machine instruction.
521       MachineInstr *MI =
522         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
523
524       // Add the asm string as an external symbol operand.
525       const char *AsmStr =
526         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
527       MI->addExternalSymbolOperand(AsmStr);
528       
529       // Add all of the operand registers to the instruction.
530       for (unsigned i = 2; i != NumOps;) {
531         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
532         unsigned NumVals = Flags >> 3;
533         
534         MI->addImmOperand(Flags);
535         ++i;  // Skip the ID value.
536         
537         switch (Flags & 7) {
538         default: assert(0 && "Bad flags!");
539         case 1:  // Use of register.
540           for (; NumVals; --NumVals, ++i) {
541             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
542             MI->addRegOperand(Reg, false);
543           }
544           break;
545         case 2:   // Def of register.
546           for (; NumVals; --NumVals, ++i) {
547             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
548             MI->addRegOperand(Reg, true);
549           }
550           break;
551         case 3: { // Immediate.
552           assert(NumVals == 1 && "Unknown immediate value!");
553           if (ConstantSDNode *CS=dyn_cast<ConstantSDNode>(Node->getOperand(i))){
554             MI->addImmOperand(CS->getValue());
555           } else {
556             GlobalAddressSDNode *GA = 
557               cast<GlobalAddressSDNode>(Node->getOperand(i));
558             MI->addGlobalAddressOperand(GA->getGlobal(), GA->getOffset());
559           }
560           ++i;
561           break;
562         }
563         case 4:  // Addressing mode.
564           // The addressing mode has been selected, just add all of the
565           // operands to the machine instruction.
566           for (; NumVals; --NumVals, ++i)
567             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
568           break;
569         }
570       }
571       break;
572     }
573     }
574   }
575
576   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
577   VRBaseMap[Node] = VRBase;
578 }
579
580 void ScheduleDAG::EmitNoop() {
581   TII->insertNoop(*BB, BB->end());
582 }
583
584 /// EmitSchedule - Emit the machine code in scheduled order.
585 void ScheduleDAG::EmitSchedule() {
586   // If this is the first basic block in the function, and if it has live ins
587   // that need to be copied into vregs, emit the copies into the top of the
588   // block before emitting the code for the block.
589   MachineFunction &MF = DAG.getMachineFunction();
590   if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
591     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
592          E = MF.livein_end(); LI != E; ++LI)
593       if (LI->second)
594         MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
595                           LI->first, RegMap->getRegClass(LI->second));
596   }
597   
598   
599   // Finally, emit the code for all of the scheduled instructions.
600   std::map<SDNode*, unsigned> VRBaseMap;
601   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
602     if (SUnit *SU = Sequence[i]) {
603       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
604         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
605       EmitNode(SU->Node, VRBaseMap);
606     } else {
607       // Null SUnit* is a noop.
608       EmitNoop();
609     }
610   }
611 }
612
613 /// dump - dump the schedule.
614 void ScheduleDAG::dumpSchedule() const {
615   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
616     if (SUnit *SU = Sequence[i])
617       SU->dump(&DAG);
618     else
619       cerr << "**** NOOP ****\n";
620   }
621 }
622
623
624 /// Run - perform scheduling.
625 ///
626 MachineBasicBlock *ScheduleDAG::Run() {
627   TII = TM.getInstrInfo();
628   MRI = TM.getRegisterInfo();
629   RegMap = BB->getParent()->getSSARegMap();
630   ConstPool = BB->getParent()->getConstantPool();
631
632   Schedule();
633   return BB;
634 }
635
636 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
637 /// a group of nodes flagged together.
638 void SUnit::dump(const SelectionDAG *G) const {
639   cerr << "SU(" << NodeNum << "): ";
640   Node->dump(G);
641   cerr << "\n";
642   if (FlaggedNodes.size() != 0) {
643     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
644       cerr << "    ";
645       FlaggedNodes[i]->dump(G);
646       cerr << "\n";
647     }
648   }
649 }
650
651 void SUnit::dumpAll(const SelectionDAG *G) const {
652   dump(G);
653
654   cerr << "  # preds left       : " << NumPredsLeft << "\n";
655   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
656   cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
657   cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
658   cerr << "  Latency            : " << Latency << "\n";
659   cerr << "  Depth              : " << Depth << "\n";
660   cerr << "  Height             : " << Height << "\n";
661
662   if (Preds.size() != 0) {
663     cerr << "  Predecessors:\n";
664     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
665          I != E; ++I) {
666       if (I->second)
667         cerr << "   ch  #";
668       else
669         cerr << "   val #";
670       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
671     }
672   }
673   if (Succs.size() != 0) {
674     cerr << "  Successors:\n";
675     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
676          I != E; ++I) {
677       if (I->second)
678         cerr << "   ch  #";
679       else
680         cerr << "   val #";
681       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
682     }
683   }
684   cerr << "\n";
685 }