LLVM  mainline
ScheduleDAGRRList.cpp
Go to the documentation of this file.
00001 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements bottom-up and top-down register pressure reduction list
00011 // schedulers, using standard algorithms.  The basic approach uses a priority
00012 // queue of available nodes to schedule.  One at a time, nodes are taken from
00013 // the priority queue (thus in priority order), checked for legality to
00014 // schedule, and emitted if legal.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/CodeGen/SchedulerRegistry.h"
00019 #include "ScheduleDAGSDNodes.h"
00020 #include "llvm/ADT/STLExtras.h"
00021 #include "llvm/ADT/SmallSet.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00025 #include "llvm/CodeGen/SelectionDAGISel.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/InlineAsm.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetLowering.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <climits>
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "pre-RA-sched"
00039 
00040 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
00041 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
00042 STATISTIC(NumDups,       "Number of duplicated nodes");
00043 STATISTIC(NumPRCopies,   "Number of physical register copies");
00044 
00045 static RegisterScheduler
00046   burrListDAGScheduler("list-burr",
00047                        "Bottom-up register reduction list scheduling",
00048                        createBURRListDAGScheduler);
00049 static RegisterScheduler
00050   sourceListDAGScheduler("source",
00051                          "Similar to list-burr but schedules in source "
00052                          "order when possible",
00053                          createSourceListDAGScheduler);
00054 
00055 static RegisterScheduler
00056   hybridListDAGScheduler("list-hybrid",
00057                          "Bottom-up register pressure aware list scheduling "
00058                          "which tries to balance latency and register pressure",
00059                          createHybridListDAGScheduler);
00060 
00061 static RegisterScheduler
00062   ILPListDAGScheduler("list-ilp",
00063                       "Bottom-up register pressure aware list scheduling "
00064                       "which tries to balance ILP and register pressure",
00065                       createILPListDAGScheduler);
00066 
00067 static cl::opt<bool> DisableSchedCycles(
00068   "disable-sched-cycles", cl::Hidden, cl::init(false),
00069   cl::desc("Disable cycle-level precision during preRA scheduling"));
00070 
00071 // Temporary sched=list-ilp flags until the heuristics are robust.
00072 // Some options are also available under sched=list-hybrid.
00073 static cl::opt<bool> DisableSchedRegPressure(
00074   "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
00075   cl::desc("Disable regpressure priority in sched=list-ilp"));
00076 static cl::opt<bool> DisableSchedLiveUses(
00077   "disable-sched-live-uses", cl::Hidden, cl::init(true),
00078   cl::desc("Disable live use priority in sched=list-ilp"));
00079 static cl::opt<bool> DisableSchedVRegCycle(
00080   "disable-sched-vrcycle", cl::Hidden, cl::init(false),
00081   cl::desc("Disable virtual register cycle interference checks"));
00082 static cl::opt<bool> DisableSchedPhysRegJoin(
00083   "disable-sched-physreg-join", cl::Hidden, cl::init(false),
00084   cl::desc("Disable physreg def-use affinity"));
00085 static cl::opt<bool> DisableSchedStalls(
00086   "disable-sched-stalls", cl::Hidden, cl::init(true),
00087   cl::desc("Disable no-stall priority in sched=list-ilp"));
00088 static cl::opt<bool> DisableSchedCriticalPath(
00089   "disable-sched-critical-path", cl::Hidden, cl::init(false),
00090   cl::desc("Disable critical path priority in sched=list-ilp"));
00091 static cl::opt<bool> DisableSchedHeight(
00092   "disable-sched-height", cl::Hidden, cl::init(false),
00093   cl::desc("Disable scheduled-height priority in sched=list-ilp"));
00094 static cl::opt<bool> Disable2AddrHack(
00095   "disable-2addr-hack", cl::Hidden, cl::init(true),
00096   cl::desc("Disable scheduler's two-address hack"));
00097 
00098 static cl::opt<int> MaxReorderWindow(
00099   "max-sched-reorder", cl::Hidden, cl::init(6),
00100   cl::desc("Number of instructions to allow ahead of the critical path "
00101            "in sched=list-ilp"));
00102 
00103 static cl::opt<unsigned> AvgIPC(
00104   "sched-avg-ipc", cl::Hidden, cl::init(1),
00105   cl::desc("Average inst/cycle whan no target itinerary exists."));
00106 
00107 namespace {
00108 //===----------------------------------------------------------------------===//
00109 /// ScheduleDAGRRList - The actual register reduction list scheduler
00110 /// implementation.  This supports both top-down and bottom-up scheduling.
00111 ///
00112 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
00113 private:
00114   /// NeedLatency - True if the scheduler will make use of latency information.
00115   ///
00116   bool NeedLatency;
00117 
00118   /// AvailableQueue - The priority queue to use for the available SUnits.
00119   SchedulingPriorityQueue *AvailableQueue;
00120 
00121   /// PendingQueue - This contains all of the instructions whose operands have
00122   /// been issued, but their results are not ready yet (due to the latency of
00123   /// the operation).  Once the operands becomes available, the instruction is
00124   /// added to the AvailableQueue.
00125   std::vector<SUnit*> PendingQueue;
00126 
00127   /// HazardRec - The hazard recognizer to use.
00128   ScheduleHazardRecognizer *HazardRec;
00129 
00130   /// CurCycle - The current scheduler state corresponds to this cycle.
00131   unsigned CurCycle;
00132 
00133   /// MinAvailableCycle - Cycle of the soonest available instruction.
00134   unsigned MinAvailableCycle;
00135 
00136   /// IssueCount - Count instructions issued in this cycle
00137   /// Currently valid only for bottom-up scheduling.
00138   unsigned IssueCount;
00139 
00140   /// LiveRegDefs - A set of physical registers and their definition
00141   /// that are "live". These nodes must be scheduled before any other nodes that
00142   /// modifies the registers can be scheduled.
00143   unsigned NumLiveRegs;
00144   std::vector<SUnit*> LiveRegDefs;
00145   std::vector<SUnit*> LiveRegGens;
00146 
00147   // Collect interferences between physical register use/defs.
00148   // Each interference is an SUnit and set of physical registers.
00149   SmallVector<SUnit*, 4> Interferences;
00150   typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT;
00151   LRegsMapT LRegsMap;
00152 
00153   /// Topo - A topological ordering for SUnits which permits fast IsReachable
00154   /// and similar queries.
00155   ScheduleDAGTopologicalSort Topo;
00156 
00157   // Hack to keep track of the inverse of FindCallSeqStart without more crazy
00158   // DAG crawling.
00159   DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
00160 
00161 public:
00162   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
00163                     SchedulingPriorityQueue *availqueue,
00164                     CodeGenOpt::Level OptLevel)
00165     : ScheduleDAGSDNodes(mf),
00166       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
00167       Topo(SUnits, nullptr) {
00168 
00169     const TargetSubtargetInfo &STI = mf.getSubtarget();
00170     if (DisableSchedCycles || !NeedLatency)
00171       HazardRec = new ScheduleHazardRecognizer();
00172     else
00173       HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
00174   }
00175 
00176   ~ScheduleDAGRRList() {
00177     delete HazardRec;
00178     delete AvailableQueue;
00179   }
00180 
00181   void Schedule() override;
00182 
00183   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
00184 
00185   /// IsReachable - Checks if SU is reachable from TargetSU.
00186   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
00187     return Topo.IsReachable(SU, TargetSU);
00188   }
00189 
00190   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
00191   /// create a cycle.
00192   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
00193     return Topo.WillCreateCycle(SU, TargetSU);
00194   }
00195 
00196   /// AddPred - adds a predecessor edge to SUnit SU.
00197   /// This returns true if this is a new predecessor.
00198   /// Updates the topological ordering if required.
00199   void AddPred(SUnit *SU, const SDep &D) {
00200     Topo.AddPred(SU, D.getSUnit());
00201     SU->addPred(D);
00202   }
00203 
00204   /// RemovePred - removes a predecessor edge from SUnit SU.
00205   /// This returns true if an edge was removed.
00206   /// Updates the topological ordering if required.
00207   void RemovePred(SUnit *SU, const SDep &D) {
00208     Topo.RemovePred(SU, D.getSUnit());
00209     SU->removePred(D);
00210   }
00211 
00212 private:
00213   bool isReady(SUnit *SU) {
00214     return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
00215       AvailableQueue->isReady(SU);
00216   }
00217 
00218   void ReleasePred(SUnit *SU, const SDep *PredEdge);
00219   void ReleasePredecessors(SUnit *SU);
00220   void ReleasePending();
00221   void AdvanceToCycle(unsigned NextCycle);
00222   void AdvancePastStalls(SUnit *SU);
00223   void EmitNode(SUnit *SU);
00224   void ScheduleNodeBottomUp(SUnit*);
00225   void CapturePred(SDep *PredEdge);
00226   void UnscheduleNodeBottomUp(SUnit*);
00227   void RestoreHazardCheckerBottomUp();
00228   void BacktrackBottomUp(SUnit*, SUnit*);
00229   SUnit *CopyAndMoveSuccessors(SUnit*);
00230   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
00231                                 const TargetRegisterClass*,
00232                                 const TargetRegisterClass*,
00233                                 SmallVectorImpl<SUnit*>&);
00234   bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
00235 
00236   void releaseInterferences(unsigned Reg = 0);
00237 
00238   SUnit *PickNodeToScheduleBottomUp();
00239   void ListScheduleBottomUp();
00240 
00241   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
00242   /// Updates the topological ordering if required.
00243   SUnit *CreateNewSUnit(SDNode *N) {
00244     unsigned NumSUnits = SUnits.size();
00245     SUnit *NewNode = newSUnit(N);
00246     // Update the topological ordering.
00247     if (NewNode->NodeNum >= NumSUnits)
00248       Topo.InitDAGTopologicalSorting();
00249     return NewNode;
00250   }
00251 
00252   /// CreateClone - Creates a new SUnit from an existing one.
00253   /// Updates the topological ordering if required.
00254   SUnit *CreateClone(SUnit *N) {
00255     unsigned NumSUnits = SUnits.size();
00256     SUnit *NewNode = Clone(N);
00257     // Update the topological ordering.
00258     if (NewNode->NodeNum >= NumSUnits)
00259       Topo.InitDAGTopologicalSorting();
00260     return NewNode;
00261   }
00262 
00263   /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
00264   /// need actual latency information but the hybrid scheduler does.
00265   bool forceUnitLatencies() const override {
00266     return !NeedLatency;
00267   }
00268 };
00269 }  // end anonymous namespace
00270 
00271 /// GetCostForDef - Looks up the register class and cost for a given definition.
00272 /// Typically this just means looking up the representative register class,
00273 /// but for untyped values (MVT::Untyped) it means inspecting the node's
00274 /// opcode to determine what register class is being generated.
00275 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
00276                           const TargetLowering *TLI,
00277                           const TargetInstrInfo *TII,
00278                           const TargetRegisterInfo *TRI,
00279                           unsigned &RegClass, unsigned &Cost,
00280                           const MachineFunction &MF) {
00281   MVT VT = RegDefPos.GetValue();
00282 
00283   // Special handling for untyped values.  These values can only come from
00284   // the expansion of custom DAG-to-DAG patterns.
00285   if (VT == MVT::Untyped) {
00286     const SDNode *Node = RegDefPos.GetNode();
00287 
00288     // Special handling for CopyFromReg of untyped values.
00289     if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
00290       unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
00291       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
00292       RegClass = RC->getID();
00293       Cost = 1;
00294       return;
00295     }
00296 
00297     unsigned Opcode = Node->getMachineOpcode();
00298     if (Opcode == TargetOpcode::REG_SEQUENCE) {
00299       unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
00300       const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
00301       RegClass = RC->getID();
00302       Cost = 1;
00303       return;
00304     }
00305 
00306     unsigned Idx = RegDefPos.GetIdx();
00307     const MCInstrDesc Desc = TII->get(Opcode);
00308     const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
00309     RegClass = RC->getID();
00310     // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
00311     // better way to determine it.
00312     Cost = 1;
00313   } else {
00314     RegClass = TLI->getRepRegClassFor(VT)->getID();
00315     Cost = TLI->getRepRegClassCostFor(VT);
00316   }
00317 }
00318 
00319 /// Schedule - Schedule the DAG using list scheduling.
00320 void ScheduleDAGRRList::Schedule() {
00321   DEBUG(dbgs()
00322         << "********** List Scheduling BB#" << BB->getNumber()
00323         << " '" << BB->getName() << "' **********\n");
00324 
00325   CurCycle = 0;
00326   IssueCount = 0;
00327   MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
00328   NumLiveRegs = 0;
00329   // Allocate slots for each physical register, plus one for a special register
00330   // to track the virtual resource of a calling sequence.
00331   LiveRegDefs.resize(TRI->getNumRegs() + 1, nullptr);
00332   LiveRegGens.resize(TRI->getNumRegs() + 1, nullptr);
00333   CallSeqEndForStart.clear();
00334   assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
00335 
00336   // Build the scheduling graph.
00337   BuildSchedGraph(nullptr);
00338 
00339   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
00340           SUnits[su].dumpAll(this));
00341   Topo.InitDAGTopologicalSorting();
00342 
00343   AvailableQueue->initNodes(SUnits);
00344 
00345   HazardRec->Reset();
00346 
00347   // Execute the actual scheduling loop.
00348   ListScheduleBottomUp();
00349 
00350   AvailableQueue->releaseState();
00351 
00352   DEBUG({
00353       dbgs() << "*** Final schedule ***\n";
00354       dumpSchedule();
00355       dbgs() << '\n';
00356     });
00357 }
00358 
00359 //===----------------------------------------------------------------------===//
00360 //  Bottom-Up Scheduling
00361 //===----------------------------------------------------------------------===//
00362 
00363 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
00364 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
00365 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
00366   SUnit *PredSU = PredEdge->getSUnit();
00367 
00368 #ifndef NDEBUG
00369   if (PredSU->NumSuccsLeft == 0) {
00370     dbgs() << "*** Scheduling failed! ***\n";
00371     PredSU->dump(this);
00372     dbgs() << " has been released too many times!\n";
00373     llvm_unreachable(nullptr);
00374   }
00375 #endif
00376   --PredSU->NumSuccsLeft;
00377 
00378   if (!forceUnitLatencies()) {
00379     // Updating predecessor's height. This is now the cycle when the
00380     // predecessor can be scheduled without causing a pipeline stall.
00381     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
00382   }
00383 
00384   // If all the node's successors are scheduled, this node is ready
00385   // to be scheduled. Ignore the special EntrySU node.
00386   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
00387     PredSU->isAvailable = true;
00388 
00389     unsigned Height = PredSU->getHeight();
00390     if (Height < MinAvailableCycle)
00391       MinAvailableCycle = Height;
00392 
00393     if (isReady(PredSU)) {
00394       AvailableQueue->push(PredSU);
00395     }
00396     // CapturePred and others may have left the node in the pending queue, avoid
00397     // adding it twice.
00398     else if (!PredSU->isPending) {
00399       PredSU->isPending = true;
00400       PendingQueue.push_back(PredSU);
00401     }
00402   }
00403 }
00404 
00405 /// IsChainDependent - Test if Outer is reachable from Inner through
00406 /// chain dependencies.
00407 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
00408                              unsigned NestLevel,
00409                              const TargetInstrInfo *TII) {
00410   SDNode *N = Outer;
00411   for (;;) {
00412     if (N == Inner)
00413       return true;
00414     // For a TokenFactor, examine each operand. There may be multiple ways
00415     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
00416     // most nesting in order to ensure that we find the corresponding match.
00417     if (N->getOpcode() == ISD::TokenFactor) {
00418       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00419         if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
00420           return true;
00421       return false;
00422     }
00423     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
00424     if (N->isMachineOpcode()) {
00425       if (N->getMachineOpcode() ==
00426           (unsigned)TII->getCallFrameDestroyOpcode()) {
00427         ++NestLevel;
00428       } else if (N->getMachineOpcode() ==
00429                  (unsigned)TII->getCallFrameSetupOpcode()) {
00430         if (NestLevel == 0)
00431           return false;
00432         --NestLevel;
00433       }
00434     }
00435     // Otherwise, find the chain and continue climbing.
00436     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00437       if (N->getOperand(i).getValueType() == MVT::Other) {
00438         N = N->getOperand(i).getNode();
00439         goto found_chain_operand;
00440       }
00441     return false;
00442   found_chain_operand:;
00443     if (N->getOpcode() == ISD::EntryToken)
00444       return false;
00445   }
00446 }
00447 
00448 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
00449 /// the corresponding (lowered) CALLSEQ_BEGIN node.
00450 ///
00451 /// NestLevel and MaxNested are used in recursion to indcate the current level
00452 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
00453 /// level seen so far.
00454 ///
00455 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
00456 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
00457 static SDNode *
00458 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
00459                  const TargetInstrInfo *TII) {
00460   for (;;) {
00461     // For a TokenFactor, examine each operand. There may be multiple ways
00462     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
00463     // most nesting in order to ensure that we find the corresponding match.
00464     if (N->getOpcode() == ISD::TokenFactor) {
00465       SDNode *Best = nullptr;
00466       unsigned BestMaxNest = MaxNest;
00467       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00468         unsigned MyNestLevel = NestLevel;
00469         unsigned MyMaxNest = MaxNest;
00470         if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
00471                                            MyNestLevel, MyMaxNest, TII))
00472           if (!Best || (MyMaxNest > BestMaxNest)) {
00473             Best = New;
00474             BestMaxNest = MyMaxNest;
00475           }
00476       }
00477       assert(Best);
00478       MaxNest = BestMaxNest;
00479       return Best;
00480     }
00481     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
00482     if (N->isMachineOpcode()) {
00483       if (N->getMachineOpcode() ==
00484           (unsigned)TII->getCallFrameDestroyOpcode()) {
00485         ++NestLevel;
00486         MaxNest = std::max(MaxNest, NestLevel);
00487       } else if (N->getMachineOpcode() ==
00488                  (unsigned)TII->getCallFrameSetupOpcode()) {
00489         assert(NestLevel != 0);
00490         --NestLevel;
00491         if (NestLevel == 0)
00492           return N;
00493       }
00494     }
00495     // Otherwise, find the chain and continue climbing.
00496     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00497       if (N->getOperand(i).getValueType() == MVT::Other) {
00498         N = N->getOperand(i).getNode();
00499         goto found_chain_operand;
00500       }
00501     return nullptr;
00502   found_chain_operand:;
00503     if (N->getOpcode() == ISD::EntryToken)
00504       return nullptr;
00505   }
00506 }
00507 
00508 /// Call ReleasePred for each predecessor, then update register live def/gen.
00509 /// Always update LiveRegDefs for a register dependence even if the current SU
00510 /// also defines the register. This effectively create one large live range
00511 /// across a sequence of two-address node. This is important because the
00512 /// entire chain must be scheduled together. Example:
00513 ///
00514 /// flags = (3) add
00515 /// flags = (2) addc flags
00516 /// flags = (1) addc flags
00517 ///
00518 /// results in
00519 ///
00520 /// LiveRegDefs[flags] = 3
00521 /// LiveRegGens[flags] = 1
00522 ///
00523 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
00524 /// interference on flags.
00525 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
00526   // Bottom up: release predecessors
00527   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00528        I != E; ++I) {
00529     ReleasePred(SU, &*I);
00530     if (I->isAssignedRegDep()) {
00531       // This is a physical register dependency and it's impossible or
00532       // expensive to copy the register. Make sure nothing that can
00533       // clobber the register is scheduled between the predecessor and
00534       // this node.
00535       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
00536       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
00537              "interference on register dependence");
00538       LiveRegDefs[I->getReg()] = I->getSUnit();
00539       if (!LiveRegGens[I->getReg()]) {
00540         ++NumLiveRegs;
00541         LiveRegGens[I->getReg()] = SU;
00542       }
00543     }
00544   }
00545 
00546   // If we're scheduling a lowered CALLSEQ_END, find the corresponding
00547   // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
00548   // these nodes, to prevent other calls from being interscheduled with them.
00549   unsigned CallResource = TRI->getNumRegs();
00550   if (!LiveRegDefs[CallResource])
00551     for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
00552       if (Node->isMachineOpcode() &&
00553           Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
00554         unsigned NestLevel = 0;
00555         unsigned MaxNest = 0;
00556         SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
00557 
00558         SUnit *Def = &SUnits[N->getNodeId()];
00559         CallSeqEndForStart[Def] = SU;
00560 
00561         ++NumLiveRegs;
00562         LiveRegDefs[CallResource] = Def;
00563         LiveRegGens[CallResource] = SU;
00564         break;
00565       }
00566 }
00567 
00568 /// Check to see if any of the pending instructions are ready to issue.  If
00569 /// so, add them to the available queue.
00570 void ScheduleDAGRRList::ReleasePending() {
00571   if (DisableSchedCycles) {
00572     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
00573     return;
00574   }
00575 
00576   // If the available queue is empty, it is safe to reset MinAvailableCycle.
00577   if (AvailableQueue->empty())
00578     MinAvailableCycle = UINT_MAX;
00579 
00580   // Check to see if any of the pending instructions are ready to issue.  If
00581   // so, add them to the available queue.
00582   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
00583     unsigned ReadyCycle = PendingQueue[i]->getHeight();
00584     if (ReadyCycle < MinAvailableCycle)
00585       MinAvailableCycle = ReadyCycle;
00586 
00587     if (PendingQueue[i]->isAvailable) {
00588       if (!isReady(PendingQueue[i]))
00589           continue;
00590       AvailableQueue->push(PendingQueue[i]);
00591     }
00592     PendingQueue[i]->isPending = false;
00593     PendingQueue[i] = PendingQueue.back();
00594     PendingQueue.pop_back();
00595     --i; --e;
00596   }
00597 }
00598 
00599 /// Move the scheduler state forward by the specified number of Cycles.
00600 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
00601   if (NextCycle <= CurCycle)
00602     return;
00603 
00604   IssueCount = 0;
00605   AvailableQueue->setCurCycle(NextCycle);
00606   if (!HazardRec->isEnabled()) {
00607     // Bypass lots of virtual calls in case of long latency.
00608     CurCycle = NextCycle;
00609   }
00610   else {
00611     for (; CurCycle != NextCycle; ++CurCycle) {
00612       HazardRec->RecedeCycle();
00613     }
00614   }
00615   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
00616   // available Q to release pending nodes at least once before popping.
00617   ReleasePending();
00618 }
00619 
00620 /// Move the scheduler state forward until the specified node's dependents are
00621 /// ready and can be scheduled with no resource conflicts.
00622 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
00623   if (DisableSchedCycles)
00624     return;
00625 
00626   // FIXME: Nodes such as CopyFromReg probably should not advance the current
00627   // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
00628   // has predecessors the cycle will be advanced when they are scheduled.
00629   // But given the crude nature of modeling latency though such nodes, we
00630   // currently need to treat these nodes like real instructions.
00631   // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
00632 
00633   unsigned ReadyCycle = SU->getHeight();
00634 
00635   // Bump CurCycle to account for latency. We assume the latency of other
00636   // available instructions may be hidden by the stall (not a full pipe stall).
00637   // This updates the hazard recognizer's cycle before reserving resources for
00638   // this instruction.
00639   AdvanceToCycle(ReadyCycle);
00640 
00641   // Calls are scheduled in their preceding cycle, so don't conflict with
00642   // hazards from instructions after the call. EmitNode will reset the
00643   // scoreboard state before emitting the call.
00644   if (SU->isCall)
00645     return;
00646 
00647   // FIXME: For resource conflicts in very long non-pipelined stages, we
00648   // should probably skip ahead here to avoid useless scoreboard checks.
00649   int Stalls = 0;
00650   while (true) {
00651     ScheduleHazardRecognizer::HazardType HT =
00652       HazardRec->getHazardType(SU, -Stalls);
00653 
00654     if (HT == ScheduleHazardRecognizer::NoHazard)
00655       break;
00656 
00657     ++Stalls;
00658   }
00659   AdvanceToCycle(CurCycle + Stalls);
00660 }
00661 
00662 /// Record this SUnit in the HazardRecognizer.
00663 /// Does not update CurCycle.
00664 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
00665   if (!HazardRec->isEnabled())
00666     return;
00667 
00668   // Check for phys reg copy.
00669   if (!SU->getNode())
00670     return;
00671 
00672   switch (SU->getNode()->getOpcode()) {
00673   default:
00674     assert(SU->getNode()->isMachineOpcode() &&
00675            "This target-independent node should not be scheduled.");
00676     break;
00677   case ISD::MERGE_VALUES:
00678   case ISD::TokenFactor:
00679   case ISD::LIFETIME_START:
00680   case ISD::LIFETIME_END:
00681   case ISD::CopyToReg:
00682   case ISD::CopyFromReg:
00683   case ISD::EH_LABEL:
00684     // Noops don't affect the scoreboard state. Copies are likely to be
00685     // removed.
00686     return;
00687   case ISD::INLINEASM:
00688     // For inline asm, clear the pipeline state.
00689     HazardRec->Reset();
00690     return;
00691   }
00692   if (SU->isCall) {
00693     // Calls are scheduled with their preceding instructions. For bottom-up
00694     // scheduling, clear the pipeline state before emitting.
00695     HazardRec->Reset();
00696   }
00697 
00698   HazardRec->EmitInstruction(SU);
00699 }
00700 
00701 static void resetVRegCycle(SUnit *SU);
00702 
00703 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
00704 /// count of its predecessors. If a predecessor pending count is zero, add it to
00705 /// the Available queue.
00706 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
00707   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
00708   DEBUG(SU->dump(this));
00709 
00710 #ifndef NDEBUG
00711   if (CurCycle < SU->getHeight())
00712     DEBUG(dbgs() << "   Height [" << SU->getHeight()
00713           << "] pipeline stall!\n");
00714 #endif
00715 
00716   // FIXME: Do not modify node height. It may interfere with
00717   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
00718   // node its ready cycle can aid heuristics, and after scheduling it can
00719   // indicate the scheduled cycle.
00720   SU->setHeightToAtLeast(CurCycle);
00721 
00722   // Reserve resources for the scheduled instruction.
00723   EmitNode(SU);
00724 
00725   Sequence.push_back(SU);
00726 
00727   AvailableQueue->scheduledNode(SU);
00728 
00729   // If HazardRec is disabled, and each inst counts as one cycle, then
00730   // advance CurCycle before ReleasePredecessors to avoid useless pushes to
00731   // PendingQueue for schedulers that implement HasReadyFilter.
00732   if (!HazardRec->isEnabled() && AvgIPC < 2)
00733     AdvanceToCycle(CurCycle + 1);
00734 
00735   // Update liveness of predecessors before successors to avoid treating a
00736   // two-address node as a live range def.
00737   ReleasePredecessors(SU);
00738 
00739   // Release all the implicit physical register defs that are live.
00740   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
00741        I != E; ++I) {
00742     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
00743     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
00744       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00745       --NumLiveRegs;
00746       LiveRegDefs[I->getReg()] = nullptr;
00747       LiveRegGens[I->getReg()] = nullptr;
00748       releaseInterferences(I->getReg());
00749     }
00750   }
00751   // Release the special call resource dependence, if this is the beginning
00752   // of a call.
00753   unsigned CallResource = TRI->getNumRegs();
00754   if (LiveRegDefs[CallResource] == SU)
00755     for (const SDNode *SUNode = SU->getNode(); SUNode;
00756          SUNode = SUNode->getGluedNode()) {
00757       if (SUNode->isMachineOpcode() &&
00758           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
00759         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00760         --NumLiveRegs;
00761         LiveRegDefs[CallResource] = nullptr;
00762         LiveRegGens[CallResource] = nullptr;
00763         releaseInterferences(CallResource);
00764       }
00765     }
00766 
00767   resetVRegCycle(SU);
00768 
00769   SU->isScheduled = true;
00770 
00771   // Conditions under which the scheduler should eagerly advance the cycle:
00772   // (1) No available instructions
00773   // (2) All pipelines full, so available instructions must have hazards.
00774   //
00775   // If HazardRec is disabled, the cycle was pre-advanced before calling
00776   // ReleasePredecessors. In that case, IssueCount should remain 0.
00777   //
00778   // Check AvailableQueue after ReleasePredecessors in case of zero latency.
00779   if (HazardRec->isEnabled() || AvgIPC > 1) {
00780     if (SU->getNode() && SU->getNode()->isMachineOpcode())
00781       ++IssueCount;
00782     if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
00783         || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
00784       AdvanceToCycle(CurCycle + 1);
00785   }
00786 }
00787 
00788 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
00789 /// unscheduled, incrcease the succ left count of its predecessors. Remove
00790 /// them from AvailableQueue if necessary.
00791 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
00792   SUnit *PredSU = PredEdge->getSUnit();
00793   if (PredSU->isAvailable) {
00794     PredSU->isAvailable = false;
00795     if (!PredSU->isPending)
00796       AvailableQueue->remove(PredSU);
00797   }
00798 
00799   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
00800   ++PredSU->NumSuccsLeft;
00801 }
00802 
00803 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
00804 /// its predecessor states to reflect the change.
00805 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
00806   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
00807   DEBUG(SU->dump(this));
00808 
00809   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00810        I != E; ++I) {
00811     CapturePred(&*I);
00812     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
00813       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00814       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
00815              "Physical register dependency violated?");
00816       --NumLiveRegs;
00817       LiveRegDefs[I->getReg()] = nullptr;
00818       LiveRegGens[I->getReg()] = nullptr;
00819       releaseInterferences(I->getReg());
00820     }
00821   }
00822 
00823   // Reclaim the special call resource dependence, if this is the beginning
00824   // of a call.
00825   unsigned CallResource = TRI->getNumRegs();
00826   for (const SDNode *SUNode = SU->getNode(); SUNode;
00827        SUNode = SUNode->getGluedNode()) {
00828     if (SUNode->isMachineOpcode() &&
00829         SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
00830       ++NumLiveRegs;
00831       LiveRegDefs[CallResource] = SU;
00832       LiveRegGens[CallResource] = CallSeqEndForStart[SU];
00833     }
00834   }
00835 
00836   // Release the special call resource dependence, if this is the end
00837   // of a call.
00838   if (LiveRegGens[CallResource] == SU)
00839     for (const SDNode *SUNode = SU->getNode(); SUNode;
00840          SUNode = SUNode->getGluedNode()) {
00841       if (SUNode->isMachineOpcode() &&
00842           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
00843         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00844         --NumLiveRegs;
00845         LiveRegDefs[CallResource] = nullptr;
00846         LiveRegGens[CallResource] = nullptr;
00847         releaseInterferences(CallResource);
00848       }
00849     }
00850 
00851   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
00852        I != E; ++I) {
00853     if (I->isAssignedRegDep()) {
00854       if (!LiveRegDefs[I->getReg()])
00855         ++NumLiveRegs;
00856       // This becomes the nearest def. Note that an earlier def may still be
00857       // pending if this is a two-address node.
00858       LiveRegDefs[I->getReg()] = SU;
00859       if (LiveRegGens[I->getReg()] == nullptr ||
00860           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
00861         LiveRegGens[I->getReg()] = I->getSUnit();
00862     }
00863   }
00864   if (SU->getHeight() < MinAvailableCycle)
00865     MinAvailableCycle = SU->getHeight();
00866 
00867   SU->setHeightDirty();
00868   SU->isScheduled = false;
00869   SU->isAvailable = true;
00870   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
00871     // Don't make available until backtracking is complete.
00872     SU->isPending = true;
00873     PendingQueue.push_back(SU);
00874   }
00875   else {
00876     AvailableQueue->push(SU);
00877   }
00878   AvailableQueue->unscheduledNode(SU);
00879 }
00880 
00881 /// After backtracking, the hazard checker needs to be restored to a state
00882 /// corresponding the current cycle.
00883 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
00884   HazardRec->Reset();
00885 
00886   unsigned LookAhead = std::min((unsigned)Sequence.size(),
00887                                 HazardRec->getMaxLookAhead());
00888   if (LookAhead == 0)
00889     return;
00890 
00891   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
00892   unsigned HazardCycle = (*I)->getHeight();
00893   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
00894     SUnit *SU = *I;
00895     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
00896       HazardRec->RecedeCycle();
00897     }
00898     EmitNode(SU);
00899   }
00900 }
00901 
00902 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
00903 /// BTCycle in order to schedule a specific node.
00904 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
00905   SUnit *OldSU = Sequence.back();
00906   while (true) {
00907     Sequence.pop_back();
00908     // FIXME: use ready cycle instead of height
00909     CurCycle = OldSU->getHeight();
00910     UnscheduleNodeBottomUp(OldSU);
00911     AvailableQueue->setCurCycle(CurCycle);
00912     if (OldSU == BtSU)
00913       break;
00914     OldSU = Sequence.back();
00915   }
00916 
00917   assert(!SU->isSucc(OldSU) && "Something is wrong!");
00918 
00919   RestoreHazardCheckerBottomUp();
00920 
00921   ReleasePending();
00922 
00923   ++NumBacktracks;
00924 }
00925 
00926 static bool isOperandOf(const SUnit *SU, SDNode *N) {
00927   for (const SDNode *SUNode = SU->getNode(); SUNode;
00928        SUNode = SUNode->getGluedNode()) {
00929     if (SUNode->isOperandOf(N))
00930       return true;
00931   }
00932   return false;
00933 }
00934 
00935 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
00936 /// successors to the newly created node.
00937 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
00938   SDNode *N = SU->getNode();
00939   if (!N)
00940     return nullptr;
00941 
00942   if (SU->getNode()->getGluedNode())
00943     return nullptr;
00944 
00945   SUnit *NewSU;
00946   bool TryUnfold = false;
00947   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
00948     MVT VT = N->getSimpleValueType(i);
00949     if (VT == MVT::Glue)
00950       return nullptr;
00951     else if (VT == MVT::Other)
00952       TryUnfold = true;
00953   }
00954   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00955     const SDValue &Op = N->getOperand(i);
00956     MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
00957     if (VT == MVT::Glue)
00958       return nullptr;
00959   }
00960 
00961   if (TryUnfold) {
00962     SmallVector<SDNode*, 2> NewNodes;
00963     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
00964       return nullptr;
00965 
00966     // unfolding an x86 DEC64m operation results in store, dec, load which
00967     // can't be handled here so quit
00968     if (NewNodes.size() == 3)
00969       return nullptr;
00970 
00971     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
00972     assert(NewNodes.size() == 2 && "Expected a load folding node!");
00973 
00974     N = NewNodes[1];
00975     SDNode *LoadNode = NewNodes[0];
00976     unsigned NumVals = N->getNumValues();
00977     unsigned OldNumVals = SU->getNode()->getNumValues();
00978     for (unsigned i = 0; i != NumVals; ++i)
00979       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
00980     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
00981                                    SDValue(LoadNode, 1));
00982 
00983     // LoadNode may already exist. This can happen when there is another
00984     // load from the same location and producing the same type of value
00985     // but it has different alignment or volatileness.
00986     bool isNewLoad = true;
00987     SUnit *LoadSU;
00988     if (LoadNode->getNodeId() != -1) {
00989       LoadSU = &SUnits[LoadNode->getNodeId()];
00990       isNewLoad = false;
00991     } else {
00992       LoadSU = CreateNewSUnit(LoadNode);
00993       LoadNode->setNodeId(LoadSU->NodeNum);
00994 
00995       InitNumRegDefsLeft(LoadSU);
00996       computeLatency(LoadSU);
00997     }
00998 
00999     SUnit *NewSU = CreateNewSUnit(N);
01000     assert(N->getNodeId() == -1 && "Node already inserted!");
01001     N->setNodeId(NewSU->NodeNum);
01002 
01003     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01004     for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
01005       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
01006         NewSU->isTwoAddress = true;
01007         break;
01008       }
01009     }
01010     if (MCID.isCommutable())
01011       NewSU->isCommutable = true;
01012 
01013     InitNumRegDefsLeft(NewSU);
01014     computeLatency(NewSU);
01015 
01016     // Record all the edges to and from the old SU, by category.
01017     SmallVector<SDep, 4> ChainPreds;
01018     SmallVector<SDep, 4> ChainSuccs;
01019     SmallVector<SDep, 4> LoadPreds;
01020     SmallVector<SDep, 4> NodePreds;
01021     SmallVector<SDep, 4> NodeSuccs;
01022     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01023          I != E; ++I) {
01024       if (I->isCtrl())
01025         ChainPreds.push_back(*I);
01026       else if (isOperandOf(I->getSUnit(), LoadNode))
01027         LoadPreds.push_back(*I);
01028       else
01029         NodePreds.push_back(*I);
01030     }
01031     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01032          I != E; ++I) {
01033       if (I->isCtrl())
01034         ChainSuccs.push_back(*I);
01035       else
01036         NodeSuccs.push_back(*I);
01037     }
01038 
01039     // Now assign edges to the newly-created nodes.
01040     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
01041       const SDep &Pred = ChainPreds[i];
01042       RemovePred(SU, Pred);
01043       if (isNewLoad)
01044         AddPred(LoadSU, Pred);
01045     }
01046     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
01047       const SDep &Pred = LoadPreds[i];
01048       RemovePred(SU, Pred);
01049       if (isNewLoad)
01050         AddPred(LoadSU, Pred);
01051     }
01052     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
01053       const SDep &Pred = NodePreds[i];
01054       RemovePred(SU, Pred);
01055       AddPred(NewSU, Pred);
01056     }
01057     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
01058       SDep D = NodeSuccs[i];
01059       SUnit *SuccDep = D.getSUnit();
01060       D.setSUnit(SU);
01061       RemovePred(SuccDep, D);
01062       D.setSUnit(NewSU);
01063       AddPred(SuccDep, D);
01064       // Balance register pressure.
01065       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
01066           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
01067         --NewSU->NumRegDefsLeft;
01068     }
01069     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
01070       SDep D = ChainSuccs[i];
01071       SUnit *SuccDep = D.getSUnit();
01072       D.setSUnit(SU);
01073       RemovePred(SuccDep, D);
01074       if (isNewLoad) {
01075         D.setSUnit(LoadSU);
01076         AddPred(SuccDep, D);
01077       }
01078     }
01079 
01080     // Add a data dependency to reflect that NewSU reads the value defined
01081     // by LoadSU.
01082     SDep D(LoadSU, SDep::Data, 0);
01083     D.setLatency(LoadSU->Latency);
01084     AddPred(NewSU, D);
01085 
01086     if (isNewLoad)
01087       AvailableQueue->addNode(LoadSU);
01088     AvailableQueue->addNode(NewSU);
01089 
01090     ++NumUnfolds;
01091 
01092     if (NewSU->NumSuccsLeft == 0) {
01093       NewSU->isAvailable = true;
01094       return NewSU;
01095     }
01096     SU = NewSU;
01097   }
01098 
01099   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
01100   NewSU = CreateClone(SU);
01101 
01102   // New SUnit has the exact same predecessors.
01103   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01104        I != E; ++I)
01105     if (!I->isArtificial())
01106       AddPred(NewSU, *I);
01107 
01108   // Only copy scheduled successors. Cut them from old node's successor
01109   // list and move them over.
01110   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01111   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01112        I != E; ++I) {
01113     if (I->isArtificial())
01114       continue;
01115     SUnit *SuccSU = I->getSUnit();
01116     if (SuccSU->isScheduled) {
01117       SDep D = *I;
01118       D.setSUnit(NewSU);
01119       AddPred(SuccSU, D);
01120       D.setSUnit(SU);
01121       DelDeps.push_back(std::make_pair(SuccSU, D));
01122     }
01123   }
01124   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01125     RemovePred(DelDeps[i].first, DelDeps[i].second);
01126 
01127   AvailableQueue->updateNode(SU);
01128   AvailableQueue->addNode(NewSU);
01129 
01130   ++NumDups;
01131   return NewSU;
01132 }
01133 
01134 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
01135 /// scheduled successors of the given SUnit to the last copy.
01136 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
01137                                               const TargetRegisterClass *DestRC,
01138                                               const TargetRegisterClass *SrcRC,
01139                                               SmallVectorImpl<SUnit*> &Copies) {
01140   SUnit *CopyFromSU = CreateNewSUnit(nullptr);
01141   CopyFromSU->CopySrcRC = SrcRC;
01142   CopyFromSU->CopyDstRC = DestRC;
01143 
01144   SUnit *CopyToSU = CreateNewSUnit(nullptr);
01145   CopyToSU->CopySrcRC = DestRC;
01146   CopyToSU->CopyDstRC = SrcRC;
01147 
01148   // Only copy scheduled successors. Cut them from old node's successor
01149   // list and move them over.
01150   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01151   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01152        I != E; ++I) {
01153     if (I->isArtificial())
01154       continue;
01155     SUnit *SuccSU = I->getSUnit();
01156     if (SuccSU->isScheduled) {
01157       SDep D = *I;
01158       D.setSUnit(CopyToSU);
01159       AddPred(SuccSU, D);
01160       DelDeps.push_back(std::make_pair(SuccSU, *I));
01161     }
01162     else {
01163       // Avoid scheduling the def-side copy before other successors. Otherwise
01164       // we could introduce another physreg interference on the copy and
01165       // continue inserting copies indefinitely.
01166       AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
01167     }
01168   }
01169   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01170     RemovePred(DelDeps[i].first, DelDeps[i].second);
01171 
01172   SDep FromDep(SU, SDep::Data, Reg);
01173   FromDep.setLatency(SU->Latency);
01174   AddPred(CopyFromSU, FromDep);
01175   SDep ToDep(CopyFromSU, SDep::Data, 0);
01176   ToDep.setLatency(CopyFromSU->Latency);
01177   AddPred(CopyToSU, ToDep);
01178 
01179   AvailableQueue->updateNode(SU);
01180   AvailableQueue->addNode(CopyFromSU);
01181   AvailableQueue->addNode(CopyToSU);
01182   Copies.push_back(CopyFromSU);
01183   Copies.push_back(CopyToSU);
01184 
01185   ++NumPRCopies;
01186 }
01187 
01188 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
01189 /// definition of the specified node.
01190 /// FIXME: Move to SelectionDAG?
01191 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
01192                                  const TargetInstrInfo *TII) {
01193   unsigned NumRes;
01194   if (N->getOpcode() == ISD::CopyFromReg) {
01195     // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
01196     NumRes = 1;
01197   } else {
01198     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01199     assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
01200     NumRes = MCID.getNumDefs();
01201     for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
01202       if (Reg == *ImpDef)
01203         break;
01204       ++NumRes;
01205     }
01206   }
01207   return N->getSimpleValueType(NumRes);
01208 }
01209 
01210 /// CheckForLiveRegDef - Return true and update live register vector if the
01211 /// specified register def of the specified SUnit clobbers any "live" registers.
01212 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
01213                                std::vector<SUnit*> &LiveRegDefs,
01214                                SmallSet<unsigned, 4> &RegAdded,
01215                                SmallVectorImpl<unsigned> &LRegs,
01216                                const TargetRegisterInfo *TRI) {
01217   for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
01218 
01219     // Check if Ref is live.
01220     if (!LiveRegDefs[*AliasI]) continue;
01221 
01222     // Allow multiple uses of the same def.
01223     if (LiveRegDefs[*AliasI] == SU) continue;
01224 
01225     // Add Reg to the set of interfering live regs.
01226     if (RegAdded.insert(*AliasI).second) {
01227       LRegs.push_back(*AliasI);
01228     }
01229   }
01230 }
01231 
01232 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
01233 /// by RegMask, and add them to LRegs.
01234 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
01235                                      std::vector<SUnit*> &LiveRegDefs,
01236                                      SmallSet<unsigned, 4> &RegAdded,
01237                                      SmallVectorImpl<unsigned> &LRegs) {
01238   // Look at all live registers. Skip Reg0 and the special CallResource.
01239   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
01240     if (!LiveRegDefs[i]) continue;
01241     if (LiveRegDefs[i] == SU) continue;
01242     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
01243     if (RegAdded.insert(i).second)
01244       LRegs.push_back(i);
01245   }
01246 }
01247 
01248 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
01249 static const uint32_t *getNodeRegMask(const SDNode *N) {
01250   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01251     if (const RegisterMaskSDNode *Op =
01252         dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
01253       return Op->getRegMask();
01254   return nullptr;
01255 }
01256 
01257 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
01258 /// scheduling of the given node to satisfy live physical register dependencies.
01259 /// If the specific node is the last one that's available to schedule, do
01260 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
01261 bool ScheduleDAGRRList::
01262 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
01263   if (NumLiveRegs == 0)
01264     return false;
01265 
01266   SmallSet<unsigned, 4> RegAdded;
01267   // If this node would clobber any "live" register, then it's not ready.
01268   //
01269   // If SU is the currently live definition of the same register that it uses,
01270   // then we are free to schedule it.
01271   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01272        I != E; ++I) {
01273     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
01274       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
01275                          RegAdded, LRegs, TRI);
01276   }
01277 
01278   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
01279     if (Node->getOpcode() == ISD::INLINEASM) {
01280       // Inline asm can clobber physical defs.
01281       unsigned NumOps = Node->getNumOperands();
01282       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
01283         --NumOps;  // Ignore the glue operand.
01284 
01285       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
01286         unsigned Flags =
01287           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
01288         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
01289 
01290         ++i; // Skip the ID value.
01291         if (InlineAsm::isRegDefKind(Flags) ||
01292             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
01293             InlineAsm::isClobberKind(Flags)) {
01294           // Check for def of register or earlyclobber register.
01295           for (; NumVals; --NumVals, ++i) {
01296             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
01297             if (TargetRegisterInfo::isPhysicalRegister(Reg))
01298               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01299           }
01300         } else
01301           i += NumVals;
01302       }
01303       continue;
01304     }
01305 
01306     if (!Node->isMachineOpcode())
01307       continue;
01308     // If we're in the middle of scheduling a call, don't begin scheduling
01309     // another call. Also, don't allow any physical registers to be live across
01310     // the call.
01311     if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
01312       // Check the special calling-sequence resource.
01313       unsigned CallResource = TRI->getNumRegs();
01314       if (LiveRegDefs[CallResource]) {
01315         SDNode *Gen = LiveRegGens[CallResource]->getNode();
01316         while (SDNode *Glued = Gen->getGluedNode())
01317           Gen = Glued;
01318         if (!IsChainDependent(Gen, Node, 0, TII) &&
01319             RegAdded.insert(CallResource).second)
01320           LRegs.push_back(CallResource);
01321       }
01322     }
01323     if (const uint32_t *RegMask = getNodeRegMask(Node))
01324       CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
01325 
01326     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
01327     if (!MCID.ImplicitDefs)
01328       continue;
01329     for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
01330       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01331   }
01332 
01333   return !LRegs.empty();
01334 }
01335 
01336 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
01337   // Add the nodes that aren't ready back onto the available list.
01338   for (unsigned i = Interferences.size(); i > 0; --i) {
01339     SUnit *SU = Interferences[i-1];
01340     LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
01341     if (Reg) {
01342       SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
01343       if (std::find(LRegs.begin(), LRegs.end(), Reg) == LRegs.end())
01344         continue;
01345     }
01346     SU->isPending = false;
01347     // The interfering node may no longer be available due to backtracking.
01348     // Furthermore, it may have been made available again, in which case it is
01349     // now already in the AvailableQueue.
01350     if (SU->isAvailable && !SU->NodeQueueId) {
01351       DEBUG(dbgs() << "    Repushing SU #" << SU->NodeNum << '\n');
01352       AvailableQueue->push(SU);
01353     }
01354     if (i < Interferences.size())
01355       Interferences[i-1] = Interferences.back();
01356     Interferences.pop_back();
01357     LRegsMap.erase(LRegsPos);
01358   }
01359 }
01360 
01361 /// Return a node that can be scheduled in this cycle. Requirements:
01362 /// (1) Ready: latency has been satisfied
01363 /// (2) No Hazards: resources are available
01364 /// (3) No Interferences: may unschedule to break register interferences.
01365 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
01366   SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
01367   while (CurSU) {
01368     SmallVector<unsigned, 4> LRegs;
01369     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
01370       break;
01371     DEBUG(dbgs() << "    Interfering reg " <<
01372           (LRegs[0] == TRI->getNumRegs() ? "CallResource"
01373            : TRI->getName(LRegs[0]))
01374            << " SU #" << CurSU->NodeNum << '\n');
01375     std::pair<LRegsMapT::iterator, bool> LRegsPair =
01376       LRegsMap.insert(std::make_pair(CurSU, LRegs));
01377     if (LRegsPair.second) {
01378       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
01379       Interferences.push_back(CurSU);
01380     }
01381     else {
01382       assert(CurSU->isPending && "Interferences are pending");
01383       // Update the interference with current live regs.
01384       LRegsPair.first->second = LRegs;
01385     }
01386     CurSU = AvailableQueue->pop();
01387   }
01388   if (CurSU)
01389     return CurSU;
01390 
01391   // All candidates are delayed due to live physical reg dependencies.
01392   // Try backtracking, code duplication, or inserting cross class copies
01393   // to resolve it.
01394   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
01395     SUnit *TrySU = Interferences[i];
01396     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01397 
01398     // Try unscheduling up to the point where it's safe to schedule
01399     // this node.
01400     SUnit *BtSU = nullptr;
01401     unsigned LiveCycle = UINT_MAX;
01402     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
01403       unsigned Reg = LRegs[j];
01404       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
01405         BtSU = LiveRegGens[Reg];
01406         LiveCycle = BtSU->getHeight();
01407       }
01408     }
01409     if (!WillCreateCycle(TrySU, BtSU))  {
01410       // BacktrackBottomUp mutates Interferences!
01411       BacktrackBottomUp(TrySU, BtSU);
01412 
01413       // Force the current node to be scheduled before the node that
01414       // requires the physical reg dep.
01415       if (BtSU->isAvailable) {
01416         BtSU->isAvailable = false;
01417         if (!BtSU->isPending)
01418           AvailableQueue->remove(BtSU);
01419       }
01420       DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
01421             << TrySU->NodeNum << ")\n");
01422       AddPred(TrySU, SDep(BtSU, SDep::Artificial));
01423 
01424       // If one or more successors has been unscheduled, then the current
01425       // node is no longer available.
01426       if (!TrySU->isAvailable || !TrySU->NodeQueueId)
01427         CurSU = AvailableQueue->pop();
01428       else {
01429         // Available and in AvailableQueue
01430         AvailableQueue->remove(TrySU);
01431         CurSU = TrySU;
01432       }
01433       // Interferences has been mutated. We must break.
01434       break;
01435     }
01436   }
01437 
01438   if (!CurSU) {
01439     // Can't backtrack. If it's too expensive to copy the value, then try
01440     // duplicate the nodes that produces these "too expensive to copy"
01441     // values to break the dependency. In case even that doesn't work,
01442     // insert cross class copies.
01443     // If it's not too expensive, i.e. cost != -1, issue copies.
01444     SUnit *TrySU = Interferences[0];
01445     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01446     assert(LRegs.size() == 1 && "Can't handle this yet!");
01447     unsigned Reg = LRegs[0];
01448     SUnit *LRDef = LiveRegDefs[Reg];
01449     MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
01450     const TargetRegisterClass *RC =
01451       TRI->getMinimalPhysRegClass(Reg, VT);
01452     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
01453 
01454     // If cross copy register class is the same as RC, then it must be possible
01455     // copy the value directly. Do not try duplicate the def.
01456     // If cross copy register class is not the same as RC, then it's possible to
01457     // copy the value but it require cross register class copies and it is
01458     // expensive.
01459     // If cross copy register class is null, then it's not possible to copy
01460     // the value at all.
01461     SUnit *NewDef = nullptr;
01462     if (DestRC != RC) {
01463       NewDef = CopyAndMoveSuccessors(LRDef);
01464       if (!DestRC && !NewDef)
01465         report_fatal_error("Can't handle live physical register dependency!");
01466     }
01467     if (!NewDef) {
01468       // Issue copies, these can be expensive cross register class copies.
01469       SmallVector<SUnit*, 2> Copies;
01470       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
01471       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
01472             << " to SU #" << Copies.front()->NodeNum << "\n");
01473       AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
01474       NewDef = Copies.back();
01475     }
01476 
01477     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
01478           << " to SU #" << TrySU->NodeNum << "\n");
01479     LiveRegDefs[Reg] = NewDef;
01480     AddPred(NewDef, SDep(TrySU, SDep::Artificial));
01481     TrySU->isAvailable = false;
01482     CurSU = NewDef;
01483   }
01484   assert(CurSU && "Unable to resolve live physical register dependencies!");
01485   return CurSU;
01486 }
01487 
01488 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
01489 /// schedulers.
01490 void ScheduleDAGRRList::ListScheduleBottomUp() {
01491   // Release any predecessors of the special Exit node.
01492   ReleasePredecessors(&ExitSU);
01493 
01494   // Add root to Available queue.
01495   if (!SUnits.empty()) {
01496     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
01497     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
01498     RootSU->isAvailable = true;
01499     AvailableQueue->push(RootSU);
01500   }
01501 
01502   // While Available queue is not empty, grab the node with the highest
01503   // priority. If it is not ready put it back.  Schedule the node.
01504   Sequence.reserve(SUnits.size());
01505   while (!AvailableQueue->empty() || !Interferences.empty()) {
01506     DEBUG(dbgs() << "\nExamining Available:\n";
01507           AvailableQueue->dump(this));
01508 
01509     // Pick the best node to schedule taking all constraints into
01510     // consideration.
01511     SUnit *SU = PickNodeToScheduleBottomUp();
01512 
01513     AdvancePastStalls(SU);
01514 
01515     ScheduleNodeBottomUp(SU);
01516 
01517     while (AvailableQueue->empty() && !PendingQueue.empty()) {
01518       // Advance the cycle to free resources. Skip ahead to the next ready SU.
01519       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
01520       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
01521     }
01522   }
01523 
01524   // Reverse the order if it is bottom up.
01525   std::reverse(Sequence.begin(), Sequence.end());
01526 
01527 #ifndef NDEBUG
01528   VerifyScheduledSequence(/*isBottomUp=*/true);
01529 #endif
01530 }
01531 
01532 //===----------------------------------------------------------------------===//
01533 //                RegReductionPriorityQueue Definition
01534 //===----------------------------------------------------------------------===//
01535 //
01536 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
01537 // to reduce register pressure.
01538 //
01539 namespace {
01540 class RegReductionPQBase;
01541 
01542 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
01543   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
01544 };
01545 
01546 #ifndef NDEBUG
01547 template<class SF>
01548 struct reverse_sort : public queue_sort {
01549   SF &SortFunc;
01550   reverse_sort(SF &sf) : SortFunc(sf) {}
01551 
01552   bool operator()(SUnit* left, SUnit* right) const {
01553     // reverse left/right rather than simply !SortFunc(left, right)
01554     // to expose different paths in the comparison logic.
01555     return SortFunc(right, left);
01556   }
01557 };
01558 #endif // NDEBUG
01559 
01560 /// bu_ls_rr_sort - Priority function for bottom up register pressure
01561 // reduction scheduler.
01562 struct bu_ls_rr_sort : public queue_sort {
01563   enum {
01564     IsBottomUp = true,
01565     HasReadyFilter = false
01566   };
01567 
01568   RegReductionPQBase *SPQ;
01569   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
01570 
01571   bool operator()(SUnit* left, SUnit* right) const;
01572 };
01573 
01574 // src_ls_rr_sort - Priority function for source order scheduler.
01575 struct src_ls_rr_sort : public queue_sort {
01576   enum {
01577     IsBottomUp = true,
01578     HasReadyFilter = false
01579   };
01580 
01581   RegReductionPQBase *SPQ;
01582   src_ls_rr_sort(RegReductionPQBase *spq)
01583     : SPQ(spq) {}
01584 
01585   bool operator()(SUnit* left, SUnit* right) const;
01586 };
01587 
01588 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
01589 struct hybrid_ls_rr_sort : public queue_sort {
01590   enum {
01591     IsBottomUp = true,
01592     HasReadyFilter = false
01593   };
01594 
01595   RegReductionPQBase *SPQ;
01596   hybrid_ls_rr_sort(RegReductionPQBase *spq)
01597     : SPQ(spq) {}
01598 
01599   bool isReady(SUnit *SU, unsigned CurCycle) const;
01600 
01601   bool operator()(SUnit* left, SUnit* right) const;
01602 };
01603 
01604 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
01605 // scheduler.
01606 struct ilp_ls_rr_sort : public queue_sort {
01607   enum {
01608     IsBottomUp = true,
01609     HasReadyFilter = false
01610   };
01611 
01612   RegReductionPQBase *SPQ;
01613   ilp_ls_rr_sort(RegReductionPQBase *spq)
01614     : SPQ(spq) {}
01615 
01616   bool isReady(SUnit *SU, unsigned CurCycle) const;
01617 
01618   bool operator()(SUnit* left, SUnit* right) const;
01619 };
01620 
01621 class RegReductionPQBase : public SchedulingPriorityQueue {
01622 protected:
01623   std::vector<SUnit*> Queue;
01624   unsigned CurQueueId;
01625   bool TracksRegPressure;
01626   bool SrcOrder;
01627 
01628   // SUnits - The SUnits for the current graph.
01629   std::vector<SUnit> *SUnits;
01630 
01631   MachineFunction &MF;
01632   const TargetInstrInfo *TII;
01633   const TargetRegisterInfo *TRI;
01634   const TargetLowering *TLI;
01635   ScheduleDAGRRList *scheduleDAG;
01636 
01637   // SethiUllmanNumbers - The SethiUllman number for each node.
01638   std::vector<unsigned> SethiUllmanNumbers;
01639 
01640   /// RegPressure - Tracking current reg pressure per register class.
01641   ///
01642   std::vector<unsigned> RegPressure;
01643 
01644   /// RegLimit - Tracking the number of allocatable registers per register
01645   /// class.
01646   std::vector<unsigned> RegLimit;
01647 
01648 public:
01649   RegReductionPQBase(MachineFunction &mf,
01650                      bool hasReadyFilter,
01651                      bool tracksrp,
01652                      bool srcorder,
01653                      const TargetInstrInfo *tii,
01654                      const TargetRegisterInfo *tri,
01655                      const TargetLowering *tli)
01656     : SchedulingPriorityQueue(hasReadyFilter),
01657       CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
01658       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
01659     if (TracksRegPressure) {
01660       unsigned NumRC = TRI->getNumRegClasses();
01661       RegLimit.resize(NumRC);
01662       RegPressure.resize(NumRC);
01663       std::fill(RegLimit.begin(), RegLimit.end(), 0);
01664       std::fill(RegPressure.begin(), RegPressure.end(), 0);
01665       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01666              E = TRI->regclass_end(); I != E; ++I)
01667         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
01668     }
01669   }
01670 
01671   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
01672     scheduleDAG = scheduleDag;
01673   }
01674 
01675   ScheduleHazardRecognizer* getHazardRec() {
01676     return scheduleDAG->getHazardRec();
01677   }
01678 
01679   void initNodes(std::vector<SUnit> &sunits) override;
01680 
01681   void addNode(const SUnit *SU) override;
01682 
01683   void updateNode(const SUnit *SU) override;
01684 
01685   void releaseState() override {
01686     SUnits = nullptr;
01687     SethiUllmanNumbers.clear();
01688     std::fill(RegPressure.begin(), RegPressure.end(), 0);
01689   }
01690 
01691   unsigned getNodePriority(const SUnit *SU) const;
01692 
01693   unsigned getNodeOrdering(const SUnit *SU) const {
01694     if (!SU->getNode()) return 0;
01695 
01696     return SU->getNode()->getIROrder();
01697   }
01698 
01699   bool empty() const override { return Queue.empty(); }
01700 
01701   void push(SUnit *U) override {
01702     assert(!U->NodeQueueId && "Node in the queue already");
01703     U->NodeQueueId = ++CurQueueId;
01704     Queue.push_back(U);
01705   }
01706 
01707   void remove(SUnit *SU) override {
01708     assert(!Queue.empty() && "Queue is empty!");
01709     assert(SU->NodeQueueId != 0 && "Not in queue!");
01710     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
01711                                                  SU);
01712     if (I != std::prev(Queue.end()))
01713       std::swap(*I, Queue.back());
01714     Queue.pop_back();
01715     SU->NodeQueueId = 0;
01716   }
01717 
01718   bool tracksRegPressure() const override { return TracksRegPressure; }
01719 
01720   void dumpRegPressure() const;
01721 
01722   bool HighRegPressure(const SUnit *SU) const;
01723 
01724   bool MayReduceRegPressure(SUnit *SU) const;
01725 
01726   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
01727 
01728   void scheduledNode(SUnit *SU) override;
01729 
01730   void unscheduledNode(SUnit *SU) override;
01731 
01732 protected:
01733   bool canClobber(const SUnit *SU, const SUnit *Op);
01734   void AddPseudoTwoAddrDeps();
01735   void PrescheduleNodesWithMultipleUses();
01736   void CalculateSethiUllmanNumbers();
01737 };
01738 
01739 template<class SF>
01740 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
01741   std::vector<SUnit *>::iterator Best = Q.begin();
01742   for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
01743          E = Q.end(); I != E; ++I)
01744     if (Picker(*Best, *I))
01745       Best = I;
01746   SUnit *V = *Best;
01747   if (Best != std::prev(Q.end()))
01748     std::swap(*Best, Q.back());
01749   Q.pop_back();
01750   return V;
01751 }
01752 
01753 template<class SF>
01754 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
01755 #ifndef NDEBUG
01756   if (DAG->StressSched) {
01757     reverse_sort<SF> RPicker(Picker);
01758     return popFromQueueImpl(Q, RPicker);
01759   }
01760 #endif
01761   (void)DAG;
01762   return popFromQueueImpl(Q, Picker);
01763 }
01764 
01765 template<class SF>
01766 class RegReductionPriorityQueue : public RegReductionPQBase {
01767   SF Picker;
01768 
01769 public:
01770   RegReductionPriorityQueue(MachineFunction &mf,
01771                             bool tracksrp,
01772                             bool srcorder,
01773                             const TargetInstrInfo *tii,
01774                             const TargetRegisterInfo *tri,
01775                             const TargetLowering *tli)
01776     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
01777                          tii, tri, tli),
01778       Picker(this) {}
01779 
01780   bool isBottomUp() const override { return SF::IsBottomUp; }
01781 
01782   bool isReady(SUnit *U) const override {
01783     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
01784   }
01785 
01786   SUnit *pop() override {
01787     if (Queue.empty()) return nullptr;
01788 
01789     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
01790     V->NodeQueueId = 0;
01791     return V;
01792   }
01793 
01794 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01795   void dump(ScheduleDAG *DAG) const override {
01796     // Emulate pop() without clobbering NodeQueueIds.
01797     std::vector<SUnit*> DumpQueue = Queue;
01798     SF DumpPicker = Picker;
01799     while (!DumpQueue.empty()) {
01800       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
01801       dbgs() << "Height " << SU->getHeight() << ": ";
01802       SU->dump(DAG);
01803     }
01804   }
01805 #endif
01806 };
01807 
01808 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
01809 BURegReductionPriorityQueue;
01810 
01811 typedef RegReductionPriorityQueue<src_ls_rr_sort>
01812 SrcRegReductionPriorityQueue;
01813 
01814 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
01815 HybridBURRPriorityQueue;
01816 
01817 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
01818 ILPBURRPriorityQueue;
01819 } // end anonymous namespace
01820 
01821 //===----------------------------------------------------------------------===//
01822 //           Static Node Priority for Register Pressure Reduction
01823 //===----------------------------------------------------------------------===//
01824 
01825 // Check for special nodes that bypass scheduling heuristics.
01826 // Currently this pushes TokenFactor nodes down, but may be used for other
01827 // pseudo-ops as well.
01828 //
01829 // Return -1 to schedule right above left, 1 for left above right.
01830 // Return 0 if no bias exists.
01831 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
01832   bool LSchedLow = left->isScheduleLow;
01833   bool RSchedLow = right->isScheduleLow;
01834   if (LSchedLow != RSchedLow)
01835     return LSchedLow < RSchedLow ? 1 : -1;
01836   return 0;
01837 }
01838 
01839 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
01840 /// Smaller number is the higher priority.
01841 static unsigned
01842 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
01843   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
01844   if (SethiUllmanNumber != 0)
01845     return SethiUllmanNumber;
01846 
01847   unsigned Extra = 0;
01848   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01849        I != E; ++I) {
01850     if (I->isCtrl()) continue;  // ignore chain preds
01851     SUnit *PredSU = I->getSUnit();
01852     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
01853     if (PredSethiUllman > SethiUllmanNumber) {
01854       SethiUllmanNumber = PredSethiUllman;
01855       Extra = 0;
01856     } else if (PredSethiUllman == SethiUllmanNumber)
01857       ++Extra;
01858   }
01859 
01860   SethiUllmanNumber += Extra;
01861 
01862   if (SethiUllmanNumber == 0)
01863     SethiUllmanNumber = 1;
01864 
01865   return SethiUllmanNumber;
01866 }
01867 
01868 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
01869 /// scheduling units.
01870 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
01871   SethiUllmanNumbers.assign(SUnits->size(), 0);
01872 
01873   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
01874     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
01875 }
01876 
01877 void RegReductionPQBase::addNode(const SUnit *SU) {
01878   unsigned SUSize = SethiUllmanNumbers.size();
01879   if (SUnits->size() > SUSize)
01880     SethiUllmanNumbers.resize(SUSize*2, 0);
01881   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01882 }
01883 
01884 void RegReductionPQBase::updateNode(const SUnit *SU) {
01885   SethiUllmanNumbers[SU->NodeNum] = 0;
01886   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01887 }
01888 
01889 // Lower priority means schedule further down. For bottom-up scheduling, lower
01890 // priority SUs are scheduled before higher priority SUs.
01891 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
01892   assert(SU->NodeNum < SethiUllmanNumbers.size());
01893   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
01894   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
01895     // CopyToReg should be close to its uses to facilitate coalescing and
01896     // avoid spilling.
01897     return 0;
01898   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
01899       Opc == TargetOpcode::SUBREG_TO_REG ||
01900       Opc == TargetOpcode::INSERT_SUBREG)
01901     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
01902     // close to their uses to facilitate coalescing.
01903     return 0;
01904   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
01905     // If SU does not have a register use, i.e. it doesn't produce a value
01906     // that would be consumed (e.g. store), then it terminates a chain of
01907     // computation.  Give it a large SethiUllman number so it will be
01908     // scheduled right before its predecessors that it doesn't lengthen
01909     // their live ranges.
01910     return 0xffff;
01911   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
01912     // If SU does not have a register def, schedule it close to its uses
01913     // because it does not lengthen any live ranges.
01914     return 0;
01915 #if 1
01916   return SethiUllmanNumbers[SU->NodeNum];
01917 #else
01918   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
01919   if (SU->isCallOp) {
01920     // FIXME: This assumes all of the defs are used as call operands.
01921     int NP = (int)Priority - SU->getNode()->getNumValues();
01922     return (NP > 0) ? NP : 0;
01923   }
01924   return Priority;
01925 #endif
01926 }
01927 
01928 //===----------------------------------------------------------------------===//
01929 //                     Register Pressure Tracking
01930 //===----------------------------------------------------------------------===//
01931 
01932 void RegReductionPQBase::dumpRegPressure() const {
01933 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01934   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01935          E = TRI->regclass_end(); I != E; ++I) {
01936     const TargetRegisterClass *RC = *I;
01937     unsigned Id = RC->getID();
01938     unsigned RP = RegPressure[Id];
01939     if (!RP) continue;
01940     DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
01941           << RegLimit[Id] << '\n');
01942   }
01943 #endif
01944 }
01945 
01946 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
01947   if (!TLI)
01948     return false;
01949 
01950   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
01951        I != E; ++I) {
01952     if (I->isCtrl())
01953       continue;
01954     SUnit *PredSU = I->getSUnit();
01955     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
01956     // to cover the number of registers defined (they are all live).
01957     if (PredSU->NumRegDefsLeft == 0) {
01958       continue;
01959     }
01960     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
01961          RegDefPos.IsValid(); RegDefPos.Advance()) {
01962       unsigned RCId, Cost;
01963       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
01964 
01965       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
01966         return true;
01967     }
01968   }
01969   return false;
01970 }
01971 
01972 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
01973   const SDNode *N = SU->getNode();
01974 
01975   if (!N->isMachineOpcode() || !SU->NumSuccs)
01976     return false;
01977 
01978   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
01979   for (unsigned i = 0; i != NumDefs; ++i) {
01980     MVT VT = N->getSimpleValueType(i);
01981     if (!N->hasAnyUseOfValue(i))
01982       continue;
01983     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
01984     if (RegPressure[RCId] >= RegLimit[RCId])
01985       return true;
01986   }
01987   return false;
01988 }
01989 
01990 // Compute the register pressure contribution by this instruction by count up
01991 // for uses that are not live and down for defs. Only count register classes
01992 // that are already under high pressure. As a side effect, compute the number of
01993 // uses of registers that are already live.
01994 //
01995 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
01996 // so could probably be factored.
01997 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
01998   LiveUses = 0;
01999   int PDiff = 0;
02000   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02001        I != E; ++I) {
02002     if (I->isCtrl())
02003       continue;
02004     SUnit *PredSU = I->getSUnit();
02005     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02006     // to cover the number of registers defined (they are all live).
02007     if (PredSU->NumRegDefsLeft == 0) {
02008       if (PredSU->getNode()->isMachineOpcode())
02009         ++LiveUses;
02010       continue;
02011     }
02012     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02013          RegDefPos.IsValid(); RegDefPos.Advance()) {
02014       MVT VT = RegDefPos.GetValue();
02015       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02016       if (RegPressure[RCId] >= RegLimit[RCId])
02017         ++PDiff;
02018     }
02019   }
02020   const SDNode *N = SU->getNode();
02021 
02022   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
02023     return PDiff;
02024 
02025   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02026   for (unsigned i = 0; i != NumDefs; ++i) {
02027     MVT VT = N->getSimpleValueType(i);
02028     if (!N->hasAnyUseOfValue(i))
02029       continue;
02030     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02031     if (RegPressure[RCId] >= RegLimit[RCId])
02032       --PDiff;
02033   }
02034   return PDiff;
02035 }
02036 
02037 void RegReductionPQBase::scheduledNode(SUnit *SU) {
02038   if (!TracksRegPressure)
02039     return;
02040 
02041   if (!SU->getNode())
02042     return;
02043 
02044   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02045        I != E; ++I) {
02046     if (I->isCtrl())
02047       continue;
02048     SUnit *PredSU = I->getSUnit();
02049     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02050     // to cover the number of registers defined (they are all live).
02051     if (PredSU->NumRegDefsLeft == 0) {
02052       continue;
02053     }
02054     // FIXME: The ScheduleDAG currently loses information about which of a
02055     // node's values is consumed by each dependence. Consequently, if the node
02056     // defines multiple register classes, we don't know which to pressurize
02057     // here. Instead the following loop consumes the register defs in an
02058     // arbitrary order. At least it handles the common case of clustered loads
02059     // to the same class. For precise liveness, each SDep needs to indicate the
02060     // result number. But that tightly couples the ScheduleDAG with the
02061     // SelectionDAG making updates tricky. A simpler hack would be to attach a
02062     // value type or register class to SDep.
02063     //
02064     // The most important aspect of register tracking is balancing the increase
02065     // here with the reduction further below. Note that this SU may use multiple
02066     // defs in PredSU. The can't be determined here, but we've already
02067     // compensated by reducing NumRegDefsLeft in PredSU during
02068     // ScheduleDAGSDNodes::AddSchedEdges.
02069     --PredSU->NumRegDefsLeft;
02070     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
02071     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02072          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02073       if (SkipRegDefs)
02074         continue;
02075 
02076       unsigned RCId, Cost;
02077       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02078       RegPressure[RCId] += Cost;
02079       break;
02080     }
02081   }
02082 
02083   // We should have this assert, but there may be dead SDNodes that never
02084   // materialize as SUnits, so they don't appear to generate liveness.
02085   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
02086   int SkipRegDefs = (int)SU->NumRegDefsLeft;
02087   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
02088        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02089     if (SkipRegDefs > 0)
02090       continue;
02091     unsigned RCId, Cost;
02092     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02093     if (RegPressure[RCId] < Cost) {
02094       // Register pressure tracking is imprecise. This can happen. But we try
02095       // hard not to let it happen because it likely results in poor scheduling.
02096       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
02097       RegPressure[RCId] = 0;
02098     }
02099     else {
02100       RegPressure[RCId] -= Cost;
02101     }
02102   }
02103   dumpRegPressure();
02104 }
02105 
02106 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
02107   if (!TracksRegPressure)
02108     return;
02109 
02110   const SDNode *N = SU->getNode();
02111   if (!N) return;
02112 
02113   if (!N->isMachineOpcode()) {
02114     if (N->getOpcode() != ISD::CopyToReg)
02115       return;
02116   } else {
02117     unsigned Opc = N->getMachineOpcode();
02118     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02119         Opc == TargetOpcode::INSERT_SUBREG ||
02120         Opc == TargetOpcode::SUBREG_TO_REG ||
02121         Opc == TargetOpcode::REG_SEQUENCE ||
02122         Opc == TargetOpcode::IMPLICIT_DEF)
02123       return;
02124   }
02125 
02126   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02127        I != E; ++I) {
02128     if (I->isCtrl())
02129       continue;
02130     SUnit *PredSU = I->getSUnit();
02131     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
02132     // counts data deps.
02133     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
02134       continue;
02135     const SDNode *PN = PredSU->getNode();
02136     if (!PN->isMachineOpcode()) {
02137       if (PN->getOpcode() == ISD::CopyFromReg) {
02138         MVT VT = PN->getSimpleValueType(0);
02139         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02140         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02141       }
02142       continue;
02143     }
02144     unsigned POpc = PN->getMachineOpcode();
02145     if (POpc == TargetOpcode::IMPLICIT_DEF)
02146       continue;
02147     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
02148         POpc == TargetOpcode::INSERT_SUBREG ||
02149         POpc == TargetOpcode::SUBREG_TO_REG) {
02150       MVT VT = PN->getSimpleValueType(0);
02151       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02152       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02153       continue;
02154     }
02155     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
02156     for (unsigned i = 0; i != NumDefs; ++i) {
02157       MVT VT = PN->getSimpleValueType(i);
02158       if (!PN->hasAnyUseOfValue(i))
02159         continue;
02160       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02161       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
02162         // Register pressure tracking is imprecise. This can happen.
02163         RegPressure[RCId] = 0;
02164       else
02165         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
02166     }
02167   }
02168 
02169   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
02170   // may transfer data dependencies to CopyToReg.
02171   if (SU->NumSuccs && N->isMachineOpcode()) {
02172     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02173     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02174       MVT VT = N->getSimpleValueType(i);
02175       if (VT == MVT::Glue || VT == MVT::Other)
02176         continue;
02177       if (!N->hasAnyUseOfValue(i))
02178         continue;
02179       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02180       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02181     }
02182   }
02183 
02184   dumpRegPressure();
02185 }
02186 
02187 //===----------------------------------------------------------------------===//
02188 //           Dynamic Node Priority for Register Pressure Reduction
02189 //===----------------------------------------------------------------------===//
02190 
02191 /// closestSucc - Returns the scheduled cycle of the successor which is
02192 /// closest to the current cycle.
02193 static unsigned closestSucc(const SUnit *SU) {
02194   unsigned MaxHeight = 0;
02195   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02196        I != E; ++I) {
02197     if (I->isCtrl()) continue;  // ignore chain succs
02198     unsigned Height = I->getSUnit()->getHeight();
02199     // If there are bunch of CopyToRegs stacked up, they should be considered
02200     // to be at the same position.
02201     if (I->getSUnit()->getNode() &&
02202         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
02203       Height = closestSucc(I->getSUnit())+1;
02204     if (Height > MaxHeight)
02205       MaxHeight = Height;
02206   }
02207   return MaxHeight;
02208 }
02209 
02210 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
02211 /// for scratch registers, i.e. number of data dependencies.
02212 static unsigned calcMaxScratches(const SUnit *SU) {
02213   unsigned Scratches = 0;
02214   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02215        I != E; ++I) {
02216     if (I->isCtrl()) continue;  // ignore chain preds
02217     Scratches++;
02218   }
02219   return Scratches;
02220 }
02221 
02222 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
02223 /// CopyFromReg from a virtual register.
02224 static bool hasOnlyLiveInOpers(const SUnit *SU) {
02225   bool RetVal = false;
02226   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02227        I != E; ++I) {
02228     if (I->isCtrl()) continue;
02229     const SUnit *PredSU = I->getSUnit();
02230     if (PredSU->getNode() &&
02231         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
02232       unsigned Reg =
02233         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
02234       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02235         RetVal = true;
02236         continue;
02237       }
02238     }
02239     return false;
02240   }
02241   return RetVal;
02242 }
02243 
02244 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
02245 /// CopyToReg to a virtual register. This SU def is probably a liveout and
02246 /// it has no other use. It should be scheduled closer to the terminator.
02247 static bool hasOnlyLiveOutUses(const SUnit *SU) {
02248   bool RetVal = false;
02249   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02250        I != E; ++I) {
02251     if (I->isCtrl()) continue;
02252     const SUnit *SuccSU = I->getSUnit();
02253     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
02254       unsigned Reg =
02255         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
02256       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02257         RetVal = true;
02258         continue;
02259       }
02260     }
02261     return false;
02262   }
02263   return RetVal;
02264 }
02265 
02266 // Set isVRegCycle for a node with only live in opers and live out uses. Also
02267 // set isVRegCycle for its CopyFromReg operands.
02268 //
02269 // This is only relevant for single-block loops, in which case the VRegCycle
02270 // node is likely an induction variable in which the operand and target virtual
02271 // registers should be coalesced (e.g. pre/post increment values). Setting the
02272 // isVRegCycle flag helps the scheduler prioritize other uses of the same
02273 // CopyFromReg so that this node becomes the virtual register "kill". This
02274 // avoids interference between the values live in and out of the block and
02275 // eliminates a copy inside the loop.
02276 static void initVRegCycle(SUnit *SU) {
02277   if (DisableSchedVRegCycle)
02278     return;
02279 
02280   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
02281     return;
02282 
02283   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
02284 
02285   SU->isVRegCycle = true;
02286 
02287   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02288        I != E; ++I) {
02289     if (I->isCtrl()) continue;
02290     I->getSUnit()->isVRegCycle = true;
02291   }
02292 }
02293 
02294 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
02295 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
02296 static void resetVRegCycle(SUnit *SU) {
02297   if (!SU->isVRegCycle)
02298     return;
02299 
02300   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02301        I != E; ++I) {
02302     if (I->isCtrl()) continue;  // ignore chain preds
02303     SUnit *PredSU = I->getSUnit();
02304     if (PredSU->isVRegCycle) {
02305       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
02306              "VRegCycle def must be CopyFromReg");
02307       I->getSUnit()->isVRegCycle = 0;
02308     }
02309   }
02310 }
02311 
02312 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
02313 // means a node that defines the VRegCycle has not been scheduled yet.
02314 static bool hasVRegCycleUse(const SUnit *SU) {
02315   // If this SU also defines the VReg, don't hoist it as a "use".
02316   if (SU->isVRegCycle)
02317     return false;
02318 
02319   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02320        I != E; ++I) {
02321     if (I->isCtrl()) continue;  // ignore chain preds
02322     if (I->getSUnit()->isVRegCycle &&
02323         I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
02324       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
02325       return true;
02326     }
02327   }
02328   return false;
02329 }
02330 
02331 // Check for either a dependence (latency) or resource (hazard) stall.
02332 //
02333 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
02334 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
02335   if ((int)SPQ->getCurCycle() < Height) return true;
02336   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02337       != ScheduleHazardRecognizer::NoHazard)
02338     return true;
02339   return false;
02340 }
02341 
02342 // Return -1 if left has higher priority, 1 if right has higher priority.
02343 // Return 0 if latency-based priority is equivalent.
02344 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
02345                             RegReductionPQBase *SPQ) {
02346   // Scheduling an instruction that uses a VReg whose postincrement has not yet
02347   // been scheduled will induce a copy. Model this as an extra cycle of latency.
02348   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
02349   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
02350   int LHeight = (int)left->getHeight() + LPenalty;
02351   int RHeight = (int)right->getHeight() + RPenalty;
02352 
02353   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
02354     BUHasStall(left, LHeight, SPQ);
02355   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
02356     BUHasStall(right, RHeight, SPQ);
02357 
02358   // If scheduling one of the node will cause a pipeline stall, delay it.
02359   // If scheduling either one of the node will cause a pipeline stall, sort
02360   // them according to their height.
02361   if (LStall) {
02362     if (!RStall)
02363       return 1;
02364     if (LHeight != RHeight)
02365       return LHeight > RHeight ? 1 : -1;
02366   } else if (RStall)
02367     return -1;
02368 
02369   // If either node is scheduling for latency, sort them by height/depth
02370   // and latency.
02371   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
02372                      right->SchedulingPref == Sched::ILP)) {
02373     // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
02374     // is enabled, grouping instructions by cycle, then its height is already
02375     // covered so only its depth matters. We also reach this point if both stall
02376     // but have the same height.
02377     if (!SPQ->getHazardRec()->isEnabled()) {
02378       if (LHeight != RHeight)
02379         return LHeight > RHeight ? 1 : -1;
02380     }
02381     int LDepth = left->getDepth() - LPenalty;
02382     int RDepth = right->getDepth() - RPenalty;
02383     if (LDepth != RDepth) {
02384       DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
02385             << ") depth " << LDepth << " vs SU (" << right->NodeNum
02386             << ") depth " << RDepth << "\n");
02387       return LDepth < RDepth ? 1 : -1;
02388     }
02389     if (left->Latency != right->Latency)
02390       return left->Latency > right->Latency ? 1 : -1;
02391   }
02392   return 0;
02393 }
02394 
02395 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
02396   // Schedule physical register definitions close to their use. This is
02397   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
02398   // long as shortening physreg live ranges is generally good, we can defer
02399   // creating a subtarget hook.
02400   if (!DisableSchedPhysRegJoin) {
02401     bool LHasPhysReg = left->hasPhysRegDefs;
02402     bool RHasPhysReg = right->hasPhysRegDefs;
02403     if (LHasPhysReg != RHasPhysReg) {
02404       #ifndef NDEBUG
02405       static const char *const PhysRegMsg[] = { " has no physreg",
02406                                                 " defines a physreg" };
02407       #endif
02408       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
02409             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
02410             << PhysRegMsg[RHasPhysReg] << "\n");
02411       return LHasPhysReg < RHasPhysReg;
02412     }
02413   }
02414 
02415   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
02416   unsigned LPriority = SPQ->getNodePriority(left);
02417   unsigned RPriority = SPQ->getNodePriority(right);
02418 
02419   // Be really careful about hoisting call operands above previous calls.
02420   // Only allows it if it would reduce register pressure.
02421   if (left->isCall && right->isCallOp) {
02422     unsigned RNumVals = right->getNode()->getNumValues();
02423     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
02424   }
02425   if (right->isCall && left->isCallOp) {
02426     unsigned LNumVals = left->getNode()->getNumValues();
02427     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
02428   }
02429 
02430   if (LPriority != RPriority)
02431     return LPriority > RPriority;
02432 
02433   // One or both of the nodes are calls and their sethi-ullman numbers are the
02434   // same, then keep source order.
02435   if (left->isCall || right->isCall) {
02436     unsigned LOrder = SPQ->getNodeOrdering(left);
02437     unsigned ROrder = SPQ->getNodeOrdering(right);
02438 
02439     // Prefer an ordering where the lower the non-zero order number, the higher
02440     // the preference.
02441     if ((LOrder || ROrder) && LOrder != ROrder)
02442       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02443   }
02444 
02445   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
02446   // e.g.
02447   // t1 = op t2, c1
02448   // t3 = op t4, c2
02449   //
02450   // and the following instructions are both ready.
02451   // t2 = op c3
02452   // t4 = op c4
02453   //
02454   // Then schedule t2 = op first.
02455   // i.e.
02456   // t4 = op c4
02457   // t2 = op c3
02458   // t1 = op t2, c1
02459   // t3 = op t4, c2
02460   //
02461   // This creates more short live intervals.
02462   unsigned LDist = closestSucc(left);
02463   unsigned RDist = closestSucc(right);
02464   if (LDist != RDist)
02465     return LDist < RDist;
02466 
02467   // How many registers becomes live when the node is scheduled.
02468   unsigned LScratch = calcMaxScratches(left);
02469   unsigned RScratch = calcMaxScratches(right);
02470   if (LScratch != RScratch)
02471     return LScratch > RScratch;
02472 
02473   // Comparing latency against a call makes little sense unless the node
02474   // is register pressure-neutral.
02475   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
02476     return (left->NodeQueueId > right->NodeQueueId);
02477 
02478   // Do not compare latencies when one or both of the nodes are calls.
02479   if (!DisableSchedCycles &&
02480       !(left->isCall || right->isCall)) {
02481     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
02482     if (result != 0)
02483       return result > 0;
02484   }
02485   else {
02486     if (left->getHeight() != right->getHeight())
02487       return left->getHeight() > right->getHeight();
02488 
02489     if (left->getDepth() != right->getDepth())
02490       return left->getDepth() < right->getDepth();
02491   }
02492 
02493   assert(left->NodeQueueId && right->NodeQueueId &&
02494          "NodeQueueId cannot be zero");
02495   return (left->NodeQueueId > right->NodeQueueId);
02496 }
02497 
02498 // Bottom up
02499 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02500   if (int res = checkSpecialNodes(left, right))
02501     return res > 0;
02502 
02503   return BURRSort(left, right, SPQ);
02504 }
02505 
02506 // Source order, otherwise bottom up.
02507 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02508   if (int res = checkSpecialNodes(left, right))
02509     return res > 0;
02510 
02511   unsigned LOrder = SPQ->getNodeOrdering(left);
02512   unsigned ROrder = SPQ->getNodeOrdering(right);
02513 
02514   // Prefer an ordering where the lower the non-zero order number, the higher
02515   // the preference.
02516   if ((LOrder || ROrder) && LOrder != ROrder)
02517     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02518 
02519   return BURRSort(left, right, SPQ);
02520 }
02521 
02522 // If the time between now and when the instruction will be ready can cover
02523 // the spill code, then avoid adding it to the ready queue. This gives long
02524 // stalls highest priority and allows hoisting across calls. It should also
02525 // speed up processing the available queue.
02526 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02527   static const unsigned ReadyDelay = 3;
02528 
02529   if (SPQ->MayReduceRegPressure(SU)) return true;
02530 
02531   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
02532 
02533   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
02534       != ScheduleHazardRecognizer::NoHazard)
02535     return false;
02536 
02537   return true;
02538 }
02539 
02540 // Return true if right should be scheduled with higher priority than left.
02541 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02542   if (int res = checkSpecialNodes(left, right))
02543     return res > 0;
02544 
02545   if (left->isCall || right->isCall)
02546     // No way to compute latency of calls.
02547     return BURRSort(left, right, SPQ);
02548 
02549   bool LHigh = SPQ->HighRegPressure(left);
02550   bool RHigh = SPQ->HighRegPressure(right);
02551   // Avoid causing spills. If register pressure is high, schedule for
02552   // register pressure reduction.
02553   if (LHigh && !RHigh) {
02554     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
02555           << right->NodeNum << ")\n");
02556     return true;
02557   }
02558   else if (!LHigh && RHigh) {
02559     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
02560           << left->NodeNum << ")\n");
02561     return false;
02562   }
02563   if (!LHigh && !RHigh) {
02564     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
02565     if (result != 0)
02566       return result > 0;
02567   }
02568   return BURRSort(left, right, SPQ);
02569 }
02570 
02571 // Schedule as many instructions in each cycle as possible. So don't make an
02572 // instruction available unless it is ready in the current cycle.
02573 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02574   if (SU->getHeight() > CurCycle) return false;
02575 
02576   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02577       != ScheduleHazardRecognizer::NoHazard)
02578     return false;
02579 
02580   return true;
02581 }
02582 
02583 static bool canEnableCoalescing(SUnit *SU) {
02584   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
02585   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
02586     // CopyToReg should be close to its uses to facilitate coalescing and
02587     // avoid spilling.
02588     return true;
02589 
02590   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02591       Opc == TargetOpcode::SUBREG_TO_REG ||
02592       Opc == TargetOpcode::INSERT_SUBREG)
02593     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
02594     // close to their uses to facilitate coalescing.
02595     return true;
02596 
02597   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
02598     // If SU does not have a register def, schedule it close to its uses
02599     // because it does not lengthen any live ranges.
02600     return true;
02601 
02602   return false;
02603 }
02604 
02605 // list-ilp is currently an experimental scheduler that allows various
02606 // heuristics to be enabled prior to the normal register reduction logic.
02607 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02608   if (int res = checkSpecialNodes(left, right))
02609     return res > 0;
02610 
02611   if (left->isCall || right->isCall)
02612     // No way to compute latency of calls.
02613     return BURRSort(left, right, SPQ);
02614 
02615   unsigned LLiveUses = 0, RLiveUses = 0;
02616   int LPDiff = 0, RPDiff = 0;
02617   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
02618     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
02619     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
02620   }
02621   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
02622     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
02623           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
02624     return LPDiff > RPDiff;
02625   }
02626 
02627   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
02628     bool LReduce = canEnableCoalescing(left);
02629     bool RReduce = canEnableCoalescing(right);
02630     if (LReduce && !RReduce) return false;
02631     if (RReduce && !LReduce) return true;
02632   }
02633 
02634   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
02635     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
02636           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
02637     return LLiveUses < RLiveUses;
02638   }
02639 
02640   if (!DisableSchedStalls) {
02641     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
02642     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
02643     if (LStall != RStall)
02644       return left->getHeight() > right->getHeight();
02645   }
02646 
02647   if (!DisableSchedCriticalPath) {
02648     int spread = (int)left->getDepth() - (int)right->getDepth();
02649     if (std::abs(spread) > MaxReorderWindow) {
02650       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
02651             << left->getDepth() << " != SU(" << right->NodeNum << "): "
02652             << right->getDepth() << "\n");
02653       return left->getDepth() < right->getDepth();
02654     }
02655   }
02656 
02657   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
02658     int spread = (int)left->getHeight() - (int)right->getHeight();
02659     if (std::abs(spread) > MaxReorderWindow)
02660       return left->getHeight() > right->getHeight();
02661   }
02662 
02663   return BURRSort(left, right, SPQ);
02664 }
02665 
02666 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
02667   SUnits = &sunits;
02668   // Add pseudo dependency edges for two-address nodes.
02669   if (!Disable2AddrHack)
02670     AddPseudoTwoAddrDeps();
02671   // Reroute edges to nodes with multiple uses.
02672   if (!TracksRegPressure && !SrcOrder)
02673     PrescheduleNodesWithMultipleUses();
02674   // Calculate node priorities.
02675   CalculateSethiUllmanNumbers();
02676 
02677   // For single block loops, mark nodes that look like canonical IV increments.
02678   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
02679     for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
02680       initVRegCycle(&sunits[i]);
02681     }
02682   }
02683 }
02684 
02685 //===----------------------------------------------------------------------===//
02686 //                    Preschedule for Register Pressure
02687 //===----------------------------------------------------------------------===//
02688 
02689 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
02690   if (SU->isTwoAddress) {
02691     unsigned Opc = SU->getNode()->getMachineOpcode();
02692     const MCInstrDesc &MCID = TII->get(Opc);
02693     unsigned NumRes = MCID.getNumDefs();
02694     unsigned NumOps = MCID.getNumOperands() - NumRes;
02695     for (unsigned i = 0; i != NumOps; ++i) {
02696       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
02697         SDNode *DU = SU->getNode()->getOperand(i).getNode();
02698         if (DU->getNodeId() != -1 &&
02699             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
02700           return true;
02701       }
02702     }
02703   }
02704   return false;
02705 }
02706 
02707 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
02708 /// successor's explicit physregs whose definition can reach DepSU.
02709 /// i.e. DepSU should not be scheduled above SU.
02710 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
02711                                          ScheduleDAGRRList *scheduleDAG,
02712                                          const TargetInstrInfo *TII,
02713                                          const TargetRegisterInfo *TRI) {
02714   const uint16_t *ImpDefs
02715     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
02716   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
02717   if(!ImpDefs && !RegMask)
02718     return false;
02719 
02720   for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
02721        SI != SE; ++SI) {
02722     SUnit *SuccSU = SI->getSUnit();
02723     for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
02724            PE = SuccSU->Preds.end(); PI != PE; ++PI) {
02725       if (!PI->isAssignedRegDep())
02726         continue;
02727 
02728       if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
02729           scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02730         return true;
02731 
02732       if (ImpDefs)
02733         for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
02734           // Return true if SU clobbers this physical register use and the
02735           // definition of the register reaches from DepSU. IsReachable queries
02736           // a topological forward sort of the DAG (following the successors).
02737           if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
02738               scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02739             return true;
02740     }
02741   }
02742   return false;
02743 }
02744 
02745 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
02746 /// physical register defs.
02747 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
02748                                   const TargetInstrInfo *TII,
02749                                   const TargetRegisterInfo *TRI) {
02750   SDNode *N = SuccSU->getNode();
02751   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02752   const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
02753   assert(ImpDefs && "Caller should check hasPhysRegDefs");
02754   for (const SDNode *SUNode = SU->getNode(); SUNode;
02755        SUNode = SUNode->getGluedNode()) {
02756     if (!SUNode->isMachineOpcode())
02757       continue;
02758     const uint16_t *SUImpDefs =
02759       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
02760     const uint32_t *SURegMask = getNodeRegMask(SUNode);
02761     if (!SUImpDefs && !SURegMask)
02762       continue;
02763     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02764       MVT VT = N->getSimpleValueType(i);
02765       if (VT == MVT::Glue || VT == MVT::Other)
02766         continue;
02767       if (!N->hasAnyUseOfValue(i))
02768         continue;
02769       unsigned Reg = ImpDefs[i - NumDefs];
02770       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
02771         return true;
02772       if (!SUImpDefs)
02773         continue;
02774       for (;*SUImpDefs; ++SUImpDefs) {
02775         unsigned SUReg = *SUImpDefs;
02776         if (TRI->regsOverlap(Reg, SUReg))
02777           return true;
02778       }
02779     }
02780   }
02781   return false;
02782 }
02783 
02784 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
02785 /// are not handled well by the general register pressure reduction
02786 /// heuristics. When presented with code like this:
02787 ///
02788 ///      N
02789 ///    / |
02790 ///   /  |
02791 ///  U  store
02792 ///  |
02793 /// ...
02794 ///
02795 /// the heuristics tend to push the store up, but since the
02796 /// operand of the store has another use (U), this would increase
02797 /// the length of that other use (the U->N edge).
02798 ///
02799 /// This function transforms code like the above to route U's
02800 /// dependence through the store when possible, like this:
02801 ///
02802 ///      N
02803 ///      ||
02804 ///      ||
02805 ///     store
02806 ///       |
02807 ///       U
02808 ///       |
02809 ///      ...
02810 ///
02811 /// This results in the store being scheduled immediately
02812 /// after N, which shortens the U->N live range, reducing
02813 /// register pressure.
02814 ///
02815 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
02816   // Visit all the nodes in topological order, working top-down.
02817   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02818     SUnit *SU = &(*SUnits)[i];
02819     // For now, only look at nodes with no data successors, such as stores.
02820     // These are especially important, due to the heuristics in
02821     // getNodePriority for nodes with no data successors.
02822     if (SU->NumSuccs != 0)
02823       continue;
02824     // For now, only look at nodes with exactly one data predecessor.
02825     if (SU->NumPreds != 1)
02826       continue;
02827     // Avoid prescheduling copies to virtual registers, which don't behave
02828     // like other nodes from the perspective of scheduling heuristics.
02829     if (SDNode *N = SU->getNode())
02830       if (N->getOpcode() == ISD::CopyToReg &&
02831           TargetRegisterInfo::isVirtualRegister
02832             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02833         continue;
02834 
02835     // Locate the single data predecessor.
02836     SUnit *PredSU = nullptr;
02837     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
02838          EE = SU->Preds.end(); II != EE; ++II)
02839       if (!II->isCtrl()) {
02840         PredSU = II->getSUnit();
02841         break;
02842       }
02843     assert(PredSU);
02844 
02845     // Don't rewrite edges that carry physregs, because that requires additional
02846     // support infrastructure.
02847     if (PredSU->hasPhysRegDefs)
02848       continue;
02849     // Short-circuit the case where SU is PredSU's only data successor.
02850     if (PredSU->NumSuccs == 1)
02851       continue;
02852     // Avoid prescheduling to copies from virtual registers, which don't behave
02853     // like other nodes from the perspective of scheduling heuristics.
02854     if (SDNode *N = SU->getNode())
02855       if (N->getOpcode() == ISD::CopyFromReg &&
02856           TargetRegisterInfo::isVirtualRegister
02857             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02858         continue;
02859 
02860     // Perform checks on the successors of PredSU.
02861     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
02862          EE = PredSU->Succs.end(); II != EE; ++II) {
02863       SUnit *PredSuccSU = II->getSUnit();
02864       if (PredSuccSU == SU) continue;
02865       // If PredSU has another successor with no data successors, for
02866       // now don't attempt to choose either over the other.
02867       if (PredSuccSU->NumSuccs == 0)
02868         goto outer_loop_continue;
02869       // Don't break physical register dependencies.
02870       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
02871         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
02872           goto outer_loop_continue;
02873       // Don't introduce graph cycles.
02874       if (scheduleDAG->IsReachable(SU, PredSuccSU))
02875         goto outer_loop_continue;
02876     }
02877 
02878     // Ok, the transformation is safe and the heuristics suggest it is
02879     // profitable. Update the graph.
02880     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
02881                  << " next to PredSU #" << PredSU->NodeNum
02882                  << " to guide scheduling in the presence of multiple uses\n");
02883     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
02884       SDep Edge = PredSU->Succs[i];
02885       assert(!Edge.isAssignedRegDep());
02886       SUnit *SuccSU = Edge.getSUnit();
02887       if (SuccSU != SU) {
02888         Edge.setSUnit(PredSU);
02889         scheduleDAG->RemovePred(SuccSU, Edge);
02890         scheduleDAG->AddPred(SU, Edge);
02891         Edge.setSUnit(SU);
02892         scheduleDAG->AddPred(SuccSU, Edge);
02893         --i;
02894       }
02895     }
02896   outer_loop_continue:;
02897   }
02898 }
02899 
02900 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
02901 /// it as a def&use operand. Add a pseudo control edge from it to the other
02902 /// node (if it won't create a cycle) so the two-address one will be scheduled
02903 /// first (lower in the schedule). If both nodes are two-address, favor the
02904 /// one that has a CopyToReg use (more likely to be a loop induction update).
02905 /// If both are two-address, but one is commutable while the other is not
02906 /// commutable, favor the one that's not commutable.
02907 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
02908   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02909     SUnit *SU = &(*SUnits)[i];
02910     if (!SU->isTwoAddress)
02911       continue;
02912 
02913     SDNode *Node = SU->getNode();
02914     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
02915       continue;
02916 
02917     bool isLiveOut = hasOnlyLiveOutUses(SU);
02918     unsigned Opc = Node->getMachineOpcode();
02919     const MCInstrDesc &MCID = TII->get(Opc);
02920     unsigned NumRes = MCID.getNumDefs();
02921     unsigned NumOps = MCID.getNumOperands() - NumRes;
02922     for (unsigned j = 0; j != NumOps; ++j) {
02923       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
02924         continue;
02925       SDNode *DU = SU->getNode()->getOperand(j).getNode();
02926       if (DU->getNodeId() == -1)
02927         continue;
02928       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
02929       if (!DUSU) continue;
02930       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
02931            E = DUSU->Succs.end(); I != E; ++I) {
02932         if (I->isCtrl()) continue;
02933         SUnit *SuccSU = I->getSUnit();
02934         if (SuccSU == SU)
02935           continue;
02936         // Be conservative. Ignore if nodes aren't at roughly the same
02937         // depth and height.
02938         if (SuccSU->getHeight() < SU->getHeight() &&
02939             (SU->getHeight() - SuccSU->getHeight()) > 1)
02940           continue;
02941         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
02942         // constrains whatever is using the copy, instead of the copy
02943         // itself. In the case that the copy is coalesced, this
02944         // preserves the intent of the pseudo two-address heurietics.
02945         while (SuccSU->Succs.size() == 1 &&
02946                SuccSU->getNode()->isMachineOpcode() &&
02947                SuccSU->getNode()->getMachineOpcode() ==
02948                  TargetOpcode::COPY_TO_REGCLASS)
02949           SuccSU = SuccSU->Succs.front().getSUnit();
02950         // Don't constrain non-instruction nodes.
02951         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
02952           continue;
02953         // Don't constrain nodes with physical register defs if the
02954         // predecessor can clobber them.
02955         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
02956           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
02957             continue;
02958         }
02959         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
02960         // these may be coalesced away. We want them close to their uses.
02961         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
02962         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
02963             SuccOpc == TargetOpcode::INSERT_SUBREG ||
02964             SuccOpc == TargetOpcode::SUBREG_TO_REG)
02965           continue;
02966         if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
02967             (!canClobber(SuccSU, DUSU) ||
02968              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
02969              (!SU->isCommutable && SuccSU->isCommutable)) &&
02970             !scheduleDAG->IsReachable(SuccSU, SU)) {
02971           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
02972                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
02973           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Artificial));
02974         }
02975       }
02976     }
02977   }
02978 }
02979 
02980 //===----------------------------------------------------------------------===//
02981 //                         Public Constructor Functions
02982 //===----------------------------------------------------------------------===//
02983 
02984 llvm::ScheduleDAGSDNodes *
02985 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
02986                                  CodeGenOpt::Level OptLevel) {
02987   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
02988   const TargetInstrInfo *TII = STI.getInstrInfo();
02989   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
02990 
02991   BURegReductionPriorityQueue *PQ =
02992     new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
02993   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
02994   PQ->setScheduleDAG(SD);
02995   return SD;
02996 }
02997 
02998 llvm::ScheduleDAGSDNodes *
02999 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
03000                                    CodeGenOpt::Level OptLevel) {
03001   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03002   const TargetInstrInfo *TII = STI.getInstrInfo();
03003   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03004 
03005   SrcRegReductionPriorityQueue *PQ =
03006     new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
03007   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
03008   PQ->setScheduleDAG(SD);
03009   return SD;
03010 }
03011 
03012 llvm::ScheduleDAGSDNodes *
03013 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
03014                                    CodeGenOpt::Level OptLevel) {
03015   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03016   const TargetInstrInfo *TII = STI.getInstrInfo();
03017   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03018   const TargetLowering *TLI = IS->TLI;
03019 
03020   HybridBURRPriorityQueue *PQ =
03021     new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03022 
03023   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03024   PQ->setScheduleDAG(SD);
03025   return SD;
03026 }
03027 
03028 llvm::ScheduleDAGSDNodes *
03029 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
03030                                 CodeGenOpt::Level OptLevel) {
03031   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03032   const TargetInstrInfo *TII = STI.getInstrInfo();
03033   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03034   const TargetLowering *TLI = IS->TLI;
03035 
03036   ILPBURRPriorityQueue *PQ =
03037     new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03038   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03039   PQ->setScheduleDAG(SD);
03040   return SD;
03041 }