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