]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp
Merge OpenSSL 1.0.1m.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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).second)
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()).second)
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   if (POpc == TargetOpcode::PATCHPOINT &&
555       Node->getValueType(0) == MVT::Other) {
556     // PATCHPOINT is defined to have one result, but it might really have none
557     // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
558     // real definition.
559     NodeNumDefs = 0;
560     return;
561   }
562   unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
563   // Some instructions define regs that are not represented in the selection DAG
564   // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
565   NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
566   DefIdx = 0;
567 }
568
569 // Construct a RegDefIter for this SUnit and find the first valid value.
570 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
571                                            const ScheduleDAGSDNodes *SD)
572   : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
573   InitNodeNumDefs();
574   Advance();
575 }
576
577 // Advance to the next valid value defined by the SUnit.
578 void ScheduleDAGSDNodes::RegDefIter::Advance() {
579   for (;Node;) { // Visit all glued nodes.
580     for (;DefIdx < NodeNumDefs; ++DefIdx) {
581       if (!Node->hasAnyUseOfValue(DefIdx))
582         continue;
583       ValueType = Node->getSimpleValueType(DefIdx);
584       ++DefIdx;
585       return; // Found a normal regdef.
586     }
587     Node = Node->getGluedNode();
588     if (!Node) {
589       return; // No values left to visit.
590     }
591     InitNodeNumDefs();
592   }
593 }
594
595 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
596   assert(SU->NumRegDefsLeft == 0 && "expect a new node");
597   for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
598     assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
599     ++SU->NumRegDefsLeft;
600   }
601 }
602
603 void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
604   SDNode *N = SU->getNode();
605
606   // TokenFactor operands are considered zero latency, and some schedulers
607   // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
608   // whenever node latency is nonzero.
609   if (N && N->getOpcode() == ISD::TokenFactor) {
610     SU->Latency = 0;
611     return;
612   }
613
614   // Check to see if the scheduler cares about latencies.
615   if (forceUnitLatencies()) {
616     SU->Latency = 1;
617     return;
618   }
619
620   if (!InstrItins || InstrItins->isEmpty()) {
621     if (N && N->isMachineOpcode() &&
622         TII->isHighLatencyDef(N->getMachineOpcode()))
623       SU->Latency = HighLatencyCycles;
624     else
625       SU->Latency = 1;
626     return;
627   }
628
629   // Compute the latency for the node.  We use the sum of the latencies for
630   // all nodes glued together into this SUnit.
631   SU->Latency = 0;
632   for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
633     if (N->isMachineOpcode())
634       SU->Latency += TII->getInstrLatency(InstrItins, N);
635 }
636
637 void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
638                                                unsigned OpIdx, SDep& dep) const{
639   // Check to see if the scheduler cares about latencies.
640   if (forceUnitLatencies())
641     return;
642
643   if (dep.getKind() != SDep::Data)
644     return;
645
646   unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
647   if (Use->isMachineOpcode())
648     // Adjust the use operand index by num of defs.
649     OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
650   int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
651   if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
652       !BB->succ_empty()) {
653     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
654     if (TargetRegisterInfo::isVirtualRegister(Reg))
655       // This copy is a liveout value. It is likely coalesced, so reduce the
656       // latency so not to penalize the def.
657       // FIXME: need target specific adjustment here?
658       Latency = (Latency > 1) ? Latency - 1 : 1;
659   }
660   if (Latency >= 0)
661     dep.setLatency(Latency);
662 }
663
664 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
665 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
666   if (!SU->getNode()) {
667     dbgs() << "PHYS REG COPY\n";
668     return;
669   }
670
671   SU->getNode()->dump(DAG);
672   dbgs() << "\n";
673   SmallVector<SDNode *, 4> GluedNodes;
674   for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
675     GluedNodes.push_back(N);
676   while (!GluedNodes.empty()) {
677     dbgs() << "    ";
678     GluedNodes.back()->dump(DAG);
679     dbgs() << "\n";
680     GluedNodes.pop_back();
681   }
682 #endif
683 }
684
685 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
686 void ScheduleDAGSDNodes::dumpSchedule() const {
687   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
688     if (SUnit *SU = Sequence[i])
689       SU->dump(this);
690     else
691       dbgs() << "**** NOOP ****\n";
692   }
693 }
694 #endif
695
696 #ifndef NDEBUG
697 /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
698 /// their state is consistent with the nodes listed in Sequence.
699 ///
700 void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
701   unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
702   unsigned Noops = 0;
703   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
704     if (!Sequence[i])
705       ++Noops;
706   assert(Sequence.size() - Noops == ScheduledNodes &&
707          "The number of nodes scheduled doesn't match the expected number!");
708 }
709 #endif // NDEBUG
710
711 /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
712 static void
713 ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
714                    SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
715                    DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
716   if (!N->getHasDebugValue())
717     return;
718
719   // Opportunistically insert immediate dbg_value uses, i.e. those with source
720   // order number right after the N.
721   MachineBasicBlock *BB = Emitter.getBlock();
722   MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
723   ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
724   for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
725     if (DVs[i]->isInvalidated())
726       continue;
727     unsigned DVOrder = DVs[i]->getOrder();
728     if (!Order || DVOrder == ++Order) {
729       MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
730       if (DbgMI) {
731         Orders.push_back(std::make_pair(DVOrder, DbgMI));
732         BB->insert(InsertPos, DbgMI);
733       }
734       DVs[i]->setIsInvalidated();
735     }
736   }
737 }
738
739 // ProcessSourceNode - Process nodes with source order numbers. These are added
740 // to a vector which EmitSchedule uses to determine how to insert dbg_value
741 // instructions in the right order.
742 static void
743 ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
744                   DenseMap<SDValue, unsigned> &VRBaseMap,
745                   SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
746                   SmallSet<unsigned, 8> &Seen) {
747   unsigned Order = N->getIROrder();
748   if (!Order || !Seen.insert(Order).second) {
749     // Process any valid SDDbgValues even if node does not have any order
750     // assigned.
751     ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
752     return;
753   }
754
755   MachineBasicBlock *BB = Emitter.getBlock();
756   if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
757       // Fast-isel may have inserted some instructions, in which case the
758       // BB->back().isPHI() test will not fire when we want it to.
759       std::prev(Emitter.getInsertPos())->isPHI()) {
760     // Did not insert any instruction.
761     Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
762     return;
763   }
764
765   Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
766   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
767 }
768
769 void ScheduleDAGSDNodes::
770 EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
771                 MachineBasicBlock::iterator InsertPos) {
772   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
773        I != E; ++I) {
774     if (I->isCtrl()) continue;  // ignore chain preds
775     if (I->getSUnit()->CopyDstRC) {
776       // Copy to physical register.
777       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
778       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
779       // Find the destination physical register.
780       unsigned Reg = 0;
781       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
782              EE = SU->Succs.end(); II != EE; ++II) {
783         if (II->isCtrl()) continue;  // ignore chain preds
784         if (II->getReg()) {
785           Reg = II->getReg();
786           break;
787         }
788       }
789       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
790         .addReg(VRI->second);
791     } else {
792       // Copy from physical register.
793       assert(I->getReg() && "Unknown physical register!");
794       unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
795       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
796       (void)isNew; // Silence compiler warning.
797       assert(isNew && "Node emitted out of order - early");
798       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
799         .addReg(I->getReg());
800     }
801     break;
802   }
803 }
804
805 /// EmitSchedule - Emit the machine code in scheduled order. Return the new
806 /// InsertPos and MachineBasicBlock that contains this insertion
807 /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
808 /// not necessarily refer to returned BB. The emitter may split blocks.
809 MachineBasicBlock *ScheduleDAGSDNodes::
810 EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
811   InstrEmitter Emitter(BB, InsertPos);
812   DenseMap<SDValue, unsigned> VRBaseMap;
813   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
814   SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
815   SmallSet<unsigned, 8> Seen;
816   bool HasDbg = DAG->hasDebugValues();
817
818   // If this is the first BB, emit byval parameter dbg_value's.
819   if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
820     SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
821     SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
822     for (; PDI != PDE; ++PDI) {
823       MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
824       if (DbgMI)
825         BB->insert(InsertPos, DbgMI);
826     }
827   }
828
829   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
830     SUnit *SU = Sequence[i];
831     if (!SU) {
832       // Null SUnit* is a noop.
833       TII->insertNoop(*Emitter.getBlock(), InsertPos);
834       continue;
835     }
836
837     // For pre-regalloc scheduling, create instructions corresponding to the
838     // SDNode and any glued SDNodes and append them to the block.
839     if (!SU->getNode()) {
840       // Emit a copy.
841       EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
842       continue;
843     }
844
845     SmallVector<SDNode *, 4> GluedNodes;
846     for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
847       GluedNodes.push_back(N);
848     while (!GluedNodes.empty()) {
849       SDNode *N = GluedNodes.back();
850       Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
851                        VRBaseMap);
852       // Remember the source order of the inserted instruction.
853       if (HasDbg)
854         ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
855       GluedNodes.pop_back();
856     }
857     Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
858                      VRBaseMap);
859     // Remember the source order of the inserted instruction.
860     if (HasDbg)
861       ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
862                         Seen);
863   }
864
865   // Insert all the dbg_values which have not already been inserted in source
866   // order sequence.
867   if (HasDbg) {
868     MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
869
870     // Sort the source order instructions and use the order to insert debug
871     // values.
872     std::sort(Orders.begin(), Orders.end(), less_first());
873
874     SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
875     SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
876     // Now emit the rest according to source order.
877     unsigned LastOrder = 0;
878     for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
879       unsigned Order = Orders[i].first;
880       MachineInstr *MI = Orders[i].second;
881       // Insert all SDDbgValue's whose order(s) are before "Order".
882       if (!MI)
883         continue;
884       for (; DI != DE &&
885              (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
886         if ((*DI)->isInvalidated())
887           continue;
888         MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
889         if (DbgMI) {
890           if (!LastOrder)
891             // Insert to start of the BB (after PHIs).
892             BB->insert(BBBegin, DbgMI);
893           else {
894             // Insert at the instruction, which may be in a different
895             // block, if the block was split by a custom inserter.
896             MachineBasicBlock::iterator Pos = MI;
897             MI->getParent()->insert(Pos, DbgMI);
898           }
899         }
900       }
901       LastOrder = Order;
902     }
903     // Add trailing DbgValue's before the terminator. FIXME: May want to add
904     // some of them before one or more conditional branches?
905     SmallVector<MachineInstr*, 8> DbgMIs;
906     while (DI != DE) {
907       if (!(*DI)->isInvalidated())
908         if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
909           DbgMIs.push_back(DbgMI);
910       ++DI;
911     }
912
913     MachineBasicBlock *InsertBB = Emitter.getBlock();
914     MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
915     InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
916   }
917
918   InsertPos = Emitter.getInsertPos();
919   return Emitter.getBlock();
920 }
921
922 /// Return the basic block label.
923 std::string ScheduleDAGSDNodes::getDAGName() const {
924   return "sunit-dag." + BB->getFullName();
925 }