Rename MachineInstr::getInstrDescriptor -> getDesc(), which reflects
[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 is distributed under the University of Illinois Open Source
6 // 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 "pre-RA-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/MachineRegisterInfo.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 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
31                          const TargetMachine &tm)
32   : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
33     TII = TM.getInstrInfo();
34     MRI = TM.getRegisterInfo();
35     ConstPool = BB->getParent()->getConstantPool();
36 }
37
38 /// CheckForPhysRegDependency - Check if the dependency between def and use of
39 /// a specified operand is a physical register dependency. If so, returns the
40 /// register and the cost of copying the register.
41 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
42                                       const MRegisterInfo *MRI, 
43                                       const TargetInstrInfo *TII,
44                                       unsigned &PhysReg, int &Cost) {
45   if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
46     return;
47
48   unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
49   if (MRegisterInfo::isVirtualRegister(Reg))
50     return;
51
52   unsigned ResNo = Use->getOperand(2).ResNo;
53   if (Def->isTargetOpcode()) {
54     const TargetInstrDescriptor &II = TII->get(Def->getTargetOpcode());
55     if (ResNo >= II.numDefs &&
56         II.ImplicitDefs[ResNo - II.numDefs] == Reg) {
57       PhysReg = Reg;
58       const TargetRegisterClass *RC =
59         MRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
60       Cost = RC->getCopyCost();
61     }
62   }
63 }
64
65 SUnit *ScheduleDAG::Clone(SUnit *Old) {
66   SUnit *SU = NewSUnit(Old->Node);
67   for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
68     SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
69   SU->InstanceNo = SUnitMap[Old->Node].size();
70   SU->Latency = Old->Latency;
71   SU->isTwoAddress = Old->isTwoAddress;
72   SU->isCommutable = Old->isCommutable;
73   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
74   SUnitMap[Old->Node].push_back(SU);
75   return SU;
76 }
77
78
79 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
80 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
81 /// together nodes with a single SUnit.
82 void ScheduleDAG::BuildSchedUnits() {
83   // Reserve entries in the vector for each of the SUnits we are creating.  This
84   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
85   // invalidated.
86   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
87   
88   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
89        E = DAG.allnodes_end(); NI != E; ++NI) {
90     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
91       continue;
92     
93     // If this node has already been processed, stop now.
94     if (SUnitMap[NI].size()) continue;
95     
96     SUnit *NodeSUnit = NewSUnit(NI);
97     
98     // See if anything is flagged to this node, if so, add them to flagged
99     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
100     // are required the be the last operand and result of a node.
101     
102     // Scan up, adding flagged preds to FlaggedNodes.
103     SDNode *N = NI;
104     if (N->getNumOperands() &&
105         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
106       do {
107         N = N->getOperand(N->getNumOperands()-1).Val;
108         NodeSUnit->FlaggedNodes.push_back(N);
109         SUnitMap[N].push_back(NodeSUnit);
110       } while (N->getNumOperands() &&
111                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
112       std::reverse(NodeSUnit->FlaggedNodes.begin(),
113                    NodeSUnit->FlaggedNodes.end());
114     }
115     
116     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
117     // have a user of the flag operand.
118     N = NI;
119     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
120       SDOperand FlagVal(N, N->getNumValues()-1);
121       
122       // There are either zero or one users of the Flag result.
123       bool HasFlagUse = false;
124       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
125            UI != E; ++UI)
126         if (FlagVal.isOperand(*UI)) {
127           HasFlagUse = true;
128           NodeSUnit->FlaggedNodes.push_back(N);
129           SUnitMap[N].push_back(NodeSUnit);
130           N = *UI;
131           break;
132         }
133       if (!HasFlagUse) break;
134     }
135     
136     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
137     // Update the SUnit
138     NodeSUnit->Node = N;
139     SUnitMap[N].push_back(NodeSUnit);
140
141     ComputeLatency(NodeSUnit);
142   }
143   
144   // Pass 2: add the preds, succs, etc.
145   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
146     SUnit *SU = &SUnits[su];
147     SDNode *MainNode = SU->Node;
148     
149     if (MainNode->isTargetOpcode()) {
150       unsigned Opc = MainNode->getTargetOpcode();
151       const TargetInstrDescriptor &TID = TII->get(Opc);
152       for (unsigned i = 0; i != TID.numOperands; ++i) {
153         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
154           SU->isTwoAddress = true;
155           break;
156         }
157       }
158       if (TID.Flags & M_COMMUTABLE)
159         SU->isCommutable = true;
160     }
161     
162     // Find all predecessors and successors of the group.
163     // Temporarily add N to make code simpler.
164     SU->FlaggedNodes.push_back(MainNode);
165     
166     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
167       SDNode *N = SU->FlaggedNodes[n];
168       if (N->isTargetOpcode() &&
169           TII->getImplicitDefs(N->getTargetOpcode()) &&
170           CountResults(N) > (unsigned)TII->getNumDefs(N->getTargetOpcode()))
171         SU->hasPhysRegDefs = true;
172       
173       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
174         SDNode *OpN = N->getOperand(i).Val;
175         if (isPassiveNode(OpN)) continue;   // Not scheduled.
176         SUnit *OpSU = SUnitMap[OpN].front();
177         assert(OpSU && "Node has no SUnit!");
178         if (OpSU == SU) continue;           // In the same group.
179
180         MVT::ValueType OpVT = N->getOperand(i).getValueType();
181         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
182         bool isChain = OpVT == MVT::Other;
183
184         unsigned PhysReg = 0;
185         int Cost = 1;
186         // Determine if this is a physical register dependency.
187         CheckForPhysRegDependency(OpN, N, i, MRI, TII, PhysReg, Cost);
188         SU->addPred(OpSU, isChain, false, PhysReg, Cost);
189       }
190     }
191     
192     // Remove MainNode from FlaggedNodes again.
193     SU->FlaggedNodes.pop_back();
194   }
195   
196   return;
197 }
198
199 void ScheduleDAG::ComputeLatency(SUnit *SU) {
200   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
201   
202   // Compute the latency for the node.  We use the sum of the latencies for
203   // all nodes flagged together into this SUnit.
204   if (InstrItins.isEmpty()) {
205     // No latency information.
206     SU->Latency = 1;
207   } else {
208     SU->Latency = 0;
209     if (SU->Node->isTargetOpcode()) {
210       unsigned SchedClass = TII->getSchedClass(SU->Node->getTargetOpcode());
211       InstrStage *S = InstrItins.begin(SchedClass);
212       InstrStage *E = InstrItins.end(SchedClass);
213       for (; S != E; ++S)
214         SU->Latency += S->Cycles;
215     }
216     for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
217       SDNode *FNode = SU->FlaggedNodes[i];
218       if (FNode->isTargetOpcode()) {
219         unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
220         InstrStage *S = InstrItins.begin(SchedClass);
221         InstrStage *E = InstrItins.end(SchedClass);
222         for (; S != E; ++S)
223           SU->Latency += S->Cycles;
224       }
225     }
226   }
227 }
228
229 void ScheduleDAG::CalculateDepths() {
230   std::vector<std::pair<SUnit*, unsigned> > WorkList;
231   for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
232     if (SUnits[i].Preds.size() == 0)
233       WorkList.push_back(std::make_pair(&SUnits[i], 0U));
234
235   while (!WorkList.empty()) {
236     SUnit *SU = WorkList.back().first;
237     unsigned Depth = WorkList.back().second;
238     WorkList.pop_back();
239     if (SU->Depth == 0 || Depth > SU->Depth) {
240       SU->Depth = Depth;
241       for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
242            I != E; ++I)
243         WorkList.push_back(std::make_pair(I->Dep, Depth+1));
244     }
245   }
246 }
247
248 void ScheduleDAG::CalculateHeights() {
249   std::vector<std::pair<SUnit*, unsigned> > WorkList;
250   SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
251   WorkList.push_back(std::make_pair(Root, 0U));
252
253   while (!WorkList.empty()) {
254     SUnit *SU = WorkList.back().first;
255     unsigned Height = WorkList.back().second;
256     WorkList.pop_back();
257     if (SU->Height == 0 || Height > SU->Height) {
258       SU->Height = Height;
259       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
260            I != E; ++I)
261         WorkList.push_back(std::make_pair(I->Dep, Height+1));
262     }
263   }
264 }
265
266 /// CountResults - The results of target nodes have register or immediate
267 /// operands first, then an optional chain, and optional flag operands (which do
268 /// not go into the machine instrs.)
269 unsigned ScheduleDAG::CountResults(SDNode *Node) {
270   unsigned N = Node->getNumValues();
271   while (N && Node->getValueType(N - 1) == MVT::Flag)
272     --N;
273   if (N && Node->getValueType(N - 1) == MVT::Other)
274     --N;    // Skip over chain result.
275   return N;
276 }
277
278 /// CountOperands  The inputs to target nodes have any actual inputs first,
279 /// followed by an optional chain operand, then flag operands.  Compute the
280 /// number of actual operands that  will go into the machine instr.
281 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
282   unsigned N = Node->getNumOperands();
283   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
284     --N;
285   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
286     --N; // Ignore chain if it exists.
287   return N;
288 }
289
290 static const TargetRegisterClass *getInstrOperandRegClass(
291         const MRegisterInfo *MRI, 
292         const TargetInstrInfo *TII,
293         const TargetInstrDescriptor *II,
294         unsigned Op) {
295   if (Op >= II->numOperands) {
296     assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
297     return NULL;
298   }
299   const TargetOperandInfo &toi = II->OpInfo[Op];
300   return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
301          ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
302 }
303
304 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
305                                   unsigned InstanceNo, unsigned SrcReg,
306                                   DenseMap<SDOperand, unsigned> &VRBaseMap) {
307   unsigned VRBase = 0;
308   if (MRegisterInfo::isVirtualRegister(SrcReg)) {
309     // Just use the input register directly!
310     if (InstanceNo > 0)
311       VRBaseMap.erase(SDOperand(Node, ResNo));
312     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
313     assert(isNew && "Node emitted out of order - early");
314     return;
315   }
316
317   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
318   // the CopyToReg'd destination register instead of creating a new vreg.
319   bool MatchReg = true;
320   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
321        UI != E; ++UI) {
322     SDNode *Use = *UI;
323     bool Match = true;
324     if (Use->getOpcode() == ISD::CopyToReg && 
325         Use->getOperand(2).Val == Node &&
326         Use->getOperand(2).ResNo == ResNo) {
327       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
328       if (MRegisterInfo::isVirtualRegister(DestReg)) {
329         VRBase = DestReg;
330         Match = false;
331       } else if (DestReg != SrcReg)
332         Match = false;
333     } else {
334       for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
335         SDOperand Op = Use->getOperand(i);
336         if (Op.Val != Node || Op.ResNo != ResNo)
337           continue;
338         MVT::ValueType VT = Node->getValueType(Op.ResNo);
339         if (VT != MVT::Other && VT != MVT::Flag)
340           Match = false;
341       }
342     }
343     MatchReg &= Match;
344     if (VRBase)
345       break;
346   }
347
348   const TargetRegisterClass *TRC = 0;
349   // Figure out the register class to create for the destreg.
350   if (VRBase)
351     TRC = RegInfo.getRegClass(VRBase);
352   else
353     TRC = MRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
354     
355   // If all uses are reading from the src physical register and copying the
356   // register is either impossible or very expensive, then don't create a copy.
357   if (MatchReg && TRC->getCopyCost() < 0) {
358     VRBase = SrcReg;
359   } else {
360     // Create the reg, emit the copy.
361     VRBase = RegInfo.createVirtualRegister(TRC);
362     TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
363   }
364
365   if (InstanceNo > 0)
366     VRBaseMap.erase(SDOperand(Node, ResNo));
367   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
368   assert(isNew && "Node emitted out of order - early");
369 }
370
371 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
372                                          MachineInstr *MI,
373                                          const TargetInstrDescriptor &II,
374                                      DenseMap<SDOperand, unsigned> &VRBaseMap) {
375   for (unsigned i = 0; i < II.numDefs; ++i) {
376     // If the specific node value is only used by a CopyToReg and the dest reg
377     // is a vreg, use the CopyToReg'd destination register instead of creating
378     // a new vreg.
379     unsigned VRBase = 0;
380     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
381          UI != E; ++UI) {
382       SDNode *Use = *UI;
383       if (Use->getOpcode() == ISD::CopyToReg && 
384           Use->getOperand(2).Val == Node &&
385           Use->getOperand(2).ResNo == i) {
386         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
387         if (MRegisterInfo::isVirtualRegister(Reg)) {
388           VRBase = Reg;
389           MI->addOperand(MachineOperand::CreateReg(Reg, true));
390           break;
391         }
392       }
393     }
394
395     // Create the result registers for this node and add the result regs to
396     // the machine instruction.
397     if (VRBase == 0) {
398       const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
399       assert(RC && "Isn't a register operand!");
400       VRBase = RegInfo.createVirtualRegister(RC);
401       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
402     }
403
404     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
405     assert(isNew && "Node emitted out of order - early");
406   }
407 }
408
409 /// getVR - Return the virtual register corresponding to the specified result
410 /// of the specified node.
411 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
412   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
413   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
414   return I->second;
415 }
416
417
418 /// AddOperand - Add the specified operand to the specified machine instr.  II
419 /// specifies the instruction information for the node, and IIOpNum is the
420 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
421 /// assertions only.
422 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
423                              unsigned IIOpNum,
424                              const TargetInstrDescriptor *II,
425                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
426   if (Op.isTargetOpcode()) {
427     // Note that this case is redundant with the final else block, but we
428     // include it because it is the most common and it makes the logic
429     // simpler here.
430     assert(Op.getValueType() != MVT::Other &&
431            Op.getValueType() != MVT::Flag &&
432            "Chain and flag operands should occur at end of operand list!");
433     
434     // Get/emit the operand.
435     unsigned VReg = getVR(Op, VRBaseMap);
436     const TargetInstrDescriptor *TID = MI->getDesc();
437     bool isOptDef = (IIOpNum < TID->numOperands)
438       ? (TID->OpInfo[IIOpNum].Flags & M_OPTIONAL_DEF_OPERAND) : false;
439     MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
440     
441     // Verify that it is right.
442     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
443     if (II) {
444       const TargetRegisterClass *RC =
445                           getInstrOperandRegClass(MRI, TII, II, IIOpNum);
446       assert(RC && "Don't have operand info for this instruction!");
447       const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
448       if (VRC != RC) {
449         cerr << "Register class of operand and regclass of use don't agree!\n";
450 #ifndef NDEBUG
451         cerr << "Operand = " << IIOpNum << "\n";
452         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
453         cerr << "MI = "; MI->print(cerr);
454         cerr << "VReg = " << VReg << "\n";
455         cerr << "VReg RegClass     size = " << VRC->getSize()
456              << ", align = " << VRC->getAlignment() << "\n";
457         cerr << "Expected RegClass size = " << RC->getSize()
458              << ", align = " << RC->getAlignment() << "\n";
459 #endif
460         cerr << "Fatal error, aborting.\n";
461         abort();
462       }
463     }
464   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
465     MI->addOperand(MachineOperand::CreateImm(C->getValue()));
466   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
467     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
468   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
469     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
470   } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
471     MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
472   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
473     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
474   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
475     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
476   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
477     int Offset = CP->getOffset();
478     unsigned Align = CP->getAlignment();
479     const Type *Type = CP->getType();
480     // MachineConstantPool wants an explicit alignment.
481     if (Align == 0) {
482       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
483       if (Align == 0) {
484         // Alignment of vector types.  FIXME!
485         Align = TM.getTargetData()->getABITypeSize(Type);
486         Align = Log2_64(Align);
487       }
488     }
489     
490     unsigned Idx;
491     if (CP->isMachineConstantPoolEntry())
492       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
493     else
494       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
495     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
496   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
497     MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
498   } else {
499     assert(Op.getValueType() != MVT::Other &&
500            Op.getValueType() != MVT::Flag &&
501            "Chain and flag operands should occur at end of operand list!");
502     unsigned VReg = getVR(Op, VRBaseMap);
503     MI->addOperand(MachineOperand::CreateReg(VReg, false));
504     
505     // Verify that it is right.
506     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
507     if (II) {
508       const TargetRegisterClass *RC =
509                             getInstrOperandRegClass(MRI, TII, II, IIOpNum);
510       assert(RC && "Don't have operand info for this instruction!");
511       assert(RegInfo.getRegClass(VReg) == RC &&
512              "Register class of operand and regclass of use don't agree!");
513     }
514   }
515   
516 }
517
518 // Returns the Register Class of a subregister
519 static const TargetRegisterClass *getSubRegisterRegClass(
520         const TargetRegisterClass *TRC,
521         unsigned SubIdx) {
522   // Pick the register class of the subregister
523   MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
524   assert(I < TRC->subregclasses_end() && 
525          "Invalid subregister index for register class");
526   return *I;
527 }
528
529 static const TargetRegisterClass *getSuperregRegisterClass(
530         const TargetRegisterClass *TRC,
531         unsigned SubIdx,
532         MVT::ValueType VT) {
533   // Pick the register class of the superegister for this type
534   for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
535          E = TRC->superregclasses_end(); I != E; ++I)
536     if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
537       return *I;
538   assert(false && "Couldn't find the register class");
539   return 0;
540 }
541
542 /// EmitSubregNode - Generate machine code for subreg nodes.
543 ///
544 void ScheduleDAG::EmitSubregNode(SDNode *Node, 
545                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
546   unsigned VRBase = 0;
547   unsigned Opc = Node->getTargetOpcode();
548   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
549     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
550     // the CopyToReg'd destination register instead of creating a new vreg.
551     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
552          UI != E; ++UI) {
553       SDNode *Use = *UI;
554       if (Use->getOpcode() == ISD::CopyToReg && 
555           Use->getOperand(2).Val == Node) {
556         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
557         if (MRegisterInfo::isVirtualRegister(DestReg)) {
558           VRBase = DestReg;
559           break;
560         }
561       }
562     }
563     
564     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
565     
566     // TODO: If the node is a use of a CopyFromReg from a physical register
567     // fold the extract into the copy now
568
569     // Create the extract_subreg machine instruction.
570     MachineInstr *MI =
571       new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
572
573     // Figure out the register class to create for the destreg.
574     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
575     const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
576     const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
577
578     if (VRBase) {
579       // Grab the destination register
580       const TargetRegisterClass *DRC = 0;
581       DRC = RegInfo.getRegClass(VRBase);
582       assert(SRC == DRC && 
583              "Source subregister and destination must have the same class");
584     } else {
585       // Create the reg
586       VRBase = RegInfo.createVirtualRegister(SRC);
587     }
588     
589     // Add def, source, and subreg index
590     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
591     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
592     MI->addOperand(MachineOperand::CreateImm(SubIdx));
593     
594   } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
595     assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
596             "Malformed insert_subreg node");
597     bool isUndefInput = (Node->getNumOperands() == 2);
598     unsigned SubReg = 0;
599     unsigned SubIdx = 0;
600     
601     if (isUndefInput) {
602       SubReg = getVR(Node->getOperand(0), VRBaseMap);
603       SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
604     } else {
605       SubReg = getVR(Node->getOperand(1), VRBaseMap);
606       SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
607     }
608     
609     // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
610     // to allow coalescing in the allocator
611           
612     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
613     // the CopyToReg'd destination register instead of creating a new vreg.
614     // If the CopyToReg'd destination register is physical, then fold the
615     // insert into the copy
616     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
617          UI != E; ++UI) {
618       SDNode *Use = *UI;
619       if (Use->getOpcode() == ISD::CopyToReg && 
620           Use->getOperand(2).Val == Node) {
621         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
622         if (MRegisterInfo::isVirtualRegister(DestReg)) {
623           VRBase = DestReg;
624           break;
625         }
626       }
627     }
628     
629     // Create the insert_subreg machine instruction.
630     MachineInstr *MI =
631       new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
632       
633     // Figure out the register class to create for the destreg.
634     const TargetRegisterClass *TRC = 0;
635     if (VRBase) {
636       TRC = RegInfo.getRegClass(VRBase);
637     } else {
638       TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx, 
639                                      Node->getValueType(0));
640       assert(TRC && "Couldn't determine register class for insert_subreg");
641       VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
642     }
643     
644     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
645     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
646     if (!isUndefInput)
647       AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
648     MI->addOperand(MachineOperand::CreateImm(SubIdx));
649   } else
650     assert(0 && "Node is not a subreg insert or extract");
651      
652   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
653   assert(isNew && "Node emitted out of order - early");
654 }
655
656 /// EmitNode - Generate machine code for an node and needed dependencies.
657 ///
658 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
659                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
660   // If machine instruction
661   if (Node->isTargetOpcode()) {
662     unsigned Opc = Node->getTargetOpcode();
663     
664     // Handle subreg insert/extract specially
665     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
666         Opc == TargetInstrInfo::INSERT_SUBREG) {
667       EmitSubregNode(Node, VRBaseMap);
668       return;
669     }
670     
671     const TargetInstrDescriptor &II = TII->get(Opc);
672
673     unsigned NumResults = CountResults(Node);
674     unsigned NodeOperands = CountOperands(Node);
675     unsigned NumMIOperands = NodeOperands + NumResults;
676     bool     HasPhysRegOuts = (NumResults > II.numDefs) && II.ImplicitDefs;
677 #ifndef NDEBUG
678     assert((unsigned(II.numOperands) == NumMIOperands ||
679             HasPhysRegOuts || (II.Flags & M_VARIABLE_OPS)) &&
680            "#operands for dag node doesn't match .td file!"); 
681 #endif
682
683     // Create the new machine instruction.
684     MachineInstr *MI = new MachineInstr(II);
685     
686     // Add result register values for things that are defined by this
687     // instruction.
688     if (NumResults)
689       CreateVirtualRegisters(Node, MI, II, VRBaseMap);
690     
691     // Emit all of the actual operands of this instruction, adding them to the
692     // instruction as appropriate.
693     for (unsigned i = 0; i != NodeOperands; ++i)
694       AddOperand(MI, Node->getOperand(i), i+II.numDefs, &II, VRBaseMap);
695
696     // Commute node if it has been determined to be profitable.
697     if (CommuteSet.count(Node)) {
698       MachineInstr *NewMI = TII->commuteInstruction(MI);
699       if (NewMI == 0)
700         DOUT << "Sched: COMMUTING FAILED!\n";
701       else {
702         DOUT << "Sched: COMMUTED TO: " << *NewMI;
703         if (MI != NewMI) {
704           delete MI;
705           MI = NewMI;
706         }
707       }
708     }
709
710     // Now that we have emitted all operands, emit this instruction itself.
711     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
712       BB->insert(BB->end(), MI);
713     } else {
714       // Insert this instruction into the end of the basic block, potentially
715       // taking some custom action.
716       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
717     }
718
719     // Additional results must be an physical register def.
720     if (HasPhysRegOuts) {
721       for (unsigned i = II.numDefs; i < NumResults; ++i) {
722         unsigned Reg = II.ImplicitDefs[i - II.numDefs];
723         if (Node->hasAnyUseOfValue(i))
724           EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
725       }
726     }
727   } else {
728     switch (Node->getOpcode()) {
729     default:
730 #ifndef NDEBUG
731       Node->dump(&DAG);
732 #endif
733       assert(0 && "This target-independent node should have been selected!");
734     case ISD::EntryToken: // fall thru
735     case ISD::TokenFactor:
736     case ISD::LABEL:
737       break;
738     case ISD::CopyToReg: {
739       unsigned InReg;
740       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
741         InReg = R->getReg();
742       else
743         InReg = getVR(Node->getOperand(2), VRBaseMap);
744       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
745       if (InReg != DestReg)  {// Coalesced away the copy?
746         const TargetRegisterClass *TRC = 0;
747         // Get the target register class
748         if (MRegisterInfo::isVirtualRegister(InReg))
749           TRC = RegInfo.getRegClass(InReg);
750         else
751           TRC =
752             MRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
753                                             InReg);
754         TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
755       }
756       break;
757     }
758     case ISD::CopyFromReg: {
759       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
760       EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
761       break;
762     }
763     case ISD::INLINEASM: {
764       unsigned NumOps = Node->getNumOperands();
765       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
766         --NumOps;  // Ignore the flag operand.
767       
768       // Create the inline asm machine instruction.
769       MachineInstr *MI =
770         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
771
772       // Add the asm string as an external symbol operand.
773       const char *AsmStr =
774         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
775       MI->addOperand(MachineOperand::CreateES(AsmStr));
776       
777       // Add all of the operand registers to the instruction.
778       for (unsigned i = 2; i != NumOps;) {
779         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
780         unsigned NumVals = Flags >> 3;
781         
782         MI->addOperand(MachineOperand::CreateImm(Flags));
783         ++i;  // Skip the ID value.
784         
785         switch (Flags & 7) {
786         default: assert(0 && "Bad flags!");
787         case 1:  // Use of register.
788           for (; NumVals; --NumVals, ++i) {
789             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
790             MI->addOperand(MachineOperand::CreateReg(Reg, false));
791           }
792           break;
793         case 2:   // Def of register.
794           for (; NumVals; --NumVals, ++i) {
795             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
796             MI->addOperand(MachineOperand::CreateReg(Reg, true));
797           }
798           break;
799         case 3: { // Immediate.
800           for (; NumVals; --NumVals, ++i) {
801             if (ConstantSDNode *CS =
802                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
803               MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
804             } else if (GlobalAddressSDNode *GA = 
805                   dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
806               MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
807                                                       GA->getOffset()));
808             } else {
809               BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
810               MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
811             }
812           }
813           break;
814         }
815         case 4:  // Addressing mode.
816           // The addressing mode has been selected, just add all of the
817           // operands to the machine instruction.
818           for (; NumVals; --NumVals, ++i)
819             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
820           break;
821         }
822       }
823       break;
824     }
825     }
826   }
827 }
828
829 void ScheduleDAG::EmitNoop() {
830   TII->insertNoop(*BB, BB->end());
831 }
832
833 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
834   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
835        I != E; ++I) {
836     if (I->isCtrl) continue;  // ignore chain preds
837     if (!I->Dep->Node) {
838       // Copy to physical register.
839       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
840       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
841       // Find the destination physical register.
842       unsigned Reg = 0;
843       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
844              EE = SU->Succs.end(); II != EE; ++II) {
845         if (I->Reg) {
846           Reg = I->Reg;
847           break;
848         }
849       }
850       assert(I->Reg && "Unknown physical register!");
851       TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
852                         SU->CopyDstRC, SU->CopySrcRC);
853     } else {
854       // Copy from physical register.
855       assert(I->Reg && "Unknown physical register!");
856       unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
857       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
858       assert(isNew && "Node emitted out of order - early");
859       TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
860                         SU->CopyDstRC, SU->CopySrcRC);
861     }
862     break;
863   }
864 }
865
866 /// EmitSchedule - Emit the machine code in scheduled order.
867 void ScheduleDAG::EmitSchedule() {
868   // If this is the first basic block in the function, and if it has live ins
869   // that need to be copied into vregs, emit the copies into the top of the
870   // block before emitting the code for the block.
871   MachineFunction &MF = DAG.getMachineFunction();
872   if (&MF.front() == BB) {
873     for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
874          E = RegInfo.livein_end(); LI != E; ++LI)
875       if (LI->second) {
876         const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
877         TII->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
878                           LI->first, RC, RC);
879       }
880   }
881   
882   
883   // Finally, emit the code for all of the scheduled instructions.
884   DenseMap<SDOperand, unsigned> VRBaseMap;
885   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
886   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
887     if (SUnit *SU = Sequence[i]) {
888       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
889         EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
890       if (SU->Node)
891         EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
892       else
893         EmitCrossRCCopy(SU, CopyVRBaseMap);
894     } else {
895       // Null SUnit* is a noop.
896       EmitNoop();
897     }
898   }
899 }
900
901 /// dump - dump the schedule.
902 void ScheduleDAG::dumpSchedule() const {
903   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
904     if (SUnit *SU = Sequence[i])
905       SU->dump(&DAG);
906     else
907       cerr << "**** NOOP ****\n";
908   }
909 }
910
911
912 /// Run - perform scheduling.
913 ///
914 MachineBasicBlock *ScheduleDAG::Run() {
915   Schedule();
916   return BB;
917 }
918
919 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
920 /// a group of nodes flagged together.
921 void SUnit::dump(const SelectionDAG *G) const {
922   cerr << "SU(" << NodeNum << "): ";
923   if (Node)
924     Node->dump(G);
925   else
926     cerr << "CROSS RC COPY ";
927   cerr << "\n";
928   if (FlaggedNodes.size() != 0) {
929     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
930       cerr << "    ";
931       FlaggedNodes[i]->dump(G);
932       cerr << "\n";
933     }
934   }
935 }
936
937 void SUnit::dumpAll(const SelectionDAG *G) const {
938   dump(G);
939
940   cerr << "  # preds left       : " << NumPredsLeft << "\n";
941   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
942   cerr << "  Latency            : " << Latency << "\n";
943   cerr << "  Depth              : " << Depth << "\n";
944   cerr << "  Height             : " << Height << "\n";
945
946   if (Preds.size() != 0) {
947     cerr << "  Predecessors:\n";
948     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
949          I != E; ++I) {
950       if (I->isCtrl)
951         cerr << "   ch  #";
952       else
953         cerr << "   val #";
954       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
955       if (I->isSpecial)
956         cerr << " *";
957       cerr << "\n";
958     }
959   }
960   if (Succs.size() != 0) {
961     cerr << "  Successors:\n";
962     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
963          I != E; ++I) {
964       if (I->isCtrl)
965         cerr << "   ch  #";
966       else
967         cerr << "   val #";
968       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
969       if (I->isSpecial)
970         cerr << " *";
971       cerr << "\n";
972     }
973   }
974   cerr << "\n";
975 }