xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This implements the ScheduleDAG class, which is a base class used by
100b57cec5SDimitry Andric // scheduling implementation classes.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "ScheduleDAGSDNodes.h"
150b57cec5SDimitry Andric #include "InstrEmitter.h"
160b57cec5SDimitry Andric #include "SDNodeDbgValue.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
290b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
300b57cec5SDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
310b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
320b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
330b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
345ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric #define DEBUG_TYPE "pre-RA-sched"
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric STATISTIC(LoadsClustered, "Number of loads clustered together");
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric // This allows the latency-based scheduler to notice high latency instructions
420b57cec5SDimitry Andric // without a target itinerary. The choice of number here has more to do with
430b57cec5SDimitry Andric // balancing scheduler heuristics than with the actual machine latency.
440b57cec5SDimitry Andric static cl::opt<int> HighLatencyCycles(
450b57cec5SDimitry Andric   "sched-high-latency-cycles", cl::Hidden, cl::init(10),
460b57cec5SDimitry Andric   cl::desc("Roughly estimate the number of cycles that 'long latency'"
470b57cec5SDimitry Andric            "instructions take for targets with no itinerary"));
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
501fd87a68SDimitry Andric     : ScheduleDAG(mf), InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric /// Run - perform scheduling.
530b57cec5SDimitry Andric ///
540b57cec5SDimitry Andric void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
550b57cec5SDimitry Andric   BB = bb;
560b57cec5SDimitry Andric   DAG = dag;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   // Clear the scheduler's SUnit DAG.
590b57cec5SDimitry Andric   ScheduleDAG::clearDAG();
600b57cec5SDimitry Andric   Sequence.clear();
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   // Invoke the target's selection of scheduler.
630b57cec5SDimitry Andric   Schedule();
640b57cec5SDimitry Andric }
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric /// NewSUnit - Creates a new SUnit and return a ptr to it.
670b57cec5SDimitry Andric ///
680b57cec5SDimitry Andric SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
690b57cec5SDimitry Andric #ifndef NDEBUG
700b57cec5SDimitry Andric   const SUnit *Addr = nullptr;
710b57cec5SDimitry Andric   if (!SUnits.empty())
720b57cec5SDimitry Andric     Addr = &SUnits[0];
730b57cec5SDimitry Andric #endif
740b57cec5SDimitry Andric   SUnits.emplace_back(N, (unsigned)SUnits.size());
750b57cec5SDimitry Andric   assert((Addr == nullptr || Addr == &SUnits[0]) &&
760b57cec5SDimitry Andric          "SUnits std::vector reallocated on the fly!");
770b57cec5SDimitry Andric   SUnits.back().OrigNode = &SUnits.back();
780b57cec5SDimitry Andric   SUnit *SU = &SUnits.back();
790b57cec5SDimitry Andric   const TargetLowering &TLI = DAG->getTargetLoweringInfo();
800b57cec5SDimitry Andric   if (!N ||
810b57cec5SDimitry Andric       (N->isMachineOpcode() &&
820b57cec5SDimitry Andric        N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
830b57cec5SDimitry Andric     SU->SchedulingPref = Sched::None;
840b57cec5SDimitry Andric   else
850b57cec5SDimitry Andric     SU->SchedulingPref = TLI.getSchedulingPreference(N);
860b57cec5SDimitry Andric   return SU;
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
900b57cec5SDimitry Andric   SUnit *SU = newSUnit(Old->getNode());
910b57cec5SDimitry Andric   SU->OrigNode = Old->OrigNode;
920b57cec5SDimitry Andric   SU->Latency = Old->Latency;
930b57cec5SDimitry Andric   SU->isVRegCycle = Old->isVRegCycle;
940b57cec5SDimitry Andric   SU->isCall = Old->isCall;
950b57cec5SDimitry Andric   SU->isCallOp = Old->isCallOp;
960b57cec5SDimitry Andric   SU->isTwoAddress = Old->isTwoAddress;
970b57cec5SDimitry Andric   SU->isCommutable = Old->isCommutable;
980b57cec5SDimitry Andric   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
990b57cec5SDimitry Andric   SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
1000b57cec5SDimitry Andric   SU->isScheduleHigh = Old->isScheduleHigh;
1010b57cec5SDimitry Andric   SU->isScheduleLow = Old->isScheduleLow;
1020b57cec5SDimitry Andric   SU->SchedulingPref = Old->SchedulingPref;
1030b57cec5SDimitry Andric   Old->isCloned = true;
1040b57cec5SDimitry Andric   return SU;
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric /// CheckForPhysRegDependency - Check if the dependency between def and use of
1080b57cec5SDimitry Andric /// a specified operand is a physical register dependency. If so, returns the
1090b57cec5SDimitry Andric /// register and the cost of copying the register.
1100b57cec5SDimitry Andric static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
1110b57cec5SDimitry Andric                                       const TargetRegisterInfo *TRI,
1120b57cec5SDimitry Andric                                       const TargetInstrInfo *TII,
113*bdd1243dSDimitry Andric                                       const TargetLowering &TLI,
1140b57cec5SDimitry Andric                                       unsigned &PhysReg, int &Cost) {
1150b57cec5SDimitry Andric   if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
1160b57cec5SDimitry Andric     return;
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
119*bdd1243dSDimitry Andric   if (TLI.checkForPhysRegDependency(Def, User, Op, TRI, TII, PhysReg, Cost))
120*bdd1243dSDimitry Andric     return;
121*bdd1243dSDimitry Andric 
1228bcb0991SDimitry Andric   if (Register::isVirtualRegister(Reg))
1230b57cec5SDimitry Andric     return;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   unsigned ResNo = User->getOperand(2).getResNo();
1260b57cec5SDimitry Andric   if (Def->getOpcode() == ISD::CopyFromReg &&
1270b57cec5SDimitry Andric       cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
1280b57cec5SDimitry Andric     PhysReg = Reg;
1290b57cec5SDimitry Andric   } else if (Def->isMachineOpcode()) {
1300b57cec5SDimitry Andric     const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
131e8d8bef9SDimitry Andric     if (ResNo >= II.getNumDefs() && II.hasImplicitDefOfPhysReg(Reg))
1320b57cec5SDimitry Andric       PhysReg = Reg;
1330b57cec5SDimitry Andric   }
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   if (PhysReg != 0) {
1360b57cec5SDimitry Andric     const TargetRegisterClass *RC =
1370b57cec5SDimitry Andric         TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
1380b57cec5SDimitry Andric     Cost = RC->getCopyCost();
1390b57cec5SDimitry Andric   }
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric // Helper for AddGlue to clone node operands.
1430b57cec5SDimitry Andric static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
1440b57cec5SDimitry Andric                                 SDValue ExtraOper = SDValue()) {
1450b57cec5SDimitry Andric   SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
1460b57cec5SDimitry Andric   if (ExtraOper.getNode())
1470b57cec5SDimitry Andric     Ops.push_back(ExtraOper);
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   SDVTList VTList = DAG->getVTList(VTs);
1500b57cec5SDimitry Andric   MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   // Store memory references.
1530b57cec5SDimitry Andric   SmallVector<MachineMemOperand *, 2> MMOs;
1540b57cec5SDimitry Andric   if (MN)
1550b57cec5SDimitry Andric     MMOs.assign(MN->memoperands_begin(), MN->memoperands_end());
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric   DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   // Reset the memory references
1600b57cec5SDimitry Andric   if (MN)
1610b57cec5SDimitry Andric     DAG->setNodeMemRefs(MN, MMOs);
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
1650b57cec5SDimitry Andric   SDNode *GlueDestNode = Glue.getNode();
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   // Don't add glue from a node to itself.
1680b57cec5SDimitry Andric   if (GlueDestNode == N) return false;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   // Don't add a glue operand to something that already uses glue.
1710b57cec5SDimitry Andric   if (GlueDestNode &&
1720b57cec5SDimitry Andric       N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
1730b57cec5SDimitry Andric     return false;
1740b57cec5SDimitry Andric   }
1750b57cec5SDimitry Andric   // Don't add glue to something that already has a glue value.
1760b57cec5SDimitry Andric   if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
1770b57cec5SDimitry Andric 
178e8d8bef9SDimitry Andric   SmallVector<EVT, 4> VTs(N->values());
1790b57cec5SDimitry Andric   if (AddGlue)
1800b57cec5SDimitry Andric     VTs.push_back(MVT::Glue);
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   CloneNodeWithValues(N, DAG, VTs, Glue);
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   return true;
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric // Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
1880b57cec5SDimitry Andric // node even though simply shrinking the value list is sufficient.
1890b57cec5SDimitry Andric static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
1900b57cec5SDimitry Andric   assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
1910b57cec5SDimitry Andric           !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
1920b57cec5SDimitry Andric          "expected an unused glue value");
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   CloneNodeWithValues(N, DAG,
195*bdd1243dSDimitry Andric                       ArrayRef(N->value_begin(), N->getNumValues() - 1));
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
1990b57cec5SDimitry Andric /// This function finds loads of the same base and different offsets. If the
2000b57cec5SDimitry Andric /// offsets are not far apart (target specific), it add MVT::Glue inputs and
2010b57cec5SDimitry Andric /// outputs to ensure they are scheduled together and in order. This
2020b57cec5SDimitry Andric /// optimization may benefit some targets by improving cache locality.
2030b57cec5SDimitry Andric void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
2045ffd83dbSDimitry Andric   SDValue Chain;
2050b57cec5SDimitry Andric   unsigned NumOps = Node->getNumOperands();
2060b57cec5SDimitry Andric   if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
2075ffd83dbSDimitry Andric     Chain = Node->getOperand(NumOps-1);
2080b57cec5SDimitry Andric   if (!Chain)
2090b57cec5SDimitry Andric     return;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   // Skip any load instruction that has a tied input. There may be an additional
2120b57cec5SDimitry Andric   // dependency requiring a different order than by increasing offsets, and the
2130b57cec5SDimitry Andric   // added glue may introduce a cycle.
2140b57cec5SDimitry Andric   auto hasTiedInput = [this](const SDNode *N) {
2150b57cec5SDimitry Andric     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
2160b57cec5SDimitry Andric     for (unsigned I = 0; I != MCID.getNumOperands(); ++I) {
2170b57cec5SDimitry Andric       if (MCID.getOperandConstraint(I, MCOI::TIED_TO) != -1)
2180b57cec5SDimitry Andric         return true;
2190b57cec5SDimitry Andric     }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric     return false;
2220b57cec5SDimitry Andric   };
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   // Look for other loads of the same chain. Find loads that are loading from
2250b57cec5SDimitry Andric   // the same base pointer and different offsets.
2260b57cec5SDimitry Andric   SmallPtrSet<SDNode*, 16> Visited;
2270b57cec5SDimitry Andric   SmallVector<int64_t, 4> Offsets;
2280b57cec5SDimitry Andric   DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
2290b57cec5SDimitry Andric   bool Cluster = false;
2300b57cec5SDimitry Andric   SDNode *Base = Node;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   if (hasTiedInput(Base))
2330b57cec5SDimitry Andric     return;
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric   // This algorithm requires a reasonably low use count before finding a match
2360b57cec5SDimitry Andric   // to avoid uselessly blowing up compile time in large blocks.
2370b57cec5SDimitry Andric   unsigned UseCount = 0;
2380b57cec5SDimitry Andric   for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
2390b57cec5SDimitry Andric        I != E && UseCount < 100; ++I, ++UseCount) {
2405ffd83dbSDimitry Andric     if (I.getUse().getResNo() != Chain.getResNo())
2415ffd83dbSDimitry Andric       continue;
2425ffd83dbSDimitry Andric 
2430b57cec5SDimitry Andric     SDNode *User = *I;
2440b57cec5SDimitry Andric     if (User == Node || !Visited.insert(User).second)
2450b57cec5SDimitry Andric       continue;
2460b57cec5SDimitry Andric     int64_t Offset1, Offset2;
2470b57cec5SDimitry Andric     if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
2480b57cec5SDimitry Andric         Offset1 == Offset2 ||
2490b57cec5SDimitry Andric         hasTiedInput(User)) {
2500b57cec5SDimitry Andric       // FIXME: Should be ok if they addresses are identical. But earlier
2510b57cec5SDimitry Andric       // optimizations really should have eliminated one of the loads.
2520b57cec5SDimitry Andric       continue;
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric     if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
2550b57cec5SDimitry Andric       Offsets.push_back(Offset1);
2560b57cec5SDimitry Andric     O2SMap.insert(std::make_pair(Offset2, User));
2570b57cec5SDimitry Andric     Offsets.push_back(Offset2);
2580b57cec5SDimitry Andric     if (Offset2 < Offset1)
2590b57cec5SDimitry Andric       Base = User;
2600b57cec5SDimitry Andric     Cluster = true;
2610b57cec5SDimitry Andric     // Reset UseCount to allow more matches.
2620b57cec5SDimitry Andric     UseCount = 0;
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   if (!Cluster)
2660b57cec5SDimitry Andric     return;
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   // Sort them in increasing order.
2690b57cec5SDimitry Andric   llvm::sort(Offsets);
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   // Check if the loads are close enough.
2720b57cec5SDimitry Andric   SmallVector<SDNode*, 4> Loads;
2730b57cec5SDimitry Andric   unsigned NumLoads = 0;
2740b57cec5SDimitry Andric   int64_t BaseOff = Offsets[0];
2750b57cec5SDimitry Andric   SDNode *BaseLoad = O2SMap[BaseOff];
2760b57cec5SDimitry Andric   Loads.push_back(BaseLoad);
2770b57cec5SDimitry Andric   for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
2780b57cec5SDimitry Andric     int64_t Offset = Offsets[i];
2790b57cec5SDimitry Andric     SDNode *Load = O2SMap[Offset];
2800b57cec5SDimitry Andric     if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
2810b57cec5SDimitry Andric       break; // Stop right here. Ignore loads that are further away.
2820b57cec5SDimitry Andric     Loads.push_back(Load);
2830b57cec5SDimitry Andric     ++NumLoads;
2840b57cec5SDimitry Andric   }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   if (NumLoads == 0)
2870b57cec5SDimitry Andric     return;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   // Cluster loads by adding MVT::Glue outputs and inputs. This also
2900b57cec5SDimitry Andric   // ensure they are scheduled in order of increasing addresses.
2910b57cec5SDimitry Andric   SDNode *Lead = Loads[0];
29204eeddc0SDimitry Andric   SDValue InGlue;
2930b57cec5SDimitry Andric   if (AddGlue(Lead, InGlue, true, DAG))
2940b57cec5SDimitry Andric     InGlue = SDValue(Lead, Lead->getNumValues() - 1);
2950b57cec5SDimitry Andric   for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
2960b57cec5SDimitry Andric     bool OutGlue = I < E - 1;
2970b57cec5SDimitry Andric     SDNode *Load = Loads[I];
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric     // If AddGlue fails, we could leave an unsused glue value. This should not
3000b57cec5SDimitry Andric     // cause any
3010b57cec5SDimitry Andric     if (AddGlue(Load, InGlue, OutGlue, DAG)) {
3020b57cec5SDimitry Andric       if (OutGlue)
3030b57cec5SDimitry Andric         InGlue = SDValue(Load, Load->getNumValues() - 1);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric       ++LoadsClustered;
3060b57cec5SDimitry Andric     }
3070b57cec5SDimitry Andric     else if (!OutGlue && InGlue.getNode())
3080b57cec5SDimitry Andric       RemoveUnusedGlue(InGlue.getNode(), DAG);
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric /// ClusterNodes - Cluster certain nodes which should be scheduled together.
3130b57cec5SDimitry Andric ///
3140b57cec5SDimitry Andric void ScheduleDAGSDNodes::ClusterNodes() {
3150b57cec5SDimitry Andric   for (SDNode &NI : DAG->allnodes()) {
3160b57cec5SDimitry Andric     SDNode *Node = &NI;
3170b57cec5SDimitry Andric     if (!Node || !Node->isMachineOpcode())
3180b57cec5SDimitry Andric       continue;
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     unsigned Opc = Node->getMachineOpcode();
3210b57cec5SDimitry Andric     const MCInstrDesc &MCID = TII->get(Opc);
3220b57cec5SDimitry Andric     if (MCID.mayLoad())
3230b57cec5SDimitry Andric       // Cluster loads from "near" addresses into combined SUnits.
3240b57cec5SDimitry Andric       ClusterNeighboringLoads(Node);
3250b57cec5SDimitry Andric   }
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric void ScheduleDAGSDNodes::BuildSchedUnits() {
3290b57cec5SDimitry Andric   // During scheduling, the NodeId field of SDNode is used to map SDNodes
3300b57cec5SDimitry Andric   // to their associated SUnits by holding SUnits table indices. A value
3310b57cec5SDimitry Andric   // of -1 means the SDNode does not yet have an associated SUnit.
3320b57cec5SDimitry Andric   unsigned NumNodes = 0;
3330b57cec5SDimitry Andric   for (SDNode &NI : DAG->allnodes()) {
3340b57cec5SDimitry Andric     NI.setNodeId(-1);
3350b57cec5SDimitry Andric     ++NumNodes;
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   // Reserve entries in the vector for each of the SUnits we are creating.  This
3390b57cec5SDimitry Andric   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
3400b57cec5SDimitry Andric   // invalidated.
3410b57cec5SDimitry Andric   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
3420b57cec5SDimitry Andric   // This is a temporary workaround.
3430b57cec5SDimitry Andric   SUnits.reserve(NumNodes * 2);
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   // Add all nodes in depth first order.
3460b57cec5SDimitry Andric   SmallVector<SDNode*, 64> Worklist;
3470b57cec5SDimitry Andric   SmallPtrSet<SDNode*, 32> Visited;
3480b57cec5SDimitry Andric   Worklist.push_back(DAG->getRoot().getNode());
3490b57cec5SDimitry Andric   Visited.insert(DAG->getRoot().getNode());
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   SmallVector<SUnit*, 8> CallSUnits;
3520b57cec5SDimitry Andric   while (!Worklist.empty()) {
3530b57cec5SDimitry Andric     SDNode *NI = Worklist.pop_back_val();
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric     // Add all operands to the worklist unless they've already been added.
3560b57cec5SDimitry Andric     for (const SDValue &Op : NI->op_values())
3570b57cec5SDimitry Andric       if (Visited.insert(Op.getNode()).second)
3580b57cec5SDimitry Andric         Worklist.push_back(Op.getNode());
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
3610b57cec5SDimitry Andric       continue;
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     // If this node has already been processed, stop now.
3640b57cec5SDimitry Andric     if (NI->getNodeId() != -1) continue;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric     SUnit *NodeSUnit = newSUnit(NI);
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric     // See if anything is glued to this node, if so, add them to glued
3690b57cec5SDimitry Andric     // nodes.  Nodes can have at most one glue input and one glue output.  Glue
3700b57cec5SDimitry Andric     // is required to be the last operand and result of a node.
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric     // Scan up to find glued preds.
3730b57cec5SDimitry Andric     SDNode *N = NI;
3740b57cec5SDimitry Andric     while (N->getNumOperands() &&
3750b57cec5SDimitry Andric            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
3760b57cec5SDimitry Andric       N = N->getOperand(N->getNumOperands()-1).getNode();
3770b57cec5SDimitry Andric       assert(N->getNodeId() == -1 && "Node already inserted!");
3780b57cec5SDimitry Andric       N->setNodeId(NodeSUnit->NodeNum);
3790b57cec5SDimitry Andric       if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
3800b57cec5SDimitry Andric         NodeSUnit->isCall = true;
3810b57cec5SDimitry Andric     }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     // Scan down to find any glued succs.
3840b57cec5SDimitry Andric     N = NI;
3850b57cec5SDimitry Andric     while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
3860b57cec5SDimitry Andric       SDValue GlueVal(N, N->getNumValues()-1);
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric       // There are either zero or one users of the Glue result.
3890b57cec5SDimitry Andric       bool HasGlueUse = false;
390349cc55cSDimitry Andric       for (SDNode *U : N->uses())
391349cc55cSDimitry Andric         if (GlueVal.isOperandOf(U)) {
3920b57cec5SDimitry Andric           HasGlueUse = true;
3930b57cec5SDimitry Andric           assert(N->getNodeId() == -1 && "Node already inserted!");
3940b57cec5SDimitry Andric           N->setNodeId(NodeSUnit->NodeNum);
395349cc55cSDimitry Andric           N = U;
3960b57cec5SDimitry Andric           if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
3970b57cec5SDimitry Andric             NodeSUnit->isCall = true;
3980b57cec5SDimitry Andric           break;
3990b57cec5SDimitry Andric         }
4000b57cec5SDimitry Andric       if (!HasGlueUse) break;
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric     if (NodeSUnit->isCall)
4040b57cec5SDimitry Andric       CallSUnits.push_back(NodeSUnit);
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     // Schedule zero-latency TokenFactor below any nodes that may increase the
4070b57cec5SDimitry Andric     // schedule height. Otherwise, ancestors of the TokenFactor may appear to
4080b57cec5SDimitry Andric     // have false stalls.
4090b57cec5SDimitry Andric     if (NI->getOpcode() == ISD::TokenFactor)
4100b57cec5SDimitry Andric       NodeSUnit->isScheduleLow = true;
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     // If there are glue operands involved, N is now the bottom-most node
4130b57cec5SDimitry Andric     // of the sequence of nodes that are glued together.
4140b57cec5SDimitry Andric     // Update the SUnit.
4150b57cec5SDimitry Andric     NodeSUnit->setNode(N);
4160b57cec5SDimitry Andric     assert(N->getNodeId() == -1 && "Node already inserted!");
4170b57cec5SDimitry Andric     N->setNodeId(NodeSUnit->NodeNum);
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric     // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
4200b57cec5SDimitry Andric     InitNumRegDefsLeft(NodeSUnit);
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric     // Assign the Latency field of NodeSUnit using target-provided information.
4230b57cec5SDimitry Andric     computeLatency(NodeSUnit);
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   // Find all call operands.
4270b57cec5SDimitry Andric   while (!CallSUnits.empty()) {
4280b57cec5SDimitry Andric     SUnit *SU = CallSUnits.pop_back_val();
4290b57cec5SDimitry Andric     for (const SDNode *SUNode = SU->getNode(); SUNode;
4300b57cec5SDimitry Andric          SUNode = SUNode->getGluedNode()) {
4310b57cec5SDimitry Andric       if (SUNode->getOpcode() != ISD::CopyToReg)
4320b57cec5SDimitry Andric         continue;
4330b57cec5SDimitry Andric       SDNode *SrcN = SUNode->getOperand(2).getNode();
4340b57cec5SDimitry Andric       if (isPassiveNode(SrcN)) continue;   // Not scheduled.
4350b57cec5SDimitry Andric       SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
4360b57cec5SDimitry Andric       SrcSU->isCallOp = true;
4370b57cec5SDimitry Andric     }
4380b57cec5SDimitry Andric   }
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric void ScheduleDAGSDNodes::AddSchedEdges() {
4420b57cec5SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget();
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
4450b57cec5SDimitry Andric   bool UnitLatencies = forceUnitLatencies();
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   // Pass 2: add the preds, succs, etc.
4480eae32dcSDimitry Andric   for (SUnit &SU : SUnits) {
4490eae32dcSDimitry Andric     SDNode *MainNode = SU.getNode();
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric     if (MainNode->isMachineOpcode()) {
4520b57cec5SDimitry Andric       unsigned Opc = MainNode->getMachineOpcode();
4530b57cec5SDimitry Andric       const MCInstrDesc &MCID = TII->get(Opc);
4540b57cec5SDimitry Andric       for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
4550b57cec5SDimitry Andric         if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
4560eae32dcSDimitry Andric           SU.isTwoAddress = true;
4570b57cec5SDimitry Andric           break;
4580b57cec5SDimitry Andric         }
4590b57cec5SDimitry Andric       }
4600b57cec5SDimitry Andric       if (MCID.isCommutable())
4610eae32dcSDimitry Andric         SU.isCommutable = true;
4620b57cec5SDimitry Andric     }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric     // Find all predecessors and successors of the group.
4650eae32dcSDimitry Andric     for (SDNode *N = SU.getNode(); N; N = N->getGluedNode()) {
4660b57cec5SDimitry Andric       if (N->isMachineOpcode() &&
467*bdd1243dSDimitry Andric           !TII->get(N->getMachineOpcode()).implicit_defs().empty()) {
4680eae32dcSDimitry Andric         SU.hasPhysRegClobbers = true;
4690b57cec5SDimitry Andric         unsigned NumUsed = InstrEmitter::CountResults(N);
4700b57cec5SDimitry Andric         while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
4710b57cec5SDimitry Andric           --NumUsed;    // Skip over unused values at the end.
4720b57cec5SDimitry Andric         if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
4730eae32dcSDimitry Andric           SU.hasPhysRegDefs = true;
4740b57cec5SDimitry Andric       }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4770b57cec5SDimitry Andric         SDNode *OpN = N->getOperand(i).getNode();
4785ffd83dbSDimitry Andric         unsigned DefIdx = N->getOperand(i).getResNo();
4790b57cec5SDimitry Andric         if (isPassiveNode(OpN)) continue;   // Not scheduled.
4800b57cec5SDimitry Andric         SUnit *OpSU = &SUnits[OpN->getNodeId()];
4810b57cec5SDimitry Andric         assert(OpSU && "Node has no SUnit!");
4820eae32dcSDimitry Andric         if (OpSU == &SU)
4830eae32dcSDimitry Andric           continue; // In the same group.
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric         EVT OpVT = N->getOperand(i).getValueType();
4860b57cec5SDimitry Andric         assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
4870b57cec5SDimitry Andric         bool isChain = OpVT == MVT::Other;
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric         unsigned PhysReg = 0;
4900b57cec5SDimitry Andric         int Cost = 1;
4910b57cec5SDimitry Andric         // Determine if this is a physical register dependency.
492*bdd1243dSDimitry Andric         const TargetLowering &TLI = DAG->getTargetLoweringInfo();
493*bdd1243dSDimitry Andric         CheckForPhysRegDependency(OpN, N, i, TRI, TII, TLI, PhysReg, Cost);
4940b57cec5SDimitry Andric         assert((PhysReg == 0 || !isChain) &&
4950b57cec5SDimitry Andric                "Chain dependence via physreg data?");
4960b57cec5SDimitry Andric         // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
4970b57cec5SDimitry Andric         // emits a copy from the physical register to a virtual register unless
4980b57cec5SDimitry Andric         // it requires a cross class copy (cost < 0). That means we are only
4990b57cec5SDimitry Andric         // treating "expensive to copy" register dependency as physical register
5000b57cec5SDimitry Andric         // dependency. This may change in the future though.
5010b57cec5SDimitry Andric         if (Cost >= 0 && !StressSched)
5020b57cec5SDimitry Andric           PhysReg = 0;
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric         // If this is a ctrl dep, latency is 1.
5050b57cec5SDimitry Andric         unsigned OpLatency = isChain ? 1 : OpSU->Latency;
5060b57cec5SDimitry Andric         // Special-case TokenFactor chains as zero-latency.
5070b57cec5SDimitry Andric         if(isChain && OpN->getOpcode() == ISD::TokenFactor)
5080b57cec5SDimitry Andric           OpLatency = 0;
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric         SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
5110b57cec5SDimitry Andric           : SDep(OpSU, SDep::Data, PhysReg);
5120b57cec5SDimitry Andric         Dep.setLatency(OpLatency);
5130b57cec5SDimitry Andric         if (!isChain && !UnitLatencies) {
5140b57cec5SDimitry Andric           computeOperandLatency(OpN, N, i, Dep);
5150eae32dcSDimitry Andric           ST.adjustSchedDependency(OpSU, DefIdx, &SU, i, Dep);
5160b57cec5SDimitry Andric         }
5170b57cec5SDimitry Andric 
5180eae32dcSDimitry Andric         if (!SU.addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
5190b57cec5SDimitry Andric           // Multiple register uses are combined in the same SUnit. For example,
5200b57cec5SDimitry Andric           // we could have a set of glued nodes with all their defs consumed by
5210b57cec5SDimitry Andric           // another set of glued nodes. Register pressure tracking sees this as
5220b57cec5SDimitry Andric           // a single use, so to keep pressure balanced we reduce the defs.
5230b57cec5SDimitry Andric           //
5240b57cec5SDimitry Andric           // We can't tell (without more book-keeping) if this results from
5250b57cec5SDimitry Andric           // glued nodes or duplicate operands. As long as we don't reduce
5260b57cec5SDimitry Andric           // NumRegDefsLeft to zero, we handle the common cases well.
5270b57cec5SDimitry Andric           --OpSU->NumRegDefsLeft;
5280b57cec5SDimitry Andric         }
5290b57cec5SDimitry Andric       }
5300b57cec5SDimitry Andric     }
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
5350b57cec5SDimitry Andric /// are input.  This SUnit graph is similar to the SelectionDAG, but
5360b57cec5SDimitry Andric /// excludes nodes that aren't interesting to scheduling, and represents
5370b57cec5SDimitry Andric /// glued together nodes with a single SUnit.
5388bcb0991SDimitry Andric void ScheduleDAGSDNodes::BuildSchedGraph(AAResults *AA) {
5390b57cec5SDimitry Andric   // Cluster certain nodes which should be scheduled together.
5400b57cec5SDimitry Andric   ClusterNodes();
5410b57cec5SDimitry Andric   // Populate the SUnits array.
5420b57cec5SDimitry Andric   BuildSchedUnits();
5430b57cec5SDimitry Andric   // Compute all the scheduling dependencies between nodes.
5440b57cec5SDimitry Andric   AddSchedEdges();
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric // Initialize NumNodeDefs for the current Node's opcode.
5480b57cec5SDimitry Andric void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
5490b57cec5SDimitry Andric   // Check for phys reg copy.
5500b57cec5SDimitry Andric   if (!Node)
5510b57cec5SDimitry Andric     return;
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   if (!Node->isMachineOpcode()) {
5540b57cec5SDimitry Andric     if (Node->getOpcode() == ISD::CopyFromReg)
5550b57cec5SDimitry Andric       NodeNumDefs = 1;
5560b57cec5SDimitry Andric     else
5570b57cec5SDimitry Andric       NodeNumDefs = 0;
5580b57cec5SDimitry Andric     return;
5590b57cec5SDimitry Andric   }
5600b57cec5SDimitry Andric   unsigned POpc = Node->getMachineOpcode();
5610b57cec5SDimitry Andric   if (POpc == TargetOpcode::IMPLICIT_DEF) {
5620b57cec5SDimitry Andric     // No register need be allocated for this.
5630b57cec5SDimitry Andric     NodeNumDefs = 0;
5640b57cec5SDimitry Andric     return;
5650b57cec5SDimitry Andric   }
5660b57cec5SDimitry Andric   if (POpc == TargetOpcode::PATCHPOINT &&
5670b57cec5SDimitry Andric       Node->getValueType(0) == MVT::Other) {
5680b57cec5SDimitry Andric     // PATCHPOINT is defined to have one result, but it might really have none
5690b57cec5SDimitry Andric     // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
5700b57cec5SDimitry Andric     // real definition.
5710b57cec5SDimitry Andric     NodeNumDefs = 0;
5720b57cec5SDimitry Andric     return;
5730b57cec5SDimitry Andric   }
5740b57cec5SDimitry Andric   unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
5750b57cec5SDimitry Andric   // Some instructions define regs that are not represented in the selection DAG
5760b57cec5SDimitry Andric   // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
5770b57cec5SDimitry Andric   NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
5780b57cec5SDimitry Andric   DefIdx = 0;
5790b57cec5SDimitry Andric }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric // Construct a RegDefIter for this SUnit and find the first valid value.
5820b57cec5SDimitry Andric ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
5830b57cec5SDimitry Andric                                            const ScheduleDAGSDNodes *SD)
5841fd87a68SDimitry Andric     : SchedDAG(SD), Node(SU->getNode()) {
5850b57cec5SDimitry Andric   InitNodeNumDefs();
5860b57cec5SDimitry Andric   Advance();
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric // Advance to the next valid value defined by the SUnit.
5900b57cec5SDimitry Andric void ScheduleDAGSDNodes::RegDefIter::Advance() {
5910b57cec5SDimitry Andric   for (;Node;) { // Visit all glued nodes.
5920b57cec5SDimitry Andric     for (;DefIdx < NodeNumDefs; ++DefIdx) {
5930b57cec5SDimitry Andric       if (!Node->hasAnyUseOfValue(DefIdx))
5940b57cec5SDimitry Andric         continue;
5950b57cec5SDimitry Andric       ValueType = Node->getSimpleValueType(DefIdx);
5960b57cec5SDimitry Andric       ++DefIdx;
5970b57cec5SDimitry Andric       return; // Found a normal regdef.
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric     Node = Node->getGluedNode();
6000b57cec5SDimitry Andric     if (!Node) {
6010b57cec5SDimitry Andric       return; // No values left to visit.
6020b57cec5SDimitry Andric     }
6030b57cec5SDimitry Andric     InitNodeNumDefs();
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
6080b57cec5SDimitry Andric   assert(SU->NumRegDefsLeft == 0 && "expect a new node");
6090b57cec5SDimitry Andric   for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
6100b57cec5SDimitry Andric     assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
6110b57cec5SDimitry Andric     ++SU->NumRegDefsLeft;
6120b57cec5SDimitry Andric   }
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
6160b57cec5SDimitry Andric   SDNode *N = SU->getNode();
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric   // TokenFactor operands are considered zero latency, and some schedulers
6190b57cec5SDimitry Andric   // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
6200b57cec5SDimitry Andric   // whenever node latency is nonzero.
6210b57cec5SDimitry Andric   if (N && N->getOpcode() == ISD::TokenFactor) {
6220b57cec5SDimitry Andric     SU->Latency = 0;
6230b57cec5SDimitry Andric     return;
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
6270b57cec5SDimitry Andric   if (forceUnitLatencies()) {
6280b57cec5SDimitry Andric     SU->Latency = 1;
6290b57cec5SDimitry Andric     return;
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   if (!InstrItins || InstrItins->isEmpty()) {
6330b57cec5SDimitry Andric     if (N && N->isMachineOpcode() &&
6340b57cec5SDimitry Andric         TII->isHighLatencyDef(N->getMachineOpcode()))
6350b57cec5SDimitry Andric       SU->Latency = HighLatencyCycles;
6360b57cec5SDimitry Andric     else
6370b57cec5SDimitry Andric       SU->Latency = 1;
6380b57cec5SDimitry Andric     return;
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // Compute the latency for the node.  We use the sum of the latencies for
6420b57cec5SDimitry Andric   // all nodes glued together into this SUnit.
6430b57cec5SDimitry Andric   SU->Latency = 0;
6440b57cec5SDimitry Andric   for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
6450b57cec5SDimitry Andric     if (N->isMachineOpcode())
6460b57cec5SDimitry Andric       SU->Latency += TII->getInstrLatency(InstrItins, N);
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
6500b57cec5SDimitry Andric                                                unsigned OpIdx, SDep& dep) const{
6510b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
6520b57cec5SDimitry Andric   if (forceUnitLatencies())
6530b57cec5SDimitry Andric     return;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   if (dep.getKind() != SDep::Data)
6560b57cec5SDimitry Andric     return;
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
6590b57cec5SDimitry Andric   if (Use->isMachineOpcode())
6600b57cec5SDimitry Andric     // Adjust the use operand index by num of defs.
6610b57cec5SDimitry Andric     OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
6620b57cec5SDimitry Andric   int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
6630b57cec5SDimitry Andric   if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
6640b57cec5SDimitry Andric       !BB->succ_empty()) {
6650b57cec5SDimitry Andric     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
6668bcb0991SDimitry Andric     if (Register::isVirtualRegister(Reg))
6670b57cec5SDimitry Andric       // This copy is a liveout value. It is likely coalesced, so reduce the
6680b57cec5SDimitry Andric       // latency so not to penalize the def.
6690b57cec5SDimitry Andric       // FIXME: need target specific adjustment here?
6700b57cec5SDimitry Andric       Latency = (Latency > 1) ? Latency - 1 : 1;
6710b57cec5SDimitry Andric   }
6720b57cec5SDimitry Andric   if (Latency >= 0)
6730b57cec5SDimitry Andric     dep.setLatency(Latency);
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric void ScheduleDAGSDNodes::dumpNode(const SUnit &SU) const {
6770b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6780b57cec5SDimitry Andric   dumpNodeName(SU);
6790b57cec5SDimitry Andric   dbgs() << ": ";
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   if (!SU.getNode()) {
6820b57cec5SDimitry Andric     dbgs() << "PHYS REG COPY\n";
6830b57cec5SDimitry Andric     return;
6840b57cec5SDimitry Andric   }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   SU.getNode()->dump(DAG);
6870b57cec5SDimitry Andric   dbgs() << "\n";
6880b57cec5SDimitry Andric   SmallVector<SDNode *, 4> GluedNodes;
6890b57cec5SDimitry Andric   for (SDNode *N = SU.getNode()->getGluedNode(); N; N = N->getGluedNode())
6900b57cec5SDimitry Andric     GluedNodes.push_back(N);
6910b57cec5SDimitry Andric   while (!GluedNodes.empty()) {
6920b57cec5SDimitry Andric     dbgs() << "    ";
6930b57cec5SDimitry Andric     GluedNodes.back()->dump(DAG);
6940b57cec5SDimitry Andric     dbgs() << "\n";
6950b57cec5SDimitry Andric     GluedNodes.pop_back();
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric #endif
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric void ScheduleDAGSDNodes::dump() const {
7010b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7020b57cec5SDimitry Andric   if (EntrySU.getNode() != nullptr)
7030b57cec5SDimitry Andric     dumpNodeAll(EntrySU);
7040b57cec5SDimitry Andric   for (const SUnit &SU : SUnits)
7050b57cec5SDimitry Andric     dumpNodeAll(SU);
7060b57cec5SDimitry Andric   if (ExitSU.getNode() != nullptr)
7070b57cec5SDimitry Andric     dumpNodeAll(ExitSU);
7080b57cec5SDimitry Andric #endif
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7120b57cec5SDimitry Andric void ScheduleDAGSDNodes::dumpSchedule() const {
7134824e7fdSDimitry Andric   for (const SUnit *SU : Sequence) {
7144824e7fdSDimitry Andric     if (SU)
7150b57cec5SDimitry Andric       dumpNode(*SU);
7160b57cec5SDimitry Andric     else
7170b57cec5SDimitry Andric       dbgs() << "**** NOOP ****\n";
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric }
7200b57cec5SDimitry Andric #endif
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric #ifndef NDEBUG
7230b57cec5SDimitry Andric /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
7240b57cec5SDimitry Andric /// their state is consistent with the nodes listed in Sequence.
7250b57cec5SDimitry Andric ///
7260b57cec5SDimitry Andric void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
7270b57cec5SDimitry Andric   unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
7280eae32dcSDimitry Andric   unsigned Noops = llvm::count(Sequence, nullptr);
7290b57cec5SDimitry Andric   assert(Sequence.size() - Noops == ScheduledNodes &&
7300b57cec5SDimitry Andric          "The number of nodes scheduled doesn't match the expected number!");
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric #endif // NDEBUG
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
7350b57cec5SDimitry Andric static void
7360b57cec5SDimitry Andric ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
7370b57cec5SDimitry Andric                    SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
7385ffd83dbSDimitry Andric                    DenseMap<SDValue, Register> &VRBaseMap, unsigned Order) {
7390b57cec5SDimitry Andric   if (!N->getHasDebugValue())
7400b57cec5SDimitry Andric     return;
7410b57cec5SDimitry Andric 
742fe6060f1SDimitry Andric   /// Returns true if \p DV has any VReg operand locations which don't exist in
743fe6060f1SDimitry Andric   /// VRBaseMap.
744fe6060f1SDimitry Andric   auto HasUnknownVReg = [&VRBaseMap](SDDbgValue *DV) {
745349cc55cSDimitry Andric     for (const SDDbgOperand &L : DV->getLocationOps()) {
746fe6060f1SDimitry Andric       if (L.getKind() == SDDbgOperand::SDNODE &&
747fe6060f1SDimitry Andric           VRBaseMap.count({L.getSDNode(), L.getResNo()}) == 0)
748fe6060f1SDimitry Andric         return true;
749fe6060f1SDimitry Andric     }
750fe6060f1SDimitry Andric     return false;
751fe6060f1SDimitry Andric   };
752fe6060f1SDimitry Andric 
7530b57cec5SDimitry Andric   // Opportunistically insert immediate dbg_value uses, i.e. those with the same
7540b57cec5SDimitry Andric   // source order number as N.
7550b57cec5SDimitry Andric   MachineBasicBlock *BB = Emitter.getBlock();
7560b57cec5SDimitry Andric   MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
757fcaf7f86SDimitry Andric   for (auto *DV : DAG->GetDbgValues(N)) {
7580b57cec5SDimitry Andric     if (DV->isEmitted())
7590b57cec5SDimitry Andric       continue;
7600b57cec5SDimitry Andric     unsigned DVOrder = DV->getOrder();
761fe6060f1SDimitry Andric     if (Order != 0 && DVOrder != Order)
762fe6060f1SDimitry Andric       continue;
763fe6060f1SDimitry Andric     // If DV has any VReg location operands which haven't been mapped then
764fe6060f1SDimitry Andric     // either that node is no longer available or we just haven't visited the
765fe6060f1SDimitry Andric     // node yet. In the former case we should emit an undef dbg_value, but we
766fe6060f1SDimitry Andric     // can do it later. And for the latter we'll want to wait until all
767fe6060f1SDimitry Andric     // dependent nodes have been visited.
768fe6060f1SDimitry Andric     if (!DV->isInvalidated() && HasUnknownVReg(DV))
769fe6060f1SDimitry Andric       continue;
7700b57cec5SDimitry Andric     MachineInstr *DbgMI = Emitter.EmitDbgValue(DV, VRBaseMap);
771fe6060f1SDimitry Andric     if (!DbgMI)
772fe6060f1SDimitry Andric       continue;
7730b57cec5SDimitry Andric     Orders.push_back({DVOrder, DbgMI});
7740b57cec5SDimitry Andric     BB->insert(InsertPos, DbgMI);
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric // ProcessSourceNode - Process nodes with source order numbers. These are added
7790b57cec5SDimitry Andric // to a vector which EmitSchedule uses to determine how to insert dbg_value
7800b57cec5SDimitry Andric // instructions in the right order.
7810b57cec5SDimitry Andric static void
7820b57cec5SDimitry Andric ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
7835ffd83dbSDimitry Andric                   DenseMap<SDValue, Register> &VRBaseMap,
7840b57cec5SDimitry Andric                   SmallVectorImpl<std::pair<unsigned, MachineInstr *>> &Orders,
7855ffd83dbSDimitry Andric                   SmallSet<Register, 8> &Seen, MachineInstr *NewInsn) {
7860b57cec5SDimitry Andric   unsigned Order = N->getIROrder();
7870b57cec5SDimitry Andric   if (!Order || Seen.count(Order)) {
7880b57cec5SDimitry Andric     // Process any valid SDDbgValues even if node does not have any order
7890b57cec5SDimitry Andric     // assigned.
7900b57cec5SDimitry Andric     ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
7910b57cec5SDimitry Andric     return;
7920b57cec5SDimitry Andric   }
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   // If a new instruction was generated for this Order number, record it.
7950b57cec5SDimitry Andric   // Otherwise, leave this order number unseen: we will either find later
7960b57cec5SDimitry Andric   // instructions for it, or leave it unseen if there were no instructions at
7970b57cec5SDimitry Andric   // all.
7980b57cec5SDimitry Andric   if (NewInsn) {
7990b57cec5SDimitry Andric     Seen.insert(Order);
8000b57cec5SDimitry Andric     Orders.push_back({Order, NewInsn});
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // Even if no instruction was generated, a Value may have become defined via
8040b57cec5SDimitry Andric   // earlier nodes. Try to process them now.
8050b57cec5SDimitry Andric   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric void ScheduleDAGSDNodes::
8095ffd83dbSDimitry Andric EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, Register> &VRBaseMap,
8100b57cec5SDimitry Andric                 MachineBasicBlock::iterator InsertPos) {
811fe6060f1SDimitry Andric   for (const SDep &Pred : SU->Preds) {
812fe6060f1SDimitry Andric     if (Pred.isCtrl())
813fe6060f1SDimitry Andric       continue; // ignore chain preds
814fe6060f1SDimitry Andric     if (Pred.getSUnit()->CopyDstRC) {
8150b57cec5SDimitry Andric       // Copy to physical register.
816fe6060f1SDimitry Andric       DenseMap<SUnit *, Register>::iterator VRI =
817fe6060f1SDimitry Andric           VRBaseMap.find(Pred.getSUnit());
8180b57cec5SDimitry Andric       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
8190b57cec5SDimitry Andric       // Find the destination physical register.
8205ffd83dbSDimitry Andric       Register Reg;
821fe6060f1SDimitry Andric       for (const SDep &Succ : SU->Succs) {
822fe6060f1SDimitry Andric         if (Succ.isCtrl())
823fe6060f1SDimitry Andric           continue; // ignore chain preds
824fe6060f1SDimitry Andric         if (Succ.getReg()) {
825fe6060f1SDimitry Andric           Reg = Succ.getReg();
8260b57cec5SDimitry Andric           break;
8270b57cec5SDimitry Andric         }
8280b57cec5SDimitry Andric       }
8290b57cec5SDimitry Andric       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
8300b57cec5SDimitry Andric         .addReg(VRI->second);
8310b57cec5SDimitry Andric     } else {
8320b57cec5SDimitry Andric       // Copy from physical register.
833fe6060f1SDimitry Andric       assert(Pred.getReg() && "Unknown physical register!");
8348bcb0991SDimitry Andric       Register VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
8350b57cec5SDimitry Andric       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
8360b57cec5SDimitry Andric       (void)isNew; // Silence compiler warning.
8370b57cec5SDimitry Andric       assert(isNew && "Node emitted out of order - early");
8380b57cec5SDimitry Andric       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
839fe6060f1SDimitry Andric           .addReg(Pred.getReg());
8400b57cec5SDimitry Andric     }
8410b57cec5SDimitry Andric     break;
8420b57cec5SDimitry Andric   }
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric /// EmitSchedule - Emit the machine code in scheduled order. Return the new
8460b57cec5SDimitry Andric /// InsertPos and MachineBasicBlock that contains this insertion
8470b57cec5SDimitry Andric /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
8480b57cec5SDimitry Andric /// not necessarily refer to returned BB. The emitter may split blocks.
8490b57cec5SDimitry Andric MachineBasicBlock *ScheduleDAGSDNodes::
8500b57cec5SDimitry Andric EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
851*bdd1243dSDimitry Andric   InstrEmitter Emitter(DAG->getTarget(), BB, InsertPos);
8525ffd83dbSDimitry Andric   DenseMap<SDValue, Register> VRBaseMap;
8535ffd83dbSDimitry Andric   DenseMap<SUnit*, Register> CopyVRBaseMap;
8540b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
8555ffd83dbSDimitry Andric   SmallSet<Register, 8> Seen;
8560b57cec5SDimitry Andric   bool HasDbg = DAG->hasDebugValues();
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   // Emit a node, and determine where its first instruction is for debuginfo.
8590b57cec5SDimitry Andric   // Zero, one, or multiple instructions can be created when emitting a node.
8600b57cec5SDimitry Andric   auto EmitNode =
8610b57cec5SDimitry Andric       [&](SDNode *Node, bool IsClone, bool IsCloned,
8625ffd83dbSDimitry Andric           DenseMap<SDValue, Register> &VRBaseMap) -> MachineInstr * {
8630b57cec5SDimitry Andric     // Fetch instruction prior to this, or end() if nonexistant.
8640b57cec5SDimitry Andric     auto GetPrevInsn = [&](MachineBasicBlock::iterator I) {
8650b57cec5SDimitry Andric       if (I == BB->begin())
8660b57cec5SDimitry Andric         return BB->end();
8670b57cec5SDimitry Andric       else
8680b57cec5SDimitry Andric         return std::prev(Emitter.getInsertPos());
8690b57cec5SDimitry Andric     };
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric     MachineBasicBlock::iterator Before = GetPrevInsn(Emitter.getInsertPos());
8720b57cec5SDimitry Andric     Emitter.EmitNode(Node, IsClone, IsCloned, VRBaseMap);
8730b57cec5SDimitry Andric     MachineBasicBlock::iterator After = GetPrevInsn(Emitter.getInsertPos());
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric     // If the iterator did not change, no instructions were inserted.
8760b57cec5SDimitry Andric     if (Before == After)
8770b57cec5SDimitry Andric       return nullptr;
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric     MachineInstr *MI;
8800b57cec5SDimitry Andric     if (Before == BB->end()) {
8810b57cec5SDimitry Andric       // There were no prior instructions; the new ones must start at the
8820b57cec5SDimitry Andric       // beginning of the block.
8830b57cec5SDimitry Andric       MI = &Emitter.getBlock()->instr_front();
8840b57cec5SDimitry Andric     } else {
8850b57cec5SDimitry Andric       // Return first instruction after the pre-existing instructions.
8860b57cec5SDimitry Andric       MI = &*std::next(Before);
8870b57cec5SDimitry Andric     }
8880b57cec5SDimitry Andric 
8895ffd83dbSDimitry Andric     if (MI->isCandidateForCallSiteEntry() &&
8905ffd83dbSDimitry Andric         DAG->getTarget().Options.EmitCallSiteInfo)
89181ad6265SDimitry Andric       MF.addCallArgsForwardingRegs(MI, DAG->getCallSiteInfo(Node));
8920b57cec5SDimitry Andric 
8935ffd83dbSDimitry Andric     if (DAG->getNoMergeSiteInfo(Node)) {
8945ffd83dbSDimitry Andric       MI->setFlag(MachineInstr::MIFlag::NoMerge);
8955ffd83dbSDimitry Andric     }
8965ffd83dbSDimitry Andric 
897*bdd1243dSDimitry Andric     if (MDNode *MD = DAG->getPCSections(Node))
898*bdd1243dSDimitry Andric       MI->setPCSections(MF, MD);
899*bdd1243dSDimitry Andric 
9000b57cec5SDimitry Andric     return MI;
9010b57cec5SDimitry Andric   };
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   // If this is the first BB, emit byval parameter dbg_value's.
9040b57cec5SDimitry Andric   if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
9050b57cec5SDimitry Andric     SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
9060b57cec5SDimitry Andric     SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
9070b57cec5SDimitry Andric     for (; PDI != PDE; ++PDI) {
9080b57cec5SDimitry Andric       MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
9090b57cec5SDimitry Andric       if (DbgMI) {
9100b57cec5SDimitry Andric         BB->insert(InsertPos, DbgMI);
9110b57cec5SDimitry Andric         // We re-emit the dbg_value closer to its use, too, after instructions
9120b57cec5SDimitry Andric         // are emitted to the BB.
9130b57cec5SDimitry Andric         (*PDI)->clearIsEmitted();
9140b57cec5SDimitry Andric       }
9150b57cec5SDimitry Andric     }
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
9180eae32dcSDimitry Andric   for (SUnit *SU : Sequence) {
9190b57cec5SDimitry Andric     if (!SU) {
9200b57cec5SDimitry Andric       // Null SUnit* is a noop.
9210b57cec5SDimitry Andric       TII->insertNoop(*Emitter.getBlock(), InsertPos);
9220b57cec5SDimitry Andric       continue;
9230b57cec5SDimitry Andric     }
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric     // For pre-regalloc scheduling, create instructions corresponding to the
9260b57cec5SDimitry Andric     // SDNode and any glued SDNodes and append them to the block.
9270b57cec5SDimitry Andric     if (!SU->getNode()) {
9280b57cec5SDimitry Andric       // Emit a copy.
9290b57cec5SDimitry Andric       EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
9300b57cec5SDimitry Andric       continue;
9310b57cec5SDimitry Andric     }
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric     SmallVector<SDNode *, 4> GluedNodes;
9340b57cec5SDimitry Andric     for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
9350b57cec5SDimitry Andric       GluedNodes.push_back(N);
9360b57cec5SDimitry Andric     while (!GluedNodes.empty()) {
9370b57cec5SDimitry Andric       SDNode *N = GluedNodes.back();
9380b57cec5SDimitry Andric       auto NewInsn = EmitNode(N, SU->OrigNode != SU, SU->isCloned, VRBaseMap);
9390b57cec5SDimitry Andric       // Remember the source order of the inserted instruction.
9400b57cec5SDimitry Andric       if (HasDbg)
9410b57cec5SDimitry Andric         ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen, NewInsn);
9420b57cec5SDimitry Andric 
943480093f4SDimitry Andric       if (MDNode *MD = DAG->getHeapAllocSite(N))
9440b57cec5SDimitry Andric         if (NewInsn && NewInsn->isCall())
945480093f4SDimitry Andric           NewInsn->setHeapAllocMarker(MF, MD);
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric       GluedNodes.pop_back();
9480b57cec5SDimitry Andric     }
9490b57cec5SDimitry Andric     auto NewInsn =
9500b57cec5SDimitry Andric         EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, VRBaseMap);
9510b57cec5SDimitry Andric     // Remember the source order of the inserted instruction.
9520b57cec5SDimitry Andric     if (HasDbg)
9530b57cec5SDimitry Andric       ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, Seen,
9540b57cec5SDimitry Andric                         NewInsn);
955480093f4SDimitry Andric 
9560b57cec5SDimitry Andric     if (MDNode *MD = DAG->getHeapAllocSite(SU->getNode())) {
9570b57cec5SDimitry Andric       if (NewInsn && NewInsn->isCall())
958480093f4SDimitry Andric         NewInsn->setHeapAllocMarker(MF, MD);
9590b57cec5SDimitry Andric     }
9600b57cec5SDimitry Andric   }
9610b57cec5SDimitry Andric 
9620b57cec5SDimitry Andric   // Insert all the dbg_values which have not already been inserted in source
9630b57cec5SDimitry Andric   // order sequence.
9640b57cec5SDimitry Andric   if (HasDbg) {
9650b57cec5SDimitry Andric     MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric     // Sort the source order instructions and use the order to insert debug
9680b57cec5SDimitry Andric     // values. Use stable_sort so that DBG_VALUEs are inserted in the same order
9690b57cec5SDimitry Andric     // regardless of the host's implementation fo std::sort.
9700b57cec5SDimitry Andric     llvm::stable_sort(Orders, less_first());
9710b57cec5SDimitry Andric     std::stable_sort(DAG->DbgBegin(), DAG->DbgEnd(),
9720b57cec5SDimitry Andric                      [](const SDDbgValue *LHS, const SDDbgValue *RHS) {
9730b57cec5SDimitry Andric                        return LHS->getOrder() < RHS->getOrder();
9740b57cec5SDimitry Andric                      });
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric     SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
9770b57cec5SDimitry Andric     SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
9780b57cec5SDimitry Andric     // Now emit the rest according to source order.
9790b57cec5SDimitry Andric     unsigned LastOrder = 0;
9800b57cec5SDimitry Andric     for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
9810b57cec5SDimitry Andric       unsigned Order = Orders[i].first;
9820b57cec5SDimitry Andric       MachineInstr *MI = Orders[i].second;
9830b57cec5SDimitry Andric       // Insert all SDDbgValue's whose order(s) are before "Order".
9840b57cec5SDimitry Andric       assert(MI);
9850b57cec5SDimitry Andric       for (; DI != DE; ++DI) {
9860b57cec5SDimitry Andric         if ((*DI)->getOrder() < LastOrder || (*DI)->getOrder() >= Order)
9870b57cec5SDimitry Andric           break;
9880b57cec5SDimitry Andric         if ((*DI)->isEmitted())
9890b57cec5SDimitry Andric           continue;
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric         MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
9920b57cec5SDimitry Andric         if (DbgMI) {
9930b57cec5SDimitry Andric           if (!LastOrder)
9940b57cec5SDimitry Andric             // Insert to start of the BB (after PHIs).
9950b57cec5SDimitry Andric             BB->insert(BBBegin, DbgMI);
9960b57cec5SDimitry Andric           else {
9970b57cec5SDimitry Andric             // Insert at the instruction, which may be in a different
9980b57cec5SDimitry Andric             // block, if the block was split by a custom inserter.
9990b57cec5SDimitry Andric             MachineBasicBlock::iterator Pos = MI;
10000b57cec5SDimitry Andric             MI->getParent()->insert(Pos, DbgMI);
10010b57cec5SDimitry Andric           }
10020b57cec5SDimitry Andric         }
10030b57cec5SDimitry Andric       }
10040b57cec5SDimitry Andric       LastOrder = Order;
10050b57cec5SDimitry Andric     }
10060b57cec5SDimitry Andric     // Add trailing DbgValue's before the terminator. FIXME: May want to add
10070b57cec5SDimitry Andric     // some of them before one or more conditional branches?
10080b57cec5SDimitry Andric     SmallVector<MachineInstr*, 8> DbgMIs;
10090b57cec5SDimitry Andric     for (; DI != DE; ++DI) {
10100b57cec5SDimitry Andric       if ((*DI)->isEmitted())
10110b57cec5SDimitry Andric         continue;
10120b57cec5SDimitry Andric       assert((*DI)->getOrder() >= LastOrder &&
10130b57cec5SDimitry Andric              "emitting DBG_VALUE out of order");
10140b57cec5SDimitry Andric       if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
10150b57cec5SDimitry Andric         DbgMIs.push_back(DbgMI);
10160b57cec5SDimitry Andric     }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric     MachineBasicBlock *InsertBB = Emitter.getBlock();
10190b57cec5SDimitry Andric     MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
10200b57cec5SDimitry Andric     InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric     SDDbgInfo::DbgLabelIterator DLI = DAG->DbgLabelBegin();
10230b57cec5SDimitry Andric     SDDbgInfo::DbgLabelIterator DLE = DAG->DbgLabelEnd();
10240b57cec5SDimitry Andric     // Now emit the rest according to source order.
10250b57cec5SDimitry Andric     LastOrder = 0;
10260b57cec5SDimitry Andric     for (const auto &InstrOrder : Orders) {
10270b57cec5SDimitry Andric       unsigned Order = InstrOrder.first;
10280b57cec5SDimitry Andric       MachineInstr *MI = InstrOrder.second;
10290b57cec5SDimitry Andric       if (!MI)
10300b57cec5SDimitry Andric         continue;
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric       // Insert all SDDbgLabel's whose order(s) are before "Order".
10330b57cec5SDimitry Andric       for (; DLI != DLE &&
10340b57cec5SDimitry Andric              (*DLI)->getOrder() >= LastOrder && (*DLI)->getOrder() < Order;
10350b57cec5SDimitry Andric              ++DLI) {
10360b57cec5SDimitry Andric         MachineInstr *DbgMI = Emitter.EmitDbgLabel(*DLI);
10370b57cec5SDimitry Andric         if (DbgMI) {
10380b57cec5SDimitry Andric           if (!LastOrder)
10390b57cec5SDimitry Andric             // Insert to start of the BB (after PHIs).
10400b57cec5SDimitry Andric             BB->insert(BBBegin, DbgMI);
10410b57cec5SDimitry Andric           else {
10420b57cec5SDimitry Andric             // Insert at the instruction, which may be in a different
10430b57cec5SDimitry Andric             // block, if the block was split by a custom inserter.
10440b57cec5SDimitry Andric             MachineBasicBlock::iterator Pos = MI;
10450b57cec5SDimitry Andric             MI->getParent()->insert(Pos, DbgMI);
10460b57cec5SDimitry Andric           }
10470b57cec5SDimitry Andric         }
10480b57cec5SDimitry Andric       }
10490b57cec5SDimitry Andric       if (DLI == DLE)
10500b57cec5SDimitry Andric         break;
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric       LastOrder = Order;
10530b57cec5SDimitry Andric     }
10540b57cec5SDimitry Andric   }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   InsertPos = Emitter.getInsertPos();
1057e8d8bef9SDimitry Andric   // In some cases, DBG_VALUEs might be inserted after the first terminator,
1058e8d8bef9SDimitry Andric   // which results in an invalid MBB. If that happens, move the DBG_VALUEs
1059e8d8bef9SDimitry Andric   // before the first terminator.
1060e8d8bef9SDimitry Andric   MachineBasicBlock *InsertBB = Emitter.getBlock();
1061e8d8bef9SDimitry Andric   auto FirstTerm = InsertBB->getFirstTerminator();
1062e8d8bef9SDimitry Andric   if (FirstTerm != InsertBB->end()) {
1063e8d8bef9SDimitry Andric     assert(!FirstTerm->isDebugValue() &&
1064e8d8bef9SDimitry Andric            "first terminator cannot be a debug value");
1065e8d8bef9SDimitry Andric     for (MachineInstr &MI : make_early_inc_range(
1066e8d8bef9SDimitry Andric              make_range(std::next(FirstTerm), InsertBB->end()))) {
106704eeddc0SDimitry Andric       // Only scan up to insertion point.
106804eeddc0SDimitry Andric       if (&MI == InsertPos)
106904eeddc0SDimitry Andric         break;
107004eeddc0SDimitry Andric 
1071e8d8bef9SDimitry Andric       if (!MI.isDebugValue())
1072e8d8bef9SDimitry Andric         continue;
1073e8d8bef9SDimitry Andric 
1074e8d8bef9SDimitry Andric       // The DBG_VALUE was referencing a value produced by a terminator. By
1075e8d8bef9SDimitry Andric       // moving the DBG_VALUE, the referenced value also needs invalidating.
1076e8d8bef9SDimitry Andric       MI.getOperand(0).ChangeToRegister(0, false);
1077e8d8bef9SDimitry Andric       MI.moveBefore(&*FirstTerm);
1078e8d8bef9SDimitry Andric     }
1079e8d8bef9SDimitry Andric   }
1080e8d8bef9SDimitry Andric   return InsertBB;
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric /// Return the basic block label.
10840b57cec5SDimitry Andric std::string ScheduleDAGSDNodes::getDAGName() const {
10850b57cec5SDimitry Andric   return "sunit-dag." + BB->getFullName();
10860b57cec5SDimitry Andric }
1087