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