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