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