When a node value is only used by a CopyToReg, use the user's dest. This should not...
[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 void ScheduleDAG::CalculateDepths() {
183   std::vector<std::pair<SUnit*, unsigned> > WorkList;
184   for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
185     if (SUnits[i].Preds.size() == 0/* && &SUnits[i] != Entry*/)
186       WorkList.push_back(std::make_pair(&SUnits[i], 0U));
187
188   while (!WorkList.empty()) {
189     SUnit *SU = WorkList.back().first;
190     unsigned Depth = WorkList.back().second;
191     WorkList.pop_back();
192     if (SU->Depth == 0 || Depth > SU->Depth) {
193       SU->Depth = Depth;
194       for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
195            I != E; ++I)
196         WorkList.push_back(std::make_pair(I->first, Depth+1));
197     }
198   }
199 }
200
201 void ScheduleDAG::CalculateHeights() {
202   std::vector<std::pair<SUnit*, unsigned> > WorkList;
203   SUnit *Root = SUnitMap[DAG.getRoot().Val];
204   WorkList.push_back(std::make_pair(Root, 0U));
205
206   while (!WorkList.empty()) {
207     SUnit *SU = WorkList.back().first;
208     unsigned Height = WorkList.back().second;
209     WorkList.pop_back();
210     if (SU->Height == 0 || Height > SU->Height) {
211       SU->Height = Height;
212       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
213            I != E; ++I)
214         WorkList.push_back(std::make_pair(I->first, Height+1));
215     }
216   }
217 }
218
219 /// CountResults - The results of target nodes have register or immediate
220 /// operands first, then an optional chain, and optional flag operands (which do
221 /// not go into the machine instrs.)
222 unsigned ScheduleDAG::CountResults(SDNode *Node) {
223   unsigned N = Node->getNumValues();
224   while (N && Node->getValueType(N - 1) == MVT::Flag)
225     --N;
226   if (N && Node->getValueType(N - 1) == MVT::Other)
227     --N;    // Skip over chain result.
228   return N;
229 }
230
231 /// CountOperands  The inputs to target nodes have any actual inputs first,
232 /// followed by an optional chain operand, then flag operands.  Compute the
233 /// number of actual operands that  will go into the machine instr.
234 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
235   unsigned N = Node->getNumOperands();
236   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
237     --N;
238   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
239     --N; // Ignore chain if it exists.
240   return N;
241 }
242
243 static const TargetRegisterClass *getInstrOperandRegClass(
244         const MRegisterInfo *MRI, 
245         const TargetInstrInfo *TII,
246         const TargetInstrDescriptor *II,
247         unsigned Op) {
248   if (Op >= II->numOperands) {
249     assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
250     return NULL;
251   }
252   const TargetOperandInfo &toi = II->OpInfo[Op];
253   return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
254          ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
255 }
256
257 static void CreateVirtualRegisters(SDNode *Node,
258                                    unsigned NumResults, 
259                                    const MRegisterInfo *MRI,
260                                    MachineInstr *MI,
261                                    SSARegMap *RegMap,
262                                    const TargetInstrInfo *TII,
263                                    const TargetInstrDescriptor &II,
264                                    DenseMap<SDOperand, unsigned> &VRBaseMap) {
265   for (unsigned i = 0; i < NumResults; ++i) {
266     // If the specific node value is only used by a CopyToReg and the dest reg
267     // is a vreg, use the CopyToReg'd destination register instead of creating
268     // a new vreg.
269     unsigned VRBase = 0;
270     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
271          UI != E; ++UI) {
272       SDNode *Use = *UI;
273       if (Use->getOpcode() == ISD::CopyToReg && 
274           Use->getOperand(2).Val == Node &&
275           Use->getOperand(2).ResNo == i) {
276         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
277         if (MRegisterInfo::isVirtualRegister(Reg)) {
278           VRBase = Reg;
279           MI->addRegOperand(Reg, true);
280           break;
281         }
282       }
283     }
284
285     if (VRBase == 0) {
286       // Create the result registers for this node and add the result regs to
287       // the machine instruction.
288       const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
289       assert(RC && "Isn't a register operand!");
290       VRBase = RegMap->createVirtualRegister(RC);
291       MI->addRegOperand(VRBase, true);
292     }
293
294     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
295     assert(isNew && "Node emitted out of order - early");
296   }
297 }
298
299 /// getVR - Return the virtual register corresponding to the specified result
300 /// of the specified node.
301 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
302   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
303   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
304   return I->second;
305 }
306
307
308 /// AddOperand - Add the specified operand to the specified machine instr.  II
309 /// specifies the instruction information for the node, and IIOpNum is the
310 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
311 /// assertions only.
312 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
313                              unsigned IIOpNum,
314                              const TargetInstrDescriptor *II,
315                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
316   if (Op.isTargetOpcode()) {
317     // Note that this case is redundant with the final else block, but we
318     // include it because it is the most common and it makes the logic
319     // simpler here.
320     assert(Op.getValueType() != MVT::Other &&
321            Op.getValueType() != MVT::Flag &&
322            "Chain and flag operands should occur at end of operand list!");
323     
324     // Get/emit the operand.
325     unsigned VReg = getVR(Op, VRBaseMap);
326     MI->addRegOperand(VReg, false);
327     
328     // Verify that it is right.
329     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
330     if (II) {
331       const TargetRegisterClass *RC =
332                           getInstrOperandRegClass(MRI, TII, II, IIOpNum);
333       assert(RC && "Don't have operand info for this instruction!");
334       const TargetRegisterClass *VRC = RegMap->getRegClass(VReg);
335       if (VRC != RC) {
336         cerr << "Register class of operand and regclass of use don't agree!\n";
337 #ifndef NDEBUG
338         cerr << "Operand = " << IIOpNum << "\n";
339         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
340         cerr << "MI = "; MI->print(cerr);
341         cerr << "VReg = " << VReg << "\n";
342         cerr << "VReg RegClass     size = " << VRC->getSize()
343              << ", align = " << VRC->getAlignment() << "\n";
344         cerr << "Expected RegClass size = " << RC->getSize()
345              << ", align = " << RC->getAlignment() << "\n";
346 #endif
347         cerr << "Fatal error, aborting.\n";
348         abort();
349       }
350     }
351   } else if (ConstantSDNode *C =
352              dyn_cast<ConstantSDNode>(Op)) {
353     MI->addImmOperand(C->getValue());
354   } else if (RegisterSDNode *R =
355              dyn_cast<RegisterSDNode>(Op)) {
356     MI->addRegOperand(R->getReg(), false);
357   } else if (GlobalAddressSDNode *TGA =
358              dyn_cast<GlobalAddressSDNode>(Op)) {
359     MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
360   } else if (BasicBlockSDNode *BB =
361              dyn_cast<BasicBlockSDNode>(Op)) {
362     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
363   } else if (FrameIndexSDNode *FI =
364              dyn_cast<FrameIndexSDNode>(Op)) {
365     MI->addFrameIndexOperand(FI->getIndex());
366   } else if (JumpTableSDNode *JT =
367              dyn_cast<JumpTableSDNode>(Op)) {
368     MI->addJumpTableIndexOperand(JT->getIndex());
369   } else if (ConstantPoolSDNode *CP = 
370              dyn_cast<ConstantPoolSDNode>(Op)) {
371     int Offset = CP->getOffset();
372     unsigned Align = CP->getAlignment();
373     const Type *Type = CP->getType();
374     // MachineConstantPool wants an explicit alignment.
375     if (Align == 0) {
376       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
377       if (Align == 0) {
378         // Alignment of vector types.  FIXME!
379         Align = TM.getTargetData()->getTypeSize(Type);
380         Align = Log2_64(Align);
381       }
382     }
383     
384     unsigned Idx;
385     if (CP->isMachineConstantPoolEntry())
386       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
387     else
388       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
389     MI->addConstantPoolIndexOperand(Idx, Offset);
390   } else if (ExternalSymbolSDNode *ES = 
391              dyn_cast<ExternalSymbolSDNode>(Op)) {
392     MI->addExternalSymbolOperand(ES->getSymbol());
393   } else {
394     assert(Op.getValueType() != MVT::Other &&
395            Op.getValueType() != MVT::Flag &&
396            "Chain and flag operands should occur at end of operand list!");
397     unsigned VReg = getVR(Op, VRBaseMap);
398     MI->addRegOperand(VReg, false);
399     
400     // Verify that it is right.
401     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
402     if (II) {
403       const TargetRegisterClass *RC =
404                             getInstrOperandRegClass(MRI, TII, II, IIOpNum);
405       assert(RC && "Don't have operand info for this instruction!");
406       assert(RegMap->getRegClass(VReg) == RC &&
407              "Register class of operand and regclass of use don't agree!");
408     }
409   }
410   
411 }
412
413 // Returns the Register Class of a physical register
414 static const TargetRegisterClass *getPhysicalRegisterRegClass(
415         const MRegisterInfo *MRI,
416         MVT::ValueType VT,
417         unsigned reg) {
418   assert(MRegisterInfo::isPhysicalRegister(reg) &&
419          "reg must be a physical register");
420   // Pick the register class of the right type that contains this physreg.
421   for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
422          E = MRI->regclass_end(); I != E; ++I)
423     if ((*I)->hasType(VT) && (*I)->contains(reg))
424       return *I;
425   assert(false && "Couldn't find the register class");
426   return 0;
427 }
428
429 /// EmitNode - Generate machine code for an node and needed dependencies.
430 ///
431 void ScheduleDAG::EmitNode(SDNode *Node, 
432                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
433   // If machine instruction
434   if (Node->isTargetOpcode()) {
435     unsigned Opc = Node->getTargetOpcode();
436     const TargetInstrDescriptor &II = TII->get(Opc);
437
438     unsigned NumResults = CountResults(Node);
439     unsigned NodeOperands = CountOperands(Node);
440     unsigned NumMIOperands = NodeOperands + NumResults;
441 #ifndef NDEBUG
442     assert((unsigned(II.numOperands) == NumMIOperands ||
443             (II.Flags & M_VARIABLE_OPS)) &&
444            "#operands for dag node doesn't match .td file!"); 
445 #endif
446
447     // Create the new machine instruction.
448     MachineInstr *MI = new MachineInstr(II);
449     
450     // Add result register values for things that are defined by this
451     // instruction.
452     if (NumResults)
453       CreateVirtualRegisters(Node, NumResults, MRI, MI, RegMap,
454                              TII, II, VRBaseMap);
455     
456     // Emit all of the actual operands of this instruction, adding them to the
457     // instruction as appropriate.
458     for (unsigned i = 0; i != NodeOperands; ++i)
459       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
460
461     // Commute node if it has been determined to be profitable.
462     if (CommuteSet.count(Node)) {
463       MachineInstr *NewMI = TII->commuteInstruction(MI);
464       if (NewMI == 0)
465         DOUT << "Sched: COMMUTING FAILED!\n";
466       else {
467         DOUT << "Sched: COMMUTED TO: " << *NewMI;
468         if (MI != NewMI) {
469           delete MI;
470           MI = NewMI;
471         }
472       }
473     }
474
475     // Now that we have emitted all operands, emit this instruction itself.
476     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
477       BB->insert(BB->end(), MI);
478     } else {
479       // Insert this instruction into the end of the basic block, potentially
480       // taking some custom action.
481       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
482     }
483   } else {
484     switch (Node->getOpcode()) {
485     default:
486 #ifndef NDEBUG
487       Node->dump(&DAG);
488 #endif
489       assert(0 && "This target-independent node should have been selected!");
490     case ISD::EntryToken: // fall thru
491     case ISD::TokenFactor:
492     case ISD::LABEL:
493       break;
494     case ISD::CopyToReg: {
495       unsigned InReg;
496       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
497         InReg = R->getReg();
498       else
499         InReg = getVR(Node->getOperand(2), VRBaseMap);
500       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
501       if (InReg != DestReg)  {// Coalesced away the copy?
502         const TargetRegisterClass *TRC = 0;
503         // Get the target register class
504         if (MRegisterInfo::isVirtualRegister(InReg))
505           TRC = RegMap->getRegClass(InReg);
506         else
507           TRC = getPhysicalRegisterRegClass(MRI,
508                                             Node->getOperand(2).getValueType(),
509                                             InReg);
510         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC);
511       }
512       break;
513     }
514     case ISD::CopyFromReg: {
515       unsigned VRBase = 0;
516       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
517       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
518         // Just use the input register directly!
519         bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0),SrcReg));
520         assert(isNew && "Node emitted out of order - early");
521         break;
522       }
523
524       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
525       // the CopyToReg'd destination register instead of creating a new vreg.
526       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
527            UI != E; ++UI) {
528         SDNode *Use = *UI;
529         if (Use->getOpcode() == ISD::CopyToReg && 
530             Use->getOperand(2).Val == Node) {
531           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
532           if (MRegisterInfo::isVirtualRegister(DestReg)) {
533             VRBase = DestReg;
534             break;
535           }
536         }
537       }
538
539       // Figure out the register class to create for the destreg.
540       const TargetRegisterClass *TRC = 0;
541       if (VRBase) {
542         TRC = RegMap->getRegClass(VRBase);
543       } else {
544         TRC = getPhysicalRegisterRegClass(MRI, Node->getValueType(0), SrcReg);
545
546         // Create the reg, emit the copy.
547         VRBase = RegMap->createVirtualRegister(TRC);
548       }
549       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
550
551       bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
552       assert(isNew && "Node emitted out of order - early");
553       break;
554     }
555     case ISD::INLINEASM: {
556       unsigned NumOps = Node->getNumOperands();
557       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
558         --NumOps;  // Ignore the flag operand.
559       
560       // Create the inline asm machine instruction.
561       MachineInstr *MI =
562         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
563
564       // Add the asm string as an external symbol operand.
565       const char *AsmStr =
566         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
567       MI->addExternalSymbolOperand(AsmStr);
568       
569       // Add all of the operand registers to the instruction.
570       for (unsigned i = 2; i != NumOps;) {
571         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
572         unsigned NumVals = Flags >> 3;
573         
574         MI->addImmOperand(Flags);
575         ++i;  // Skip the ID value.
576         
577         switch (Flags & 7) {
578         default: assert(0 && "Bad flags!");
579         case 1:  // Use of register.
580           for (; NumVals; --NumVals, ++i) {
581             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
582             MI->addRegOperand(Reg, false);
583           }
584           break;
585         case 2:   // Def of register.
586           for (; NumVals; --NumVals, ++i) {
587             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
588             MI->addRegOperand(Reg, true);
589           }
590           break;
591         case 3: { // Immediate.
592           assert(NumVals == 1 && "Unknown immediate value!");
593           if (ConstantSDNode *CS=dyn_cast<ConstantSDNode>(Node->getOperand(i))){
594             MI->addImmOperand(CS->getValue());
595           } else {
596             GlobalAddressSDNode *GA = 
597               cast<GlobalAddressSDNode>(Node->getOperand(i));
598             MI->addGlobalAddressOperand(GA->getGlobal(), GA->getOffset());
599           }
600           ++i;
601           break;
602         }
603         case 4:  // Addressing mode.
604           // The addressing mode has been selected, just add all of the
605           // operands to the machine instruction.
606           for (; NumVals; --NumVals, ++i)
607             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
608           break;
609         }
610       }
611       break;
612     }
613     }
614   }
615 }
616
617 void ScheduleDAG::EmitNoop() {
618   TII->insertNoop(*BB, BB->end());
619 }
620
621 /// EmitSchedule - Emit the machine code in scheduled order.
622 void ScheduleDAG::EmitSchedule() {
623   // If this is the first basic block in the function, and if it has live ins
624   // that need to be copied into vregs, emit the copies into the top of the
625   // block before emitting the code for the block.
626   MachineFunction &MF = DAG.getMachineFunction();
627   if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
628     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
629          E = MF.livein_end(); LI != E; ++LI)
630       if (LI->second)
631         MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
632                           LI->first, RegMap->getRegClass(LI->second));
633   }
634   
635   
636   // Finally, emit the code for all of the scheduled instructions.
637   DenseMap<SDOperand, unsigned> VRBaseMap;
638   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
639     if (SUnit *SU = Sequence[i]) {
640       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
641         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
642       EmitNode(SU->Node, VRBaseMap);
643     } else {
644       // Null SUnit* is a noop.
645       EmitNoop();
646     }
647   }
648 }
649
650 /// dump - dump the schedule.
651 void ScheduleDAG::dumpSchedule() const {
652   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
653     if (SUnit *SU = Sequence[i])
654       SU->dump(&DAG);
655     else
656       cerr << "**** NOOP ****\n";
657   }
658 }
659
660
661 /// Run - perform scheduling.
662 ///
663 MachineBasicBlock *ScheduleDAG::Run() {
664   TII = TM.getInstrInfo();
665   MRI = TM.getRegisterInfo();
666   RegMap = BB->getParent()->getSSARegMap();
667   ConstPool = BB->getParent()->getConstantPool();
668
669   Schedule();
670   return BB;
671 }
672
673 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
674 /// a group of nodes flagged together.
675 void SUnit::dump(const SelectionDAG *G) const {
676   cerr << "SU(" << NodeNum << "): ";
677   Node->dump(G);
678   cerr << "\n";
679   if (FlaggedNodes.size() != 0) {
680     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
681       cerr << "    ";
682       FlaggedNodes[i]->dump(G);
683       cerr << "\n";
684     }
685   }
686 }
687
688 void SUnit::dumpAll(const SelectionDAG *G) const {
689   dump(G);
690
691   cerr << "  # preds left       : " << NumPredsLeft << "\n";
692   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
693   cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
694   cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
695   cerr << "  Latency            : " << Latency << "\n";
696   cerr << "  Depth              : " << Depth << "\n";
697   cerr << "  Height             : " << Height << "\n";
698
699   if (Preds.size() != 0) {
700     cerr << "  Predecessors:\n";
701     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
702          I != E; ++I) {
703       if (I->second)
704         cerr << "   ch  #";
705       else
706         cerr << "   val #";
707       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
708     }
709   }
710   if (Succs.size() != 0) {
711     cerr << "  Successors:\n";
712     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
713          I != E; ++I) {
714       if (I->second)
715         cerr << "   ch  #";
716       else
717         cerr << "   val #";
718       cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
719     }
720   }
721   cerr << "\n";
722 }