xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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)
500b57cec5SDimitry Andric     : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
510b57cec5SDimitry Andric       InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric /// Run - perform scheduling.
540b57cec5SDimitry Andric ///
550b57cec5SDimitry Andric void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
560b57cec5SDimitry Andric   BB = bb;
570b57cec5SDimitry Andric   DAG = dag;
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric   // Clear the scheduler's SUnit DAG.
600b57cec5SDimitry Andric   ScheduleDAG::clearDAG();
610b57cec5SDimitry Andric   Sequence.clear();
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric   // Invoke the target's selection of scheduler.
640b57cec5SDimitry Andric   Schedule();
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// NewSUnit - Creates a new SUnit and return a ptr to it.
680b57cec5SDimitry Andric ///
690b57cec5SDimitry Andric SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
700b57cec5SDimitry Andric #ifndef NDEBUG
710b57cec5SDimitry Andric   const SUnit *Addr = nullptr;
720b57cec5SDimitry Andric   if (!SUnits.empty())
730b57cec5SDimitry Andric     Addr = &SUnits[0];
740b57cec5SDimitry Andric #endif
750b57cec5SDimitry Andric   SUnits.emplace_back(N, (unsigned)SUnits.size());
760b57cec5SDimitry Andric   assert((Addr == nullptr || Addr == &SUnits[0]) &&
770b57cec5SDimitry Andric          "SUnits std::vector reallocated on the fly!");
780b57cec5SDimitry Andric   SUnits.back().OrigNode = &SUnits.back();
790b57cec5SDimitry Andric   SUnit *SU = &SUnits.back();
800b57cec5SDimitry Andric   const TargetLowering &TLI = DAG->getTargetLoweringInfo();
810b57cec5SDimitry Andric   if (!N ||
820b57cec5SDimitry Andric       (N->isMachineOpcode() &&
830b57cec5SDimitry Andric        N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
840b57cec5SDimitry Andric     SU->SchedulingPref = Sched::None;
850b57cec5SDimitry Andric   else
860b57cec5SDimitry Andric     SU->SchedulingPref = TLI.getSchedulingPreference(N);
870b57cec5SDimitry Andric   return SU;
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
910b57cec5SDimitry Andric   SUnit *SU = newSUnit(Old->getNode());
920b57cec5SDimitry Andric   SU->OrigNode = Old->OrigNode;
930b57cec5SDimitry Andric   SU->Latency = Old->Latency;
940b57cec5SDimitry Andric   SU->isVRegCycle = Old->isVRegCycle;
950b57cec5SDimitry Andric   SU->isCall = Old->isCall;
960b57cec5SDimitry Andric   SU->isCallOp = Old->isCallOp;
970b57cec5SDimitry Andric   SU->isTwoAddress = Old->isTwoAddress;
980b57cec5SDimitry Andric   SU->isCommutable = Old->isCommutable;
990b57cec5SDimitry Andric   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
1000b57cec5SDimitry Andric   SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
1010b57cec5SDimitry Andric   SU->isScheduleHigh = Old->isScheduleHigh;
1020b57cec5SDimitry Andric   SU->isScheduleLow = Old->isScheduleLow;
1030b57cec5SDimitry Andric   SU->SchedulingPref = Old->SchedulingPref;
1040b57cec5SDimitry Andric   Old->isCloned = true;
1050b57cec5SDimitry Andric   return SU;
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric /// CheckForPhysRegDependency - Check if the dependency between def and use of
1090b57cec5SDimitry Andric /// a specified operand is a physical register dependency. If so, returns the
1100b57cec5SDimitry Andric /// register and the cost of copying the register.
1110b57cec5SDimitry Andric static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
1120b57cec5SDimitry Andric                                       const TargetRegisterInfo *TRI,
1130b57cec5SDimitry Andric                                       const TargetInstrInfo *TII,
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();
1198bcb0991SDimitry Andric   if (Register::isVirtualRegister(Reg))
1200b57cec5SDimitry Andric     return;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   unsigned ResNo = User->getOperand(2).getResNo();
1230b57cec5SDimitry Andric   if (Def->getOpcode() == ISD::CopyFromReg &&
1240b57cec5SDimitry Andric       cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
1250b57cec5SDimitry Andric     PhysReg = Reg;
1260b57cec5SDimitry Andric   } else if (Def->isMachineOpcode()) {
1270b57cec5SDimitry Andric     const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
128*e8d8bef9SDimitry Andric     if (ResNo >= II.getNumDefs() && II.hasImplicitDefOfPhysReg(Reg))
1290b57cec5SDimitry Andric       PhysReg = Reg;
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   if (PhysReg != 0) {
1330b57cec5SDimitry Andric     const TargetRegisterClass *RC =
1340b57cec5SDimitry Andric         TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
1350b57cec5SDimitry Andric     Cost = RC->getCopyCost();
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric // Helper for AddGlue to clone node operands.
1400b57cec5SDimitry Andric static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
1410b57cec5SDimitry Andric                                 SDValue ExtraOper = SDValue()) {
1420b57cec5SDimitry Andric   SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
1430b57cec5SDimitry Andric   if (ExtraOper.getNode())
1440b57cec5SDimitry Andric     Ops.push_back(ExtraOper);
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   SDVTList VTList = DAG->getVTList(VTs);
1470b57cec5SDimitry Andric   MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   // Store memory references.
1500b57cec5SDimitry Andric   SmallVector<MachineMemOperand *, 2> MMOs;
1510b57cec5SDimitry Andric   if (MN)
1520b57cec5SDimitry Andric     MMOs.assign(MN->memoperands_begin(), MN->memoperands_end());
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   // Reset the memory references
1570b57cec5SDimitry Andric   if (MN)
1580b57cec5SDimitry Andric     DAG->setNodeMemRefs(MN, MMOs);
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
1620b57cec5SDimitry Andric   SDNode *GlueDestNode = Glue.getNode();
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // Don't add glue from a node to itself.
1650b57cec5SDimitry Andric   if (GlueDestNode == N) return false;
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric   // Don't add a glue operand to something that already uses glue.
1680b57cec5SDimitry Andric   if (GlueDestNode &&
1690b57cec5SDimitry Andric       N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
1700b57cec5SDimitry Andric     return false;
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric   // Don't add glue to something that already has a glue value.
1730b57cec5SDimitry Andric   if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
1740b57cec5SDimitry Andric 
175*e8d8bef9SDimitry Andric   SmallVector<EVT, 4> VTs(N->values());
1760b57cec5SDimitry Andric   if (AddGlue)
1770b57cec5SDimitry Andric     VTs.push_back(MVT::Glue);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   CloneNodeWithValues(N, DAG, VTs, Glue);
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   return true;
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric // Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
1850b57cec5SDimitry Andric // node even though simply shrinking the value list is sufficient.
1860b57cec5SDimitry Andric static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
1870b57cec5SDimitry Andric   assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
1880b57cec5SDimitry Andric           !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
1890b57cec5SDimitry Andric          "expected an unused glue value");
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   CloneNodeWithValues(N, DAG,
1920b57cec5SDimitry Andric                       makeArrayRef(N->value_begin(), N->getNumValues() - 1));
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
1960b57cec5SDimitry Andric /// This function finds loads of the same base and different offsets. If the
1970b57cec5SDimitry Andric /// offsets are not far apart (target specific), it add MVT::Glue inputs and
1980b57cec5SDimitry Andric /// outputs to ensure they are scheduled together and in order. This
1990b57cec5SDimitry Andric /// optimization may benefit some targets by improving cache locality.
2000b57cec5SDimitry Andric void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
2015ffd83dbSDimitry Andric   SDValue Chain;
2020b57cec5SDimitry Andric   unsigned NumOps = Node->getNumOperands();
2030b57cec5SDimitry Andric   if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
2045ffd83dbSDimitry Andric     Chain = Node->getOperand(NumOps-1);
2050b57cec5SDimitry Andric   if (!Chain)
2060b57cec5SDimitry Andric     return;
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   // Skip any load instruction that has a tied input. There may be an additional
2090b57cec5SDimitry Andric   // dependency requiring a different order than by increasing offsets, and the
2100b57cec5SDimitry Andric   // added glue may introduce a cycle.
2110b57cec5SDimitry Andric   auto hasTiedInput = [this](const SDNode *N) {
2120b57cec5SDimitry Andric     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
2130b57cec5SDimitry Andric     for (unsigned I = 0; I != MCID.getNumOperands(); ++I) {
2140b57cec5SDimitry Andric       if (MCID.getOperandConstraint(I, MCOI::TIED_TO) != -1)
2150b57cec5SDimitry Andric         return true;
2160b57cec5SDimitry Andric     }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     return false;
2190b57cec5SDimitry Andric   };
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // Look for other loads of the same chain. Find loads that are loading from
2220b57cec5SDimitry Andric   // the same base pointer and different offsets.
2230b57cec5SDimitry Andric   SmallPtrSet<SDNode*, 16> Visited;
2240b57cec5SDimitry Andric   SmallVector<int64_t, 4> Offsets;
2250b57cec5SDimitry Andric   DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
2260b57cec5SDimitry Andric   bool Cluster = false;
2270b57cec5SDimitry Andric   SDNode *Base = Node;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   if (hasTiedInput(Base))
2300b57cec5SDimitry Andric     return;
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   // This algorithm requires a reasonably low use count before finding a match
2330b57cec5SDimitry Andric   // to avoid uselessly blowing up compile time in large blocks.
2340b57cec5SDimitry Andric   unsigned UseCount = 0;
2350b57cec5SDimitry Andric   for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
2360b57cec5SDimitry Andric        I != E && UseCount < 100; ++I, ++UseCount) {
2375ffd83dbSDimitry Andric     if (I.getUse().getResNo() != Chain.getResNo())
2385ffd83dbSDimitry Andric       continue;
2395ffd83dbSDimitry Andric 
2400b57cec5SDimitry Andric     SDNode *User = *I;
2410b57cec5SDimitry Andric     if (User == Node || !Visited.insert(User).second)
2420b57cec5SDimitry Andric       continue;
2430b57cec5SDimitry Andric     int64_t Offset1, Offset2;
2440b57cec5SDimitry Andric     if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
2450b57cec5SDimitry Andric         Offset1 == Offset2 ||
2460b57cec5SDimitry Andric         hasTiedInput(User)) {
2470b57cec5SDimitry Andric       // FIXME: Should be ok if they addresses are identical. But earlier
2480b57cec5SDimitry Andric       // optimizations really should have eliminated one of the loads.
2490b57cec5SDimitry Andric       continue;
2500b57cec5SDimitry Andric     }
2510b57cec5SDimitry Andric     if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
2520b57cec5SDimitry Andric       Offsets.push_back(Offset1);
2530b57cec5SDimitry Andric     O2SMap.insert(std::make_pair(Offset2, User));
2540b57cec5SDimitry Andric     Offsets.push_back(Offset2);
2550b57cec5SDimitry Andric     if (Offset2 < Offset1)
2560b57cec5SDimitry Andric       Base = User;
2570b57cec5SDimitry Andric     Cluster = true;
2580b57cec5SDimitry Andric     // Reset UseCount to allow more matches.
2590b57cec5SDimitry Andric     UseCount = 0;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   if (!Cluster)
2630b57cec5SDimitry Andric     return;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   // Sort them in increasing order.
2660b57cec5SDimitry Andric   llvm::sort(Offsets);
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   // Check if the loads are close enough.
2690b57cec5SDimitry Andric   SmallVector<SDNode*, 4> Loads;
2700b57cec5SDimitry Andric   unsigned NumLoads = 0;
2710b57cec5SDimitry Andric   int64_t BaseOff = Offsets[0];
2720b57cec5SDimitry Andric   SDNode *BaseLoad = O2SMap[BaseOff];
2730b57cec5SDimitry Andric   Loads.push_back(BaseLoad);
2740b57cec5SDimitry Andric   for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
2750b57cec5SDimitry Andric     int64_t Offset = Offsets[i];
2760b57cec5SDimitry Andric     SDNode *Load = O2SMap[Offset];
2770b57cec5SDimitry Andric     if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
2780b57cec5SDimitry Andric       break; // Stop right here. Ignore loads that are further away.
2790b57cec5SDimitry Andric     Loads.push_back(Load);
2800b57cec5SDimitry Andric     ++NumLoads;
2810b57cec5SDimitry Andric   }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   if (NumLoads == 0)
2840b57cec5SDimitry Andric     return;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   // Cluster loads by adding MVT::Glue outputs and inputs. This also
2870b57cec5SDimitry Andric   // ensure they are scheduled in order of increasing addresses.
2880b57cec5SDimitry Andric   SDNode *Lead = Loads[0];
2890b57cec5SDimitry Andric   SDValue InGlue = SDValue(nullptr, 0);
2900b57cec5SDimitry Andric   if (AddGlue(Lead, InGlue, true, DAG))
2910b57cec5SDimitry Andric     InGlue = SDValue(Lead, Lead->getNumValues() - 1);
2920b57cec5SDimitry Andric   for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
2930b57cec5SDimitry Andric     bool OutGlue = I < E - 1;
2940b57cec5SDimitry Andric     SDNode *Load = Loads[I];
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric     // If AddGlue fails, we could leave an unsused glue value. This should not
2970b57cec5SDimitry Andric     // cause any
2980b57cec5SDimitry Andric     if (AddGlue(Load, InGlue, OutGlue, DAG)) {
2990b57cec5SDimitry Andric       if (OutGlue)
3000b57cec5SDimitry Andric         InGlue = SDValue(Load, Load->getNumValues() - 1);
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric       ++LoadsClustered;
3030b57cec5SDimitry Andric     }
3040b57cec5SDimitry Andric     else if (!OutGlue && InGlue.getNode())
3050b57cec5SDimitry Andric       RemoveUnusedGlue(InGlue.getNode(), DAG);
3060b57cec5SDimitry Andric   }
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric /// ClusterNodes - Cluster certain nodes which should be scheduled together.
3100b57cec5SDimitry Andric ///
3110b57cec5SDimitry Andric void ScheduleDAGSDNodes::ClusterNodes() {
3120b57cec5SDimitry Andric   for (SDNode &NI : DAG->allnodes()) {
3130b57cec5SDimitry Andric     SDNode *Node = &NI;
3140b57cec5SDimitry Andric     if (!Node || !Node->isMachineOpcode())
3150b57cec5SDimitry Andric       continue;
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric     unsigned Opc = Node->getMachineOpcode();
3180b57cec5SDimitry Andric     const MCInstrDesc &MCID = TII->get(Opc);
3190b57cec5SDimitry Andric     if (MCID.mayLoad())
3200b57cec5SDimitry Andric       // Cluster loads from "near" addresses into combined SUnits.
3210b57cec5SDimitry Andric       ClusterNeighboringLoads(Node);
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric void ScheduleDAGSDNodes::BuildSchedUnits() {
3260b57cec5SDimitry Andric   // During scheduling, the NodeId field of SDNode is used to map SDNodes
3270b57cec5SDimitry Andric   // to their associated SUnits by holding SUnits table indices. A value
3280b57cec5SDimitry Andric   // of -1 means the SDNode does not yet have an associated SUnit.
3290b57cec5SDimitry Andric   unsigned NumNodes = 0;
3300b57cec5SDimitry Andric   for (SDNode &NI : DAG->allnodes()) {
3310b57cec5SDimitry Andric     NI.setNodeId(-1);
3320b57cec5SDimitry Andric     ++NumNodes;
3330b57cec5SDimitry Andric   }
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric   // Reserve entries in the vector for each of the SUnits we are creating.  This
3360b57cec5SDimitry Andric   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
3370b57cec5SDimitry Andric   // invalidated.
3380b57cec5SDimitry Andric   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
3390b57cec5SDimitry Andric   // This is a temporary workaround.
3400b57cec5SDimitry Andric   SUnits.reserve(NumNodes * 2);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   // Add all nodes in depth first order.
3430b57cec5SDimitry Andric   SmallVector<SDNode*, 64> Worklist;
3440b57cec5SDimitry Andric   SmallPtrSet<SDNode*, 32> Visited;
3450b57cec5SDimitry Andric   Worklist.push_back(DAG->getRoot().getNode());
3460b57cec5SDimitry Andric   Visited.insert(DAG->getRoot().getNode());
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   SmallVector<SUnit*, 8> CallSUnits;
3490b57cec5SDimitry Andric   while (!Worklist.empty()) {
3500b57cec5SDimitry Andric     SDNode *NI = Worklist.pop_back_val();
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     // Add all operands to the worklist unless they've already been added.
3530b57cec5SDimitry Andric     for (const SDValue &Op : NI->op_values())
3540b57cec5SDimitry Andric       if (Visited.insert(Op.getNode()).second)
3550b57cec5SDimitry Andric         Worklist.push_back(Op.getNode());
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
3580b57cec5SDimitry Andric       continue;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     // If this node has already been processed, stop now.
3610b57cec5SDimitry Andric     if (NI->getNodeId() != -1) continue;
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     SUnit *NodeSUnit = newSUnit(NI);
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric     // See if anything is glued to this node, if so, add them to glued
3660b57cec5SDimitry Andric     // nodes.  Nodes can have at most one glue input and one glue output.  Glue
3670b57cec5SDimitry Andric     // is required to be the last operand and result of a node.
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric     // Scan up to find glued preds.
3700b57cec5SDimitry Andric     SDNode *N = NI;
3710b57cec5SDimitry Andric     while (N->getNumOperands() &&
3720b57cec5SDimitry Andric            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
3730b57cec5SDimitry Andric       N = N->getOperand(N->getNumOperands()-1).getNode();
3740b57cec5SDimitry Andric       assert(N->getNodeId() == -1 && "Node already inserted!");
3750b57cec5SDimitry Andric       N->setNodeId(NodeSUnit->NodeNum);
3760b57cec5SDimitry Andric       if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
3770b57cec5SDimitry Andric         NodeSUnit->isCall = true;
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     // Scan down to find any glued succs.
3810b57cec5SDimitry Andric     N = NI;
3820b57cec5SDimitry Andric     while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
3830b57cec5SDimitry Andric       SDValue GlueVal(N, N->getNumValues()-1);
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric       // There are either zero or one users of the Glue result.
3860b57cec5SDimitry Andric       bool HasGlueUse = false;
3870b57cec5SDimitry Andric       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
3880b57cec5SDimitry Andric            UI != E; ++UI)
3890b57cec5SDimitry Andric         if (GlueVal.isOperandOf(*UI)) {
3900b57cec5SDimitry Andric           HasGlueUse = true;
3910b57cec5SDimitry Andric           assert(N->getNodeId() == -1 && "Node already inserted!");
3920b57cec5SDimitry Andric           N->setNodeId(NodeSUnit->NodeNum);
3930b57cec5SDimitry Andric           N = *UI;
3940b57cec5SDimitry Andric           if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
3950b57cec5SDimitry Andric             NodeSUnit->isCall = true;
3960b57cec5SDimitry Andric           break;
3970b57cec5SDimitry Andric         }
3980b57cec5SDimitry Andric       if (!HasGlueUse) break;
3990b57cec5SDimitry Andric     }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric     if (NodeSUnit->isCall)
4020b57cec5SDimitry Andric       CallSUnits.push_back(NodeSUnit);
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     // Schedule zero-latency TokenFactor below any nodes that may increase the
4050b57cec5SDimitry Andric     // schedule height. Otherwise, ancestors of the TokenFactor may appear to
4060b57cec5SDimitry Andric     // have false stalls.
4070b57cec5SDimitry Andric     if (NI->getOpcode() == ISD::TokenFactor)
4080b57cec5SDimitry Andric       NodeSUnit->isScheduleLow = true;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric     // If there are glue operands involved, N is now the bottom-most node
4110b57cec5SDimitry Andric     // of the sequence of nodes that are glued together.
4120b57cec5SDimitry Andric     // Update the SUnit.
4130b57cec5SDimitry Andric     NodeSUnit->setNode(N);
4140b57cec5SDimitry Andric     assert(N->getNodeId() == -1 && "Node already inserted!");
4150b57cec5SDimitry Andric     N->setNodeId(NodeSUnit->NodeNum);
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric     // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
4180b57cec5SDimitry Andric     InitNumRegDefsLeft(NodeSUnit);
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric     // Assign the Latency field of NodeSUnit using target-provided information.
4210b57cec5SDimitry Andric     computeLatency(NodeSUnit);
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   // Find all call operands.
4250b57cec5SDimitry Andric   while (!CallSUnits.empty()) {
4260b57cec5SDimitry Andric     SUnit *SU = CallSUnits.pop_back_val();
4270b57cec5SDimitry Andric     for (const SDNode *SUNode = SU->getNode(); SUNode;
4280b57cec5SDimitry Andric          SUNode = SUNode->getGluedNode()) {
4290b57cec5SDimitry Andric       if (SUNode->getOpcode() != ISD::CopyToReg)
4300b57cec5SDimitry Andric         continue;
4310b57cec5SDimitry Andric       SDNode *SrcN = SUNode->getOperand(2).getNode();
4320b57cec5SDimitry Andric       if (isPassiveNode(SrcN)) continue;   // Not scheduled.
4330b57cec5SDimitry Andric       SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
4340b57cec5SDimitry Andric       SrcSU->isCallOp = true;
4350b57cec5SDimitry Andric     }
4360b57cec5SDimitry Andric   }
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric void ScheduleDAGSDNodes::AddSchedEdges() {
4400b57cec5SDimitry Andric   const TargetSubtargetInfo &ST = MF.getSubtarget();
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
4430b57cec5SDimitry Andric   bool UnitLatencies = forceUnitLatencies();
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   // Pass 2: add the preds, succs, etc.
4460b57cec5SDimitry Andric   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
4470b57cec5SDimitry Andric     SUnit *SU = &SUnits[su];
4480b57cec5SDimitry Andric     SDNode *MainNode = SU->getNode();
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric     if (MainNode->isMachineOpcode()) {
4510b57cec5SDimitry Andric       unsigned Opc = MainNode->getMachineOpcode();
4520b57cec5SDimitry Andric       const MCInstrDesc &MCID = TII->get(Opc);
4530b57cec5SDimitry Andric       for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
4540b57cec5SDimitry Andric         if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
4550b57cec5SDimitry Andric           SU->isTwoAddress = true;
4560b57cec5SDimitry Andric           break;
4570b57cec5SDimitry Andric         }
4580b57cec5SDimitry Andric       }
4590b57cec5SDimitry Andric       if (MCID.isCommutable())
4600b57cec5SDimitry Andric         SU->isCommutable = true;
4610b57cec5SDimitry Andric     }
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric     // Find all predecessors and successors of the group.
4640b57cec5SDimitry Andric     for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
4650b57cec5SDimitry Andric       if (N->isMachineOpcode() &&
4660b57cec5SDimitry Andric           TII->get(N->getMachineOpcode()).getImplicitDefs()) {
4670b57cec5SDimitry Andric         SU->hasPhysRegClobbers = true;
4680b57cec5SDimitry Andric         unsigned NumUsed = InstrEmitter::CountResults(N);
4690b57cec5SDimitry Andric         while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
4700b57cec5SDimitry Andric           --NumUsed;    // Skip over unused values at the end.
4710b57cec5SDimitry Andric         if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
4720b57cec5SDimitry Andric           SU->hasPhysRegDefs = true;
4730b57cec5SDimitry Andric       }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4760b57cec5SDimitry Andric         SDNode *OpN = N->getOperand(i).getNode();
4775ffd83dbSDimitry Andric         unsigned DefIdx = N->getOperand(i).getResNo();
4780b57cec5SDimitry Andric         if (isPassiveNode(OpN)) continue;   // Not scheduled.
4790b57cec5SDimitry Andric         SUnit *OpSU = &SUnits[OpN->getNodeId()];
4800b57cec5SDimitry Andric         assert(OpSU && "Node has no SUnit!");
4810b57cec5SDimitry Andric         if (OpSU == SU) continue;           // In the same group.
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric         EVT OpVT = N->getOperand(i).getValueType();
4840b57cec5SDimitry Andric         assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
4850b57cec5SDimitry Andric         bool isChain = OpVT == MVT::Other;
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric         unsigned PhysReg = 0;
4880b57cec5SDimitry Andric         int Cost = 1;
4890b57cec5SDimitry Andric         // Determine if this is a physical register dependency.
4900b57cec5SDimitry Andric         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
4910b57cec5SDimitry Andric         assert((PhysReg == 0 || !isChain) &&
4920b57cec5SDimitry Andric                "Chain dependence via physreg data?");
4930b57cec5SDimitry Andric         // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
4940b57cec5SDimitry Andric         // emits a copy from the physical register to a virtual register unless
4950b57cec5SDimitry Andric         // it requires a cross class copy (cost < 0). That means we are only
4960b57cec5SDimitry Andric         // treating "expensive to copy" register dependency as physical register
4970b57cec5SDimitry Andric         // dependency. This may change in the future though.
4980b57cec5SDimitry Andric         if (Cost >= 0 && !StressSched)
4990b57cec5SDimitry Andric           PhysReg = 0;
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric         // If this is a ctrl dep, latency is 1.
5020b57cec5SDimitry Andric         unsigned OpLatency = isChain ? 1 : OpSU->Latency;
5030b57cec5SDimitry Andric         // Special-case TokenFactor chains as zero-latency.
5040b57cec5SDimitry Andric         if(isChain && OpN->getOpcode() == ISD::TokenFactor)
5050b57cec5SDimitry Andric           OpLatency = 0;
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric         SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
5080b57cec5SDimitry Andric           : SDep(OpSU, SDep::Data, PhysReg);
5090b57cec5SDimitry Andric         Dep.setLatency(OpLatency);
5100b57cec5SDimitry Andric         if (!isChain && !UnitLatencies) {
5110b57cec5SDimitry Andric           computeOperandLatency(OpN, N, i, Dep);
5125ffd83dbSDimitry Andric           ST.adjustSchedDependency(OpSU, DefIdx, SU, i, Dep);
5130b57cec5SDimitry Andric         }
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric         if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
5160b57cec5SDimitry Andric           // Multiple register uses are combined in the same SUnit. For example,
5170b57cec5SDimitry Andric           // we could have a set of glued nodes with all their defs consumed by
5180b57cec5SDimitry Andric           // another set of glued nodes. Register pressure tracking sees this as
5190b57cec5SDimitry Andric           // a single use, so to keep pressure balanced we reduce the defs.
5200b57cec5SDimitry Andric           //
5210b57cec5SDimitry Andric           // We can't tell (without more book-keeping) if this results from
5220b57cec5SDimitry Andric           // glued nodes or duplicate operands. As long as we don't reduce
5230b57cec5SDimitry Andric           // NumRegDefsLeft to zero, we handle the common cases well.
5240b57cec5SDimitry Andric           --OpSU->NumRegDefsLeft;
5250b57cec5SDimitry Andric         }
5260b57cec5SDimitry Andric       }
5270b57cec5SDimitry Andric     }
5280b57cec5SDimitry Andric   }
5290b57cec5SDimitry Andric }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
5320b57cec5SDimitry Andric /// are input.  This SUnit graph is similar to the SelectionDAG, but
5330b57cec5SDimitry Andric /// excludes nodes that aren't interesting to scheduling, and represents
5340b57cec5SDimitry Andric /// glued together nodes with a single SUnit.
5358bcb0991SDimitry Andric void ScheduleDAGSDNodes::BuildSchedGraph(AAResults *AA) {
5360b57cec5SDimitry Andric   // Cluster certain nodes which should be scheduled together.
5370b57cec5SDimitry Andric   ClusterNodes();
5380b57cec5SDimitry Andric   // Populate the SUnits array.
5390b57cec5SDimitry Andric   BuildSchedUnits();
5400b57cec5SDimitry Andric   // Compute all the scheduling dependencies between nodes.
5410b57cec5SDimitry Andric   AddSchedEdges();
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric // Initialize NumNodeDefs for the current Node's opcode.
5450b57cec5SDimitry Andric void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
5460b57cec5SDimitry Andric   // Check for phys reg copy.
5470b57cec5SDimitry Andric   if (!Node)
5480b57cec5SDimitry Andric     return;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   if (!Node->isMachineOpcode()) {
5510b57cec5SDimitry Andric     if (Node->getOpcode() == ISD::CopyFromReg)
5520b57cec5SDimitry Andric       NodeNumDefs = 1;
5530b57cec5SDimitry Andric     else
5540b57cec5SDimitry Andric       NodeNumDefs = 0;
5550b57cec5SDimitry Andric     return;
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric   unsigned POpc = Node->getMachineOpcode();
5580b57cec5SDimitry Andric   if (POpc == TargetOpcode::IMPLICIT_DEF) {
5590b57cec5SDimitry Andric     // No register need be allocated for this.
5600b57cec5SDimitry Andric     NodeNumDefs = 0;
5610b57cec5SDimitry Andric     return;
5620b57cec5SDimitry Andric   }
5630b57cec5SDimitry Andric   if (POpc == TargetOpcode::PATCHPOINT &&
5640b57cec5SDimitry Andric       Node->getValueType(0) == MVT::Other) {
5650b57cec5SDimitry Andric     // PATCHPOINT is defined to have one result, but it might really have none
5660b57cec5SDimitry Andric     // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
5670b57cec5SDimitry Andric     // real definition.
5680b57cec5SDimitry Andric     NodeNumDefs = 0;
5690b57cec5SDimitry Andric     return;
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric   unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
5720b57cec5SDimitry Andric   // Some instructions define regs that are not represented in the selection DAG
5730b57cec5SDimitry Andric   // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
5740b57cec5SDimitry Andric   NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
5750b57cec5SDimitry Andric   DefIdx = 0;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric // Construct a RegDefIter for this SUnit and find the first valid value.
5790b57cec5SDimitry Andric ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
5800b57cec5SDimitry Andric                                            const ScheduleDAGSDNodes *SD)
5810b57cec5SDimitry Andric   : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
5820b57cec5SDimitry Andric   InitNodeNumDefs();
5830b57cec5SDimitry Andric   Advance();
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric // Advance to the next valid value defined by the SUnit.
5870b57cec5SDimitry Andric void ScheduleDAGSDNodes::RegDefIter::Advance() {
5880b57cec5SDimitry Andric   for (;Node;) { // Visit all glued nodes.
5890b57cec5SDimitry Andric     for (;DefIdx < NodeNumDefs; ++DefIdx) {
5900b57cec5SDimitry Andric       if (!Node->hasAnyUseOfValue(DefIdx))
5910b57cec5SDimitry Andric         continue;
5920b57cec5SDimitry Andric       ValueType = Node->getSimpleValueType(DefIdx);
5930b57cec5SDimitry Andric       ++DefIdx;
5940b57cec5SDimitry Andric       return; // Found a normal regdef.
5950b57cec5SDimitry Andric     }
5960b57cec5SDimitry Andric     Node = Node->getGluedNode();
5970b57cec5SDimitry Andric     if (!Node) {
5980b57cec5SDimitry Andric       return; // No values left to visit.
5990b57cec5SDimitry Andric     }
6000b57cec5SDimitry Andric     InitNodeNumDefs();
6010b57cec5SDimitry Andric   }
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
6050b57cec5SDimitry Andric   assert(SU->NumRegDefsLeft == 0 && "expect a new node");
6060b57cec5SDimitry Andric   for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
6070b57cec5SDimitry Andric     assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
6080b57cec5SDimitry Andric     ++SU->NumRegDefsLeft;
6090b57cec5SDimitry Andric   }
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
6130b57cec5SDimitry Andric   SDNode *N = SU->getNode();
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   // TokenFactor operands are considered zero latency, and some schedulers
6160b57cec5SDimitry Andric   // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
6170b57cec5SDimitry Andric   // whenever node latency is nonzero.
6180b57cec5SDimitry Andric   if (N && N->getOpcode() == ISD::TokenFactor) {
6190b57cec5SDimitry Andric     SU->Latency = 0;
6200b57cec5SDimitry Andric     return;
6210b57cec5SDimitry Andric   }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
6240b57cec5SDimitry Andric   if (forceUnitLatencies()) {
6250b57cec5SDimitry Andric     SU->Latency = 1;
6260b57cec5SDimitry Andric     return;
6270b57cec5SDimitry Andric   }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   if (!InstrItins || InstrItins->isEmpty()) {
6300b57cec5SDimitry Andric     if (N && N->isMachineOpcode() &&
6310b57cec5SDimitry Andric         TII->isHighLatencyDef(N->getMachineOpcode()))
6320b57cec5SDimitry Andric       SU->Latency = HighLatencyCycles;
6330b57cec5SDimitry Andric     else
6340b57cec5SDimitry Andric       SU->Latency = 1;
6350b57cec5SDimitry Andric     return;
6360b57cec5SDimitry Andric   }
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   // Compute the latency for the node.  We use the sum of the latencies for
6390b57cec5SDimitry Andric   // all nodes glued together into this SUnit.
6400b57cec5SDimitry Andric   SU->Latency = 0;
6410b57cec5SDimitry Andric   for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
6420b57cec5SDimitry Andric     if (N->isMachineOpcode())
6430b57cec5SDimitry Andric       SU->Latency += TII->getInstrLatency(InstrItins, N);
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
6470b57cec5SDimitry Andric                                                unsigned OpIdx, SDep& dep) const{
6480b57cec5SDimitry Andric   // Check to see if the scheduler cares about latencies.
6490b57cec5SDimitry Andric   if (forceUnitLatencies())
6500b57cec5SDimitry Andric     return;
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   if (dep.getKind() != SDep::Data)
6530b57cec5SDimitry Andric     return;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
6560b57cec5SDimitry Andric   if (Use->isMachineOpcode())
6570b57cec5SDimitry Andric     // Adjust the use operand index by num of defs.
6580b57cec5SDimitry Andric     OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
6590b57cec5SDimitry Andric   int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
6600b57cec5SDimitry Andric   if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
6610b57cec5SDimitry Andric       !BB->succ_empty()) {
6620b57cec5SDimitry Andric     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
6638bcb0991SDimitry Andric     if (Register::isVirtualRegister(Reg))
6640b57cec5SDimitry Andric       // This copy is a liveout value. It is likely coalesced, so reduce the
6650b57cec5SDimitry Andric       // latency so not to penalize the def.
6660b57cec5SDimitry Andric       // FIXME: need target specific adjustment here?
6670b57cec5SDimitry Andric       Latency = (Latency > 1) ? Latency - 1 : 1;
6680b57cec5SDimitry Andric   }
6690b57cec5SDimitry Andric   if (Latency >= 0)
6700b57cec5SDimitry Andric     dep.setLatency(Latency);
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric void ScheduleDAGSDNodes::dumpNode(const SUnit &SU) const {
6740b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6750b57cec5SDimitry Andric   dumpNodeName(SU);
6760b57cec5SDimitry Andric   dbgs() << ": ";
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric   if (!SU.getNode()) {
6790b57cec5SDimitry Andric     dbgs() << "PHYS REG COPY\n";
6800b57cec5SDimitry Andric     return;
6810b57cec5SDimitry Andric   }
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   SU.getNode()->dump(DAG);
6840b57cec5SDimitry Andric   dbgs() << "\n";
6850b57cec5SDimitry Andric   SmallVector<SDNode *, 4> GluedNodes;
6860b57cec5SDimitry Andric   for (SDNode *N = SU.getNode()->getGluedNode(); N; N = N->getGluedNode())
6870b57cec5SDimitry Andric     GluedNodes.push_back(N);
6880b57cec5SDimitry Andric   while (!GluedNodes.empty()) {
6890b57cec5SDimitry Andric     dbgs() << "    ";
6900b57cec5SDimitry Andric     GluedNodes.back()->dump(DAG);
6910b57cec5SDimitry Andric     dbgs() << "\n";
6920b57cec5SDimitry Andric     GluedNodes.pop_back();
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric #endif
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric void ScheduleDAGSDNodes::dump() const {
6980b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6990b57cec5SDimitry Andric   if (EntrySU.getNode() != nullptr)
7000b57cec5SDimitry Andric     dumpNodeAll(EntrySU);
7010b57cec5SDimitry Andric   for (const SUnit &SU : SUnits)
7020b57cec5SDimitry Andric     dumpNodeAll(SU);
7030b57cec5SDimitry Andric   if (ExitSU.getNode() != nullptr)
7040b57cec5SDimitry Andric     dumpNodeAll(ExitSU);
7050b57cec5SDimitry Andric #endif
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7090b57cec5SDimitry Andric void ScheduleDAGSDNodes::dumpSchedule() const {
7100b57cec5SDimitry Andric   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
7110b57cec5SDimitry Andric     if (SUnit *SU = Sequence[i])
7120b57cec5SDimitry Andric       dumpNode(*SU);
7130b57cec5SDimitry Andric     else
7140b57cec5SDimitry Andric       dbgs() << "**** NOOP ****\n";
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric #endif
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric #ifndef NDEBUG
7200b57cec5SDimitry Andric /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
7210b57cec5SDimitry Andric /// their state is consistent with the nodes listed in Sequence.
7220b57cec5SDimitry Andric ///
7230b57cec5SDimitry Andric void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
7240b57cec5SDimitry Andric   unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
7250b57cec5SDimitry Andric   unsigned Noops = 0;
7260b57cec5SDimitry Andric   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
7270b57cec5SDimitry Andric     if (!Sequence[i])
7280b57cec5SDimitry Andric       ++Noops;
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 
7420b57cec5SDimitry Andric   // Opportunistically insert immediate dbg_value uses, i.e. those with the same
7430b57cec5SDimitry Andric   // source order number as N.
7440b57cec5SDimitry Andric   MachineBasicBlock *BB = Emitter.getBlock();
7450b57cec5SDimitry Andric   MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
7460b57cec5SDimitry Andric   for (auto DV : DAG->GetDbgValues(N)) {
7470b57cec5SDimitry Andric     if (DV->isEmitted())
7480b57cec5SDimitry Andric       continue;
7490b57cec5SDimitry Andric     unsigned DVOrder = DV->getOrder();
7500b57cec5SDimitry Andric     if (!Order || DVOrder == Order) {
7510b57cec5SDimitry Andric       MachineInstr *DbgMI = Emitter.EmitDbgValue(DV, VRBaseMap);
7520b57cec5SDimitry Andric       if (DbgMI) {
7530b57cec5SDimitry Andric         Orders.push_back({DVOrder, DbgMI});
7540b57cec5SDimitry Andric         BB->insert(InsertPos, DbgMI);
7550b57cec5SDimitry Andric       }
7560b57cec5SDimitry Andric     }
7570b57cec5SDimitry Andric   }
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric // ProcessSourceNode - Process nodes with source order numbers. These are added
7610b57cec5SDimitry Andric // to a vector which EmitSchedule uses to determine how to insert dbg_value
7620b57cec5SDimitry Andric // instructions in the right order.
7630b57cec5SDimitry Andric static void
7640b57cec5SDimitry Andric ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
7655ffd83dbSDimitry Andric                   DenseMap<SDValue, Register> &VRBaseMap,
7660b57cec5SDimitry Andric                   SmallVectorImpl<std::pair<unsigned, MachineInstr *>> &Orders,
7675ffd83dbSDimitry Andric                   SmallSet<Register, 8> &Seen, MachineInstr *NewInsn) {
7680b57cec5SDimitry Andric   unsigned Order = N->getIROrder();
7690b57cec5SDimitry Andric   if (!Order || Seen.count(Order)) {
7700b57cec5SDimitry Andric     // Process any valid SDDbgValues even if node does not have any order
7710b57cec5SDimitry Andric     // assigned.
7720b57cec5SDimitry Andric     ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
7730b57cec5SDimitry Andric     return;
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   // If a new instruction was generated for this Order number, record it.
7770b57cec5SDimitry Andric   // Otherwise, leave this order number unseen: we will either find later
7780b57cec5SDimitry Andric   // instructions for it, or leave it unseen if there were no instructions at
7790b57cec5SDimitry Andric   // all.
7800b57cec5SDimitry Andric   if (NewInsn) {
7810b57cec5SDimitry Andric     Seen.insert(Order);
7820b57cec5SDimitry Andric     Orders.push_back({Order, NewInsn});
7830b57cec5SDimitry Andric   }
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   // Even if no instruction was generated, a Value may have become defined via
7860b57cec5SDimitry Andric   // earlier nodes. Try to process them now.
7870b57cec5SDimitry Andric   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric void ScheduleDAGSDNodes::
7915ffd83dbSDimitry Andric EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, Register> &VRBaseMap,
7920b57cec5SDimitry Andric                 MachineBasicBlock::iterator InsertPos) {
7930b57cec5SDimitry Andric   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
7940b57cec5SDimitry Andric        I != E; ++I) {
7950b57cec5SDimitry Andric     if (I->isCtrl()) continue;  // ignore chain preds
7960b57cec5SDimitry Andric     if (I->getSUnit()->CopyDstRC) {
7970b57cec5SDimitry Andric       // Copy to physical register.
7985ffd83dbSDimitry Andric       DenseMap<SUnit*, Register>::iterator VRI = VRBaseMap.find(I->getSUnit());
7990b57cec5SDimitry Andric       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
8000b57cec5SDimitry Andric       // Find the destination physical register.
8015ffd83dbSDimitry Andric       Register Reg;
8020b57cec5SDimitry Andric       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
8030b57cec5SDimitry Andric              EE = SU->Succs.end(); II != EE; ++II) {
8040b57cec5SDimitry Andric         if (II->isCtrl()) continue;  // ignore chain preds
8050b57cec5SDimitry Andric         if (II->getReg()) {
8060b57cec5SDimitry Andric           Reg = II->getReg();
8070b57cec5SDimitry Andric           break;
8080b57cec5SDimitry Andric         }
8090b57cec5SDimitry Andric       }
8100b57cec5SDimitry Andric       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
8110b57cec5SDimitry Andric         .addReg(VRI->second);
8120b57cec5SDimitry Andric     } else {
8130b57cec5SDimitry Andric       // Copy from physical register.
8140b57cec5SDimitry Andric       assert(I->getReg() && "Unknown physical register!");
8158bcb0991SDimitry Andric       Register VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
8160b57cec5SDimitry Andric       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
8170b57cec5SDimitry Andric       (void)isNew; // Silence compiler warning.
8180b57cec5SDimitry Andric       assert(isNew && "Node emitted out of order - early");
8190b57cec5SDimitry Andric       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
8200b57cec5SDimitry Andric         .addReg(I->getReg());
8210b57cec5SDimitry Andric     }
8220b57cec5SDimitry Andric     break;
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric /// EmitSchedule - Emit the machine code in scheduled order. Return the new
8270b57cec5SDimitry Andric /// InsertPos and MachineBasicBlock that contains this insertion
8280b57cec5SDimitry Andric /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
8290b57cec5SDimitry Andric /// not necessarily refer to returned BB. The emitter may split blocks.
8300b57cec5SDimitry Andric MachineBasicBlock *ScheduleDAGSDNodes::
8310b57cec5SDimitry Andric EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
832*e8d8bef9SDimitry Andric   InstrEmitter Emitter(DAG->getTarget(), BB, InsertPos);
8335ffd83dbSDimitry Andric   DenseMap<SDValue, Register> VRBaseMap;
8345ffd83dbSDimitry Andric   DenseMap<SUnit*, Register> CopyVRBaseMap;
8350b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
8365ffd83dbSDimitry Andric   SmallSet<Register, 8> Seen;
8370b57cec5SDimitry Andric   bool HasDbg = DAG->hasDebugValues();
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // Emit a node, and determine where its first instruction is for debuginfo.
8400b57cec5SDimitry Andric   // Zero, one, or multiple instructions can be created when emitting a node.
8410b57cec5SDimitry Andric   auto EmitNode =
8420b57cec5SDimitry Andric       [&](SDNode *Node, bool IsClone, bool IsCloned,
8435ffd83dbSDimitry Andric           DenseMap<SDValue, Register> &VRBaseMap) -> MachineInstr * {
8440b57cec5SDimitry Andric     // Fetch instruction prior to this, or end() if nonexistant.
8450b57cec5SDimitry Andric     auto GetPrevInsn = [&](MachineBasicBlock::iterator I) {
8460b57cec5SDimitry Andric       if (I == BB->begin())
8470b57cec5SDimitry Andric         return BB->end();
8480b57cec5SDimitry Andric       else
8490b57cec5SDimitry Andric         return std::prev(Emitter.getInsertPos());
8500b57cec5SDimitry Andric     };
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric     MachineBasicBlock::iterator Before = GetPrevInsn(Emitter.getInsertPos());
8530b57cec5SDimitry Andric     Emitter.EmitNode(Node, IsClone, IsCloned, VRBaseMap);
8540b57cec5SDimitry Andric     MachineBasicBlock::iterator After = GetPrevInsn(Emitter.getInsertPos());
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric     // If the iterator did not change, no instructions were inserted.
8570b57cec5SDimitry Andric     if (Before == After)
8580b57cec5SDimitry Andric       return nullptr;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric     MachineInstr *MI;
8610b57cec5SDimitry Andric     if (Before == BB->end()) {
8620b57cec5SDimitry Andric       // There were no prior instructions; the new ones must start at the
8630b57cec5SDimitry Andric       // beginning of the block.
8640b57cec5SDimitry Andric       MI = &Emitter.getBlock()->instr_front();
8650b57cec5SDimitry Andric     } else {
8660b57cec5SDimitry Andric       // Return first instruction after the pre-existing instructions.
8670b57cec5SDimitry Andric       MI = &*std::next(Before);
8680b57cec5SDimitry Andric     }
8690b57cec5SDimitry Andric 
8705ffd83dbSDimitry Andric     if (MI->isCandidateForCallSiteEntry() &&
8715ffd83dbSDimitry Andric         DAG->getTarget().Options.EmitCallSiteInfo)
8720b57cec5SDimitry Andric       MF.addCallArgsForwardingRegs(MI, DAG->getSDCallSiteInfo(Node));
8730b57cec5SDimitry Andric 
8745ffd83dbSDimitry Andric     if (DAG->getNoMergeSiteInfo(Node)) {
8755ffd83dbSDimitry Andric       MI->setFlag(MachineInstr::MIFlag::NoMerge);
8765ffd83dbSDimitry Andric     }
8775ffd83dbSDimitry Andric 
8780b57cec5SDimitry Andric     return MI;
8790b57cec5SDimitry Andric   };
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   // If this is the first BB, emit byval parameter dbg_value's.
8820b57cec5SDimitry Andric   if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
8830b57cec5SDimitry Andric     SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
8840b57cec5SDimitry Andric     SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
8850b57cec5SDimitry Andric     for (; PDI != PDE; ++PDI) {
8860b57cec5SDimitry Andric       MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
8870b57cec5SDimitry Andric       if (DbgMI) {
8880b57cec5SDimitry Andric         BB->insert(InsertPos, DbgMI);
8890b57cec5SDimitry Andric         // We re-emit the dbg_value closer to its use, too, after instructions
8900b57cec5SDimitry Andric         // are emitted to the BB.
8910b57cec5SDimitry Andric         (*PDI)->clearIsEmitted();
8920b57cec5SDimitry Andric       }
8930b57cec5SDimitry Andric     }
8940b57cec5SDimitry Andric   }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
8970b57cec5SDimitry Andric     SUnit *SU = Sequence[i];
8980b57cec5SDimitry Andric     if (!SU) {
8990b57cec5SDimitry Andric       // Null SUnit* is a noop.
9000b57cec5SDimitry Andric       TII->insertNoop(*Emitter.getBlock(), InsertPos);
9010b57cec5SDimitry Andric       continue;
9020b57cec5SDimitry Andric     }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric     // For pre-regalloc scheduling, create instructions corresponding to the
9050b57cec5SDimitry Andric     // SDNode and any glued SDNodes and append them to the block.
9060b57cec5SDimitry Andric     if (!SU->getNode()) {
9070b57cec5SDimitry Andric       // Emit a copy.
9080b57cec5SDimitry Andric       EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
9090b57cec5SDimitry Andric       continue;
9100b57cec5SDimitry Andric     }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric     SmallVector<SDNode *, 4> GluedNodes;
9130b57cec5SDimitry Andric     for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
9140b57cec5SDimitry Andric       GluedNodes.push_back(N);
9150b57cec5SDimitry Andric     while (!GluedNodes.empty()) {
9160b57cec5SDimitry Andric       SDNode *N = GluedNodes.back();
9170b57cec5SDimitry Andric       auto NewInsn = EmitNode(N, SU->OrigNode != SU, SU->isCloned, VRBaseMap);
9180b57cec5SDimitry Andric       // Remember the source order of the inserted instruction.
9190b57cec5SDimitry Andric       if (HasDbg)
9200b57cec5SDimitry Andric         ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen, NewInsn);
9210b57cec5SDimitry Andric 
922480093f4SDimitry Andric       if (MDNode *MD = DAG->getHeapAllocSite(N))
9230b57cec5SDimitry Andric         if (NewInsn && NewInsn->isCall())
924480093f4SDimitry Andric           NewInsn->setHeapAllocMarker(MF, MD);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric       GluedNodes.pop_back();
9270b57cec5SDimitry Andric     }
9280b57cec5SDimitry Andric     auto NewInsn =
9290b57cec5SDimitry Andric         EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, VRBaseMap);
9300b57cec5SDimitry Andric     // Remember the source order of the inserted instruction.
9310b57cec5SDimitry Andric     if (HasDbg)
9320b57cec5SDimitry Andric       ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, Seen,
9330b57cec5SDimitry Andric                         NewInsn);
934480093f4SDimitry Andric 
9350b57cec5SDimitry Andric     if (MDNode *MD = DAG->getHeapAllocSite(SU->getNode())) {
9360b57cec5SDimitry Andric       if (NewInsn && NewInsn->isCall())
937480093f4SDimitry Andric         NewInsn->setHeapAllocMarker(MF, MD);
9380b57cec5SDimitry Andric     }
9390b57cec5SDimitry Andric   }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // Insert all the dbg_values which have not already been inserted in source
9420b57cec5SDimitry Andric   // order sequence.
9430b57cec5SDimitry Andric   if (HasDbg) {
9440b57cec5SDimitry Andric     MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric     // Sort the source order instructions and use the order to insert debug
9470b57cec5SDimitry Andric     // values. Use stable_sort so that DBG_VALUEs are inserted in the same order
9480b57cec5SDimitry Andric     // regardless of the host's implementation fo std::sort.
9490b57cec5SDimitry Andric     llvm::stable_sort(Orders, less_first());
9500b57cec5SDimitry Andric     std::stable_sort(DAG->DbgBegin(), DAG->DbgEnd(),
9510b57cec5SDimitry Andric                      [](const SDDbgValue *LHS, const SDDbgValue *RHS) {
9520b57cec5SDimitry Andric                        return LHS->getOrder() < RHS->getOrder();
9530b57cec5SDimitry Andric                      });
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric     SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
9560b57cec5SDimitry Andric     SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
9570b57cec5SDimitry Andric     // Now emit the rest according to source order.
9580b57cec5SDimitry Andric     unsigned LastOrder = 0;
9590b57cec5SDimitry Andric     for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
9600b57cec5SDimitry Andric       unsigned Order = Orders[i].first;
9610b57cec5SDimitry Andric       MachineInstr *MI = Orders[i].second;
9620b57cec5SDimitry Andric       // Insert all SDDbgValue's whose order(s) are before "Order".
9630b57cec5SDimitry Andric       assert(MI);
9640b57cec5SDimitry Andric       for (; DI != DE; ++DI) {
9650b57cec5SDimitry Andric         if ((*DI)->getOrder() < LastOrder || (*DI)->getOrder() >= Order)
9660b57cec5SDimitry Andric           break;
9670b57cec5SDimitry Andric         if ((*DI)->isEmitted())
9680b57cec5SDimitry Andric           continue;
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric         MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
9710b57cec5SDimitry Andric         if (DbgMI) {
9720b57cec5SDimitry Andric           if (!LastOrder)
9730b57cec5SDimitry Andric             // Insert to start of the BB (after PHIs).
9740b57cec5SDimitry Andric             BB->insert(BBBegin, DbgMI);
9750b57cec5SDimitry Andric           else {
9760b57cec5SDimitry Andric             // Insert at the instruction, which may be in a different
9770b57cec5SDimitry Andric             // block, if the block was split by a custom inserter.
9780b57cec5SDimitry Andric             MachineBasicBlock::iterator Pos = MI;
9790b57cec5SDimitry Andric             MI->getParent()->insert(Pos, DbgMI);
9800b57cec5SDimitry Andric           }
9810b57cec5SDimitry Andric         }
9820b57cec5SDimitry Andric       }
9830b57cec5SDimitry Andric       LastOrder = Order;
9840b57cec5SDimitry Andric     }
9850b57cec5SDimitry Andric     // Add trailing DbgValue's before the terminator. FIXME: May want to add
9860b57cec5SDimitry Andric     // some of them before one or more conditional branches?
9870b57cec5SDimitry Andric     SmallVector<MachineInstr*, 8> DbgMIs;
9880b57cec5SDimitry Andric     for (; DI != DE; ++DI) {
9890b57cec5SDimitry Andric       if ((*DI)->isEmitted())
9900b57cec5SDimitry Andric         continue;
9910b57cec5SDimitry Andric       assert((*DI)->getOrder() >= LastOrder &&
9920b57cec5SDimitry Andric              "emitting DBG_VALUE out of order");
9930b57cec5SDimitry Andric       if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
9940b57cec5SDimitry Andric         DbgMIs.push_back(DbgMI);
9950b57cec5SDimitry Andric     }
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric     MachineBasicBlock *InsertBB = Emitter.getBlock();
9980b57cec5SDimitry Andric     MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
9990b57cec5SDimitry Andric     InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric     SDDbgInfo::DbgLabelIterator DLI = DAG->DbgLabelBegin();
10020b57cec5SDimitry Andric     SDDbgInfo::DbgLabelIterator DLE = DAG->DbgLabelEnd();
10030b57cec5SDimitry Andric     // Now emit the rest according to source order.
10040b57cec5SDimitry Andric     LastOrder = 0;
10050b57cec5SDimitry Andric     for (const auto &InstrOrder : Orders) {
10060b57cec5SDimitry Andric       unsigned Order = InstrOrder.first;
10070b57cec5SDimitry Andric       MachineInstr *MI = InstrOrder.second;
10080b57cec5SDimitry Andric       if (!MI)
10090b57cec5SDimitry Andric         continue;
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric       // Insert all SDDbgLabel's whose order(s) are before "Order".
10120b57cec5SDimitry Andric       for (; DLI != DLE &&
10130b57cec5SDimitry Andric              (*DLI)->getOrder() >= LastOrder && (*DLI)->getOrder() < Order;
10140b57cec5SDimitry Andric              ++DLI) {
10150b57cec5SDimitry Andric         MachineInstr *DbgMI = Emitter.EmitDbgLabel(*DLI);
10160b57cec5SDimitry Andric         if (DbgMI) {
10170b57cec5SDimitry Andric           if (!LastOrder)
10180b57cec5SDimitry Andric             // Insert to start of the BB (after PHIs).
10190b57cec5SDimitry Andric             BB->insert(BBBegin, DbgMI);
10200b57cec5SDimitry Andric           else {
10210b57cec5SDimitry Andric             // Insert at the instruction, which may be in a different
10220b57cec5SDimitry Andric             // block, if the block was split by a custom inserter.
10230b57cec5SDimitry Andric             MachineBasicBlock::iterator Pos = MI;
10240b57cec5SDimitry Andric             MI->getParent()->insert(Pos, DbgMI);
10250b57cec5SDimitry Andric           }
10260b57cec5SDimitry Andric         }
10270b57cec5SDimitry Andric       }
10280b57cec5SDimitry Andric       if (DLI == DLE)
10290b57cec5SDimitry Andric         break;
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric       LastOrder = Order;
10320b57cec5SDimitry Andric     }
10330b57cec5SDimitry Andric   }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   InsertPos = Emitter.getInsertPos();
1036*e8d8bef9SDimitry Andric   // In some cases, DBG_VALUEs might be inserted after the first terminator,
1037*e8d8bef9SDimitry Andric   // which results in an invalid MBB. If that happens, move the DBG_VALUEs
1038*e8d8bef9SDimitry Andric   // before the first terminator.
1039*e8d8bef9SDimitry Andric   MachineBasicBlock *InsertBB = Emitter.getBlock();
1040*e8d8bef9SDimitry Andric   auto FirstTerm = InsertBB->getFirstTerminator();
1041*e8d8bef9SDimitry Andric   if (FirstTerm != InsertBB->end()) {
1042*e8d8bef9SDimitry Andric     assert(!FirstTerm->isDebugValue() &&
1043*e8d8bef9SDimitry Andric            "first terminator cannot be a debug value");
1044*e8d8bef9SDimitry Andric     for (MachineInstr &MI : make_early_inc_range(
1045*e8d8bef9SDimitry Andric              make_range(std::next(FirstTerm), InsertBB->end()))) {
1046*e8d8bef9SDimitry Andric       if (!MI.isDebugValue())
1047*e8d8bef9SDimitry Andric         continue;
1048*e8d8bef9SDimitry Andric 
1049*e8d8bef9SDimitry Andric       if (&MI == InsertPos)
1050*e8d8bef9SDimitry Andric         InsertPos = std::prev(InsertPos->getIterator());
1051*e8d8bef9SDimitry Andric 
1052*e8d8bef9SDimitry Andric       // The DBG_VALUE was referencing a value produced by a terminator. By
1053*e8d8bef9SDimitry Andric       // moving the DBG_VALUE, the referenced value also needs invalidating.
1054*e8d8bef9SDimitry Andric       MI.getOperand(0).ChangeToRegister(0, false);
1055*e8d8bef9SDimitry Andric       MI.moveBefore(&*FirstTerm);
1056*e8d8bef9SDimitry Andric     }
1057*e8d8bef9SDimitry Andric   }
1058*e8d8bef9SDimitry Andric   return InsertBB;
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric /// Return the basic block label.
10620b57cec5SDimitry Andric std::string ScheduleDAGSDNodes::getDAGName() const {
10630b57cec5SDimitry Andric   return "sunit-dag." + BB->getFullName();
10640b57cec5SDimitry Andric }
1065