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