Fix some latent bugs if the nodes are unschedulable. We'd gotten away
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSDNodes.cpp
1 //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes 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 the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "SDNodeDbgValue.h"
17 #include "ScheduleDAGSDNodes.h"
18 #include "InstrEmitter.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetSubtarget.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 STATISTIC(LoadsClustered, "Number of loads clustered together");
36
37 // This allows latency based scheduler to notice high latency instructions
38 // without a target itinerary. The choise if number here has more to do with
39 // balancing scheduler heursitics than with the actual machine latency.
40 static cl::opt<int> HighLatencyCycles(
41   "sched-high-latency-cycles", cl::Hidden, cl::init(10),
42   cl::desc("Roughly estimate the number of cycles that 'long latency'"
43            "instructions take for targets with no itinerary"));
44
45 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
46   : ScheduleDAG(mf),
47     InstrItins(mf.getTarget().getInstrItineraryData()) {}
48
49 /// Run - perform scheduling.
50 ///
51 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
52                              MachineBasicBlock::iterator insertPos) {
53   DAG = dag;
54   ScheduleDAG::Run(bb, insertPos);
55 }
56
57 /// NewSUnit - Creates a new SUnit and return a ptr to it.
58 ///
59 SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
60 #ifndef NDEBUG
61   const SUnit *Addr = 0;
62   if (!SUnits.empty())
63     Addr = &SUnits[0];
64 #endif
65   SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
66   assert((Addr == 0 || Addr == &SUnits[0]) &&
67          "SUnits std::vector reallocated on the fly!");
68   SUnits.back().OrigNode = &SUnits.back();
69   SUnit *SU = &SUnits.back();
70   const TargetLowering &TLI = DAG->getTargetLoweringInfo();
71   if (!N ||
72       (N->isMachineOpcode() &&
73        N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
74     SU->SchedulingPref = Sched::None;
75   else
76     SU->SchedulingPref = TLI.getSchedulingPreference(N);
77   return SU;
78 }
79
80 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
81   SUnit *SU = NewSUnit(Old->getNode());
82   SU->OrigNode = Old->OrigNode;
83   SU->Latency = Old->Latency;
84   SU->isCall = Old->isCall;
85   SU->isTwoAddress = Old->isTwoAddress;
86   SU->isCommutable = Old->isCommutable;
87   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
88   SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
89   SU->SchedulingPref = Old->SchedulingPref;
90   Old->isCloned = true;
91   return SU;
92 }
93
94 /// CheckForPhysRegDependency - Check if the dependency between def and use of
95 /// a specified operand is a physical register dependency. If so, returns the
96 /// register and the cost of copying the register.
97 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
98                                       const TargetRegisterInfo *TRI,
99                                       const TargetInstrInfo *TII,
100                                       unsigned &PhysReg, int &Cost) {
101   if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
102     return;
103
104   unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
105   if (TargetRegisterInfo::isVirtualRegister(Reg))
106     return;
107
108   unsigned ResNo = User->getOperand(2).getResNo();
109   if (Def->isMachineOpcode()) {
110     const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
111     if (ResNo >= II.getNumDefs() &&
112         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
113       PhysReg = Reg;
114       const TargetRegisterClass *RC =
115         TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
116       Cost = RC->getCopyCost();
117     }
118   }
119 }
120
121 static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
122   SmallVector<EVT, 4> VTs;
123   SDNode *GlueDestNode = Glue.getNode();
124
125   // Don't add glue from a node to itself.
126   if (GlueDestNode == N) return;
127
128   // Don't add glue to something which already has glue.
129   if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return;
130
131   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
132     VTs.push_back(N->getValueType(I));
133
134   if (AddGlue)
135     VTs.push_back(MVT::Glue);
136
137   SmallVector<SDValue, 4> Ops;
138   for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
139     Ops.push_back(N->getOperand(I));
140
141   if (GlueDestNode)
142     Ops.push_back(Glue);
143
144   SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
145   MachineSDNode::mmo_iterator Begin = 0, End = 0;
146   MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
147
148   // Store memory references.
149   if (MN) {
150     Begin = MN->memoperands_begin();
151     End = MN->memoperands_end();
152   }
153
154   DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
155
156   // Reset the memory references
157   if (MN)
158     MN->setMemRefs(Begin, End);
159 }
160
161 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
162 /// This function finds loads of the same base and different offsets. If the
163 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
164 /// outputs to ensure they are scheduled together and in order. This
165 /// optimization may benefit some targets by improving cache locality.
166 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
167   SDNode *Chain = 0;
168   unsigned NumOps = Node->getNumOperands();
169   if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
170     Chain = Node->getOperand(NumOps-1).getNode();
171   if (!Chain)
172     return;
173
174   // Look for other loads of the same chain. Find loads that are loading from
175   // the same base pointer and different offsets.
176   SmallPtrSet<SDNode*, 16> Visited;
177   SmallVector<int64_t, 4> Offsets;
178   DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
179   bool Cluster = false;
180   SDNode *Base = Node;
181   for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
182        I != E; ++I) {
183     SDNode *User = *I;
184     if (User == Node || !Visited.insert(User))
185       continue;
186     int64_t Offset1, Offset2;
187     if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
188         Offset1 == Offset2)
189       // FIXME: Should be ok if they addresses are identical. But earlier
190       // optimizations really should have eliminated one of the loads.
191       continue;
192     if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
193       Offsets.push_back(Offset1);
194     O2SMap.insert(std::make_pair(Offset2, User));
195     Offsets.push_back(Offset2);
196     if (Offset2 < Offset1)
197       Base = User;
198     Cluster = true;
199   }
200
201   if (!Cluster)
202     return;
203
204   // Sort them in increasing order.
205   std::sort(Offsets.begin(), Offsets.end());
206
207   // Check if the loads are close enough.
208   SmallVector<SDNode*, 4> Loads;
209   unsigned NumLoads = 0;
210   int64_t BaseOff = Offsets[0];
211   SDNode *BaseLoad = O2SMap[BaseOff];
212   Loads.push_back(BaseLoad);
213   for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
214     int64_t Offset = Offsets[i];
215     SDNode *Load = O2SMap[Offset];
216     if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
217       break; // Stop right here. Ignore loads that are further away.
218     Loads.push_back(Load);
219     ++NumLoads;
220   }
221
222   if (NumLoads == 0)
223     return;
224
225   // Cluster loads by adding MVT::Glue outputs and inputs. This also
226   // ensure they are scheduled in order of increasing addresses.
227   SDNode *Lead = Loads[0];
228   AddGlue(Lead, SDValue(0, 0), true, DAG);
229
230   SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
231   for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
232     bool OutGlue = I < E - 1;
233     SDNode *Load = Loads[I];
234
235     AddGlue(Load, InGlue, OutGlue, DAG);
236
237     if (OutGlue)
238       InGlue = SDValue(Load, Load->getNumValues() - 1);
239
240     ++LoadsClustered;
241   }
242 }
243
244 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
245 ///
246 void ScheduleDAGSDNodes::ClusterNodes() {
247   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
248        E = DAG->allnodes_end(); NI != E; ++NI) {
249     SDNode *Node = &*NI;
250     if (!Node || !Node->isMachineOpcode())
251       continue;
252
253     unsigned Opc = Node->getMachineOpcode();
254     const TargetInstrDesc &TID = TII->get(Opc);
255     if (TID.mayLoad())
256       // Cluster loads from "near" addresses into combined SUnits.
257       ClusterNeighboringLoads(Node);
258   }
259 }
260
261 void ScheduleDAGSDNodes::BuildSchedUnits() {
262   // During scheduling, the NodeId field of SDNode is used to map SDNodes
263   // to their associated SUnits by holding SUnits table indices. A value
264   // of -1 means the SDNode does not yet have an associated SUnit.
265   unsigned NumNodes = 0;
266   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
267        E = DAG->allnodes_end(); NI != E; ++NI) {
268     NI->setNodeId(-1);
269     ++NumNodes;
270   }
271
272   // Reserve entries in the vector for each of the SUnits we are creating.  This
273   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
274   // invalidated.
275   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
276   // This is a temporary workaround.
277   SUnits.reserve(NumNodes * 2);
278
279   // Add all nodes in depth first order.
280   SmallVector<SDNode*, 64> Worklist;
281   SmallPtrSet<SDNode*, 64> Visited;
282   Worklist.push_back(DAG->getRoot().getNode());
283   Visited.insert(DAG->getRoot().getNode());
284
285   while (!Worklist.empty()) {
286     SDNode *NI = Worklist.pop_back_val();
287
288     // Add all operands to the worklist unless they've already been added.
289     for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
290       if (Visited.insert(NI->getOperand(i).getNode()))
291         Worklist.push_back(NI->getOperand(i).getNode());
292
293     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
294       continue;
295
296     // If this node has already been processed, stop now.
297     if (NI->getNodeId() != -1) continue;
298
299     SUnit *NodeSUnit = NewSUnit(NI);
300
301     // See if anything is glued to this node, if so, add them to glued
302     // nodes.  Nodes can have at most one glue input and one glue output.  Glue
303     // is required to be the last operand and result of a node.
304
305     // Scan up to find glued preds.
306     SDNode *N = NI;
307     while (N->getNumOperands() &&
308            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
309       N = N->getOperand(N->getNumOperands()-1).getNode();
310       assert(N->getNodeId() == -1 && "Node already inserted!");
311       N->setNodeId(NodeSUnit->NodeNum);
312       if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
313         NodeSUnit->isCall = true;
314     }
315
316     // Scan down to find any glued succs.
317     N = NI;
318     while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
319       SDValue GlueVal(N, N->getNumValues()-1);
320
321       // There are either zero or one users of the Glue result.
322       bool HasGlueUse = false;
323       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
324            UI != E; ++UI)
325         if (GlueVal.isOperandOf(*UI)) {
326           HasGlueUse = true;
327           assert(N->getNodeId() == -1 && "Node already inserted!");
328           N->setNodeId(NodeSUnit->NodeNum);
329           N = *UI;
330           if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
331             NodeSUnit->isCall = true;
332           break;
333         }
334       if (!HasGlueUse) break;
335     }
336
337     // If there are glue operands involved, N is now the bottom-most node
338     // of the sequence of nodes that are glued together.
339     // Update the SUnit.
340     NodeSUnit->setNode(N);
341     assert(N->getNodeId() == -1 && "Node already inserted!");
342     N->setNodeId(NodeSUnit->NodeNum);
343
344     // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
345     InitNumRegDefsLeft(NodeSUnit);
346
347     // Assign the Latency field of NodeSUnit using target-provided information.
348     ComputeLatency(NodeSUnit);
349   }
350 }
351
352 void ScheduleDAGSDNodes::AddSchedEdges() {
353   const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
354
355   // Check to see if the scheduler cares about latencies.
356   bool UnitLatencies = ForceUnitLatencies();
357
358   // Pass 2: add the preds, succs, etc.
359   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
360     SUnit *SU = &SUnits[su];
361     SDNode *MainNode = SU->getNode();
362
363     if (MainNode->isMachineOpcode()) {
364       unsigned Opc = MainNode->getMachineOpcode();
365       const TargetInstrDesc &TID = TII->get(Opc);
366       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
367         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
368           SU->isTwoAddress = true;
369           break;
370         }
371       }
372       if (TID.isCommutable())
373         SU->isCommutable = true;
374     }
375
376     // Find all predecessors and successors of the group.
377     for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
378       if (N->isMachineOpcode() &&
379           TII->get(N->getMachineOpcode()).getImplicitDefs()) {
380         SU->hasPhysRegClobbers = true;
381         unsigned NumUsed = InstrEmitter::CountResults(N);
382         while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
383           --NumUsed;    // Skip over unused values at the end.
384         if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
385           SU->hasPhysRegDefs = true;
386       }
387
388       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
389         SDNode *OpN = N->getOperand(i).getNode();
390         if (isPassiveNode(OpN)) continue;   // Not scheduled.
391         SUnit *OpSU = &SUnits[OpN->getNodeId()];
392         assert(OpSU && "Node has no SUnit!");
393         if (OpSU == SU) continue;           // In the same group.
394
395         EVT OpVT = N->getOperand(i).getValueType();
396         assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
397         bool isChain = OpVT == MVT::Other;
398
399         unsigned PhysReg = 0;
400         int Cost = 1;
401         // Determine if this is a physical register dependency.
402         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
403         assert((PhysReg == 0 || !isChain) &&
404                "Chain dependence via physreg data?");
405         // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
406         // emits a copy from the physical register to a virtual register unless
407         // it requires a cross class copy (cost < 0). That means we are only
408         // treating "expensive to copy" register dependency as physical register
409         // dependency. This may change in the future though.
410         if (Cost >= 0)
411           PhysReg = 0;
412
413         // If this is a ctrl dep, latency is 1.
414         unsigned OpLatency = isChain ? 1 : OpSU->Latency;
415         const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
416                                OpLatency, PhysReg);
417         if (!isChain && !UnitLatencies) {
418           ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
419           ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
420         }
421
422         if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 0) {
423           // Multiple register uses are combined in the same SUnit. For example,
424           // we could have a set of glued nodes with all their defs consumed by
425           // another set of glued nodes. Register pressure tracking sees this as
426           // a single use, so to keep pressure balanced we reduce the defs.
427           --OpSU->NumRegDefsLeft;
428         }
429       }
430     }
431   }
432 }
433
434 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
435 /// are input.  This SUnit graph is similar to the SelectionDAG, but
436 /// excludes nodes that aren't interesting to scheduling, and represents
437 /// glued together nodes with a single SUnit.
438 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
439   // Cluster certain nodes which should be scheduled together.
440   ClusterNodes();
441   // Populate the SUnits array.
442   BuildSchedUnits();
443   // Compute all the scheduling dependencies between nodes.
444   AddSchedEdges();
445 }
446
447 // Initialize NumNodeDefs for the current Node's opcode.
448 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
449   // Check for phys reg copy.
450   if (!Node)
451     return;
452
453   if (!Node->isMachineOpcode()) {
454     if (Node->getOpcode() == ISD::CopyFromReg)
455       NodeNumDefs = 1;
456     else
457       NodeNumDefs = 0;
458     return;
459   }
460   unsigned POpc = Node->getMachineOpcode();
461   if (POpc == TargetOpcode::IMPLICIT_DEF) {
462     // No register need be allocated for this.
463     NodeNumDefs = 0;
464     return;
465   }
466   unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
467   // Some instructions define regs that are not represented in the selection DAG
468   // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
469   NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
470   DefIdx = 0;
471 }
472
473 // Construct a RegDefIter for this SUnit and find the first valid value.
474 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
475                                            const ScheduleDAGSDNodes *SD)
476   : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
477   InitNodeNumDefs();
478   Advance();
479 }
480
481 // Advance to the next valid value defined by the SUnit.
482 void ScheduleDAGSDNodes::RegDefIter::Advance() {
483   for (;Node;) { // Visit all glued nodes.
484     for (;DefIdx < NodeNumDefs; ++DefIdx) {
485       if (!Node->hasAnyUseOfValue(DefIdx))
486         continue;
487       if (Node->isMachineOpcode() &&
488           Node->getMachineOpcode() == TargetOpcode::EXTRACT_SUBREG) {
489         // Propagate the incoming (full-register) type. I doubt it's needed.
490         ValueType = Node->getOperand(0).getValueType();
491       }
492       else {
493         ValueType = Node->getValueType(DefIdx);
494       }
495       ++DefIdx;
496       return; // Found a normal regdef.
497     }
498     Node = Node->getGluedNode();
499     if (Node == NULL) {
500       return; // No values left to visit.
501     }
502     InitNodeNumDefs();
503   }
504 }
505
506 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
507   assert(SU->NumRegDefsLeft == 0 && "expect a new node");
508   for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
509     assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
510     ++SU->NumRegDefsLeft;
511   }
512 }
513
514 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
515   // Check to see if the scheduler cares about latencies.
516   if (ForceUnitLatencies()) {
517     SU->Latency = 1;
518     return;
519   }
520
521   if (!InstrItins || InstrItins->isEmpty()) {
522     SDNode *N = SU->getNode();
523     if (N && N->isMachineOpcode() &&
524         TII->isHighLatencyDef(N->getMachineOpcode()))
525       SU->Latency = HighLatencyCycles;
526     else
527       SU->Latency = 1;
528     return;
529   }
530
531   // Compute the latency for the node.  We use the sum of the latencies for
532   // all nodes glued together into this SUnit.
533   SU->Latency = 0;
534   for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
535     if (N->isMachineOpcode())
536       SU->Latency += TII->getInstrLatency(InstrItins, N);
537 }
538
539 void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
540                                                unsigned OpIdx, SDep& dep) const{
541   // Check to see if the scheduler cares about latencies.
542   if (ForceUnitLatencies())
543     return;
544
545   if (dep.getKind() != SDep::Data)
546     return;
547
548   unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
549   if (Use->isMachineOpcode())
550     // Adjust the use operand index by num of defs.
551     OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
552   int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
553   if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
554       !BB->succ_empty()) {
555     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
556     if (TargetRegisterInfo::isVirtualRegister(Reg))
557       // This copy is a liveout value. It is likely coalesced, so reduce the
558       // latency so not to penalize the def.
559       // FIXME: need target specific adjustment here?
560       Latency = (Latency > 1) ? Latency - 1 : 1;
561   }
562   if (Latency >= 0)
563     dep.setLatency(Latency);
564 }
565
566 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
567   if (!SU->getNode()) {
568     dbgs() << "PHYS REG COPY\n";
569     return;
570   }
571
572   SU->getNode()->dump(DAG);
573   dbgs() << "\n";
574   SmallVector<SDNode *, 4> GluedNodes;
575   for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
576     GluedNodes.push_back(N);
577   while (!GluedNodes.empty()) {
578     dbgs() << "    ";
579     GluedNodes.back()->dump(DAG);
580     dbgs() << "\n";
581     GluedNodes.pop_back();
582   }
583 }
584
585 namespace {
586   struct OrderSorter {
587     bool operator()(const std::pair<unsigned, MachineInstr*> &A,
588                     const std::pair<unsigned, MachineInstr*> &B) {
589       return A.first < B.first;
590     }
591   };
592 }
593
594 /// ProcessSDDbgValues - Process SDDbgValues assoicated with this node.
595 static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
596                                InstrEmitter &Emitter,
597                     SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
598                             DenseMap<SDValue, unsigned> &VRBaseMap,
599                             unsigned Order) {
600   if (!N->getHasDebugValue())
601     return;
602
603   // Opportunistically insert immediate dbg_value uses, i.e. those with source
604   // order number right after the N.
605   MachineBasicBlock *BB = Emitter.getBlock();
606   MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
607   SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
608   for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
609     if (DVs[i]->isInvalidated())
610       continue;
611     unsigned DVOrder = DVs[i]->getOrder();
612     if (!Order || DVOrder == ++Order) {
613       MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
614       if (DbgMI) {
615         Orders.push_back(std::make_pair(DVOrder, DbgMI));
616         BB->insert(InsertPos, DbgMI);
617       }
618       DVs[i]->setIsInvalidated();
619     }
620   }
621 }
622
623 // ProcessSourceNode - Process nodes with source order numbers. These are added
624 // to a vector which EmitSchedule uses to determine how to insert dbg_value
625 // instructions in the right order.
626 static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
627                            InstrEmitter &Emitter,
628                            DenseMap<SDValue, unsigned> &VRBaseMap,
629                     SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
630                            SmallSet<unsigned, 8> &Seen) {
631   unsigned Order = DAG->GetOrdering(N);
632   if (!Order || !Seen.insert(Order)) {
633     // Process any valid SDDbgValues even if node does not have any order
634     // assigned.
635     ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
636     return;
637   }
638
639   MachineBasicBlock *BB = Emitter.getBlock();
640   if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
641     // Did not insert any instruction.
642     Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
643     return;
644   }
645
646   Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
647   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
648 }
649
650
651 /// EmitSchedule - Emit the machine code in scheduled order.
652 MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
653   InstrEmitter Emitter(BB, InsertPos);
654   DenseMap<SDValue, unsigned> VRBaseMap;
655   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
656   SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
657   SmallSet<unsigned, 8> Seen;
658   bool HasDbg = DAG->hasDebugValues();
659
660   // If this is the first BB, emit byval parameter dbg_value's.
661   if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
662     SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
663     SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
664     for (; PDI != PDE; ++PDI) {
665       MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
666       if (DbgMI)
667         BB->insert(InsertPos, DbgMI);
668     }
669   }
670
671   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
672     SUnit *SU = Sequence[i];
673     if (!SU) {
674       // Null SUnit* is a noop.
675       EmitNoop();
676       continue;
677     }
678
679     // For pre-regalloc scheduling, create instructions corresponding to the
680     // SDNode and any glued SDNodes and append them to the block.
681     if (!SU->getNode()) {
682       // Emit a copy.
683       EmitPhysRegCopy(SU, CopyVRBaseMap);
684       continue;
685     }
686
687     SmallVector<SDNode *, 4> GluedNodes;
688     for (SDNode *N = SU->getNode()->getGluedNode(); N;
689          N = N->getGluedNode())
690       GluedNodes.push_back(N);
691     while (!GluedNodes.empty()) {
692       SDNode *N = GluedNodes.back();
693       Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
694                        VRBaseMap);
695       // Remember the source order of the inserted instruction.
696       if (HasDbg)
697         ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
698       GluedNodes.pop_back();
699     }
700     Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
701                      VRBaseMap);
702     // Remember the source order of the inserted instruction.
703     if (HasDbg)
704       ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
705                         Seen);
706   }
707
708   // Insert all the dbg_values which have not already been inserted in source
709   // order sequence.
710   if (HasDbg) {
711     MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
712
713     // Sort the source order instructions and use the order to insert debug
714     // values.
715     std::sort(Orders.begin(), Orders.end(), OrderSorter());
716
717     SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
718     SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
719     // Now emit the rest according to source order.
720     unsigned LastOrder = 0;
721     for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
722       unsigned Order = Orders[i].first;
723       MachineInstr *MI = Orders[i].second;
724       // Insert all SDDbgValue's whose order(s) are before "Order".
725       if (!MI)
726         continue;
727       for (; DI != DE &&
728              (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
729         if ((*DI)->isInvalidated())
730           continue;
731         MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
732         if (DbgMI) {
733           if (!LastOrder)
734             // Insert to start of the BB (after PHIs).
735             BB->insert(BBBegin, DbgMI);
736           else {
737             // Insert at the instruction, which may be in a different
738             // block, if the block was split by a custom inserter.
739             MachineBasicBlock::iterator Pos = MI;
740             MI->getParent()->insert(llvm::next(Pos), DbgMI);
741           }
742         }
743       }
744       LastOrder = Order;
745     }
746     // Add trailing DbgValue's before the terminator. FIXME: May want to add
747     // some of them before one or more conditional branches?
748     while (DI != DE) {
749       MachineBasicBlock *InsertBB = Emitter.getBlock();
750       MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
751       if (!(*DI)->isInvalidated()) {
752         MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
753         if (DbgMI)
754           InsertBB->insert(Pos, DbgMI);
755       }
756       ++DI;
757     }
758   }
759
760   BB = Emitter.getBlock();
761   InsertPos = Emitter.getInsertPos();
762   return BB;
763 }