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