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::unique_ptr<SUnit*[]> LiveRegDefs;
00145   std::unique_ptr<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() override {
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.reset(new SUnit*[TRI->getNumRegs() + 1]());
00332   LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
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 (const SDValue &Op : N->op_values())
00419         if (IsChainDependent(Op.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 (const SDValue &Op : N->op_values())
00437       if (Op.getValueType() == MVT::Other) {
00438         N = Op.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 (const SDValue &Op : N->op_values()) {
00468         unsigned MyNestLevel = NestLevel;
00469         unsigned MyMaxNest = MaxNest;
00470         if (SDNode *New = FindCallSeqStart(Op.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 (const SDValue &Op : N->op_values())
00497       if (Op.getValueType() == MVT::Other) {
00498         N = Op.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 (auto &Succ : SU->Succs) {
00852     if (Succ.isAssignedRegDep()) {
00853       auto Reg = Succ.getReg();
00854       if (!LiveRegDefs[Reg])
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[Reg] = SU;
00859 
00860       // Update LiveRegGen only if was empty before this unscheduling.
00861       // This is to avoid incorrect updating LiveRegGen set in previous run.
00862       if (!LiveRegGens[Reg]) {
00863         // Find the successor with the lowest height.
00864         LiveRegGens[Reg] = Succ.getSUnit();
00865         for (auto &Succ2 : SU->Succs) {
00866           if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
00867               Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
00868             LiveRegGens[Reg] = Succ2.getSUnit();
00869         }
00870       }
00871     }
00872   }
00873   if (SU->getHeight() < MinAvailableCycle)
00874     MinAvailableCycle = SU->getHeight();
00875 
00876   SU->setHeightDirty();
00877   SU->isScheduled = false;
00878   SU->isAvailable = true;
00879   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
00880     // Don't make available until backtracking is complete.
00881     SU->isPending = true;
00882     PendingQueue.push_back(SU);
00883   }
00884   else {
00885     AvailableQueue->push(SU);
00886   }
00887   AvailableQueue->unscheduledNode(SU);
00888 }
00889 
00890 /// After backtracking, the hazard checker needs to be restored to a state
00891 /// corresponding the current cycle.
00892 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
00893   HazardRec->Reset();
00894 
00895   unsigned LookAhead = std::min((unsigned)Sequence.size(),
00896                                 HazardRec->getMaxLookAhead());
00897   if (LookAhead == 0)
00898     return;
00899 
00900   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
00901   unsigned HazardCycle = (*I)->getHeight();
00902   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
00903     SUnit *SU = *I;
00904     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
00905       HazardRec->RecedeCycle();
00906     }
00907     EmitNode(SU);
00908   }
00909 }
00910 
00911 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
00912 /// BTCycle in order to schedule a specific node.
00913 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
00914   SUnit *OldSU = Sequence.back();
00915   while (true) {
00916     Sequence.pop_back();
00917     // FIXME: use ready cycle instead of height
00918     CurCycle = OldSU->getHeight();
00919     UnscheduleNodeBottomUp(OldSU);
00920     AvailableQueue->setCurCycle(CurCycle);
00921     if (OldSU == BtSU)
00922       break;
00923     OldSU = Sequence.back();
00924   }
00925 
00926   assert(!SU->isSucc(OldSU) && "Something is wrong!");
00927 
00928   RestoreHazardCheckerBottomUp();
00929 
00930   ReleasePending();
00931 
00932   ++NumBacktracks;
00933 }
00934 
00935 static bool isOperandOf(const SUnit *SU, SDNode *N) {
00936   for (const SDNode *SUNode = SU->getNode(); SUNode;
00937        SUNode = SUNode->getGluedNode()) {
00938     if (SUNode->isOperandOf(N))
00939       return true;
00940   }
00941   return false;
00942 }
00943 
00944 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
00945 /// successors to the newly created node.
00946 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
00947   SDNode *N = SU->getNode();
00948   if (!N)
00949     return nullptr;
00950 
00951   if (SU->getNode()->getGluedNode())
00952     return nullptr;
00953 
00954   SUnit *NewSU;
00955   bool TryUnfold = false;
00956   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
00957     MVT VT = N->getSimpleValueType(i);
00958     if (VT == MVT::Glue)
00959       return nullptr;
00960     else if (VT == MVT::Other)
00961       TryUnfold = true;
00962   }
00963   for (const SDValue &Op : N->op_values()) {
00964     MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
00965     if (VT == MVT::Glue)
00966       return nullptr;
00967   }
00968 
00969   if (TryUnfold) {
00970     SmallVector<SDNode*, 2> NewNodes;
00971     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
00972       return nullptr;
00973 
00974     // unfolding an x86 DEC64m operation results in store, dec, load which
00975     // can't be handled here so quit
00976     if (NewNodes.size() == 3)
00977       return nullptr;
00978 
00979     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
00980     assert(NewNodes.size() == 2 && "Expected a load folding node!");
00981 
00982     N = NewNodes[1];
00983     SDNode *LoadNode = NewNodes[0];
00984     unsigned NumVals = N->getNumValues();
00985     unsigned OldNumVals = SU->getNode()->getNumValues();
00986     for (unsigned i = 0; i != NumVals; ++i)
00987       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
00988     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
00989                                    SDValue(LoadNode, 1));
00990 
00991     // LoadNode may already exist. This can happen when there is another
00992     // load from the same location and producing the same type of value
00993     // but it has different alignment or volatileness.
00994     bool isNewLoad = true;
00995     SUnit *LoadSU;
00996     if (LoadNode->getNodeId() != -1) {
00997       LoadSU = &SUnits[LoadNode->getNodeId()];
00998       isNewLoad = false;
00999     } else {
01000       LoadSU = CreateNewSUnit(LoadNode);
01001       LoadNode->setNodeId(LoadSU->NodeNum);
01002 
01003       InitNumRegDefsLeft(LoadSU);
01004       computeLatency(LoadSU);
01005     }
01006 
01007     SUnit *NewSU = CreateNewSUnit(N);
01008     assert(N->getNodeId() == -1 && "Node already inserted!");
01009     N->setNodeId(NewSU->NodeNum);
01010 
01011     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01012     for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
01013       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
01014         NewSU->isTwoAddress = true;
01015         break;
01016       }
01017     }
01018     if (MCID.isCommutable())
01019       NewSU->isCommutable = true;
01020 
01021     InitNumRegDefsLeft(NewSU);
01022     computeLatency(NewSU);
01023 
01024     // Record all the edges to and from the old SU, by category.
01025     SmallVector<SDep, 4> ChainPreds;
01026     SmallVector<SDep, 4> ChainSuccs;
01027     SmallVector<SDep, 4> LoadPreds;
01028     SmallVector<SDep, 4> NodePreds;
01029     SmallVector<SDep, 4> NodeSuccs;
01030     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01031          I != E; ++I) {
01032       if (I->isCtrl())
01033         ChainPreds.push_back(*I);
01034       else if (isOperandOf(I->getSUnit(), LoadNode))
01035         LoadPreds.push_back(*I);
01036       else
01037         NodePreds.push_back(*I);
01038     }
01039     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01040          I != E; ++I) {
01041       if (I->isCtrl())
01042         ChainSuccs.push_back(*I);
01043       else
01044         NodeSuccs.push_back(*I);
01045     }
01046 
01047     // Now assign edges to the newly-created nodes.
01048     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
01049       const SDep &Pred = ChainPreds[i];
01050       RemovePred(SU, Pred);
01051       if (isNewLoad)
01052         AddPred(LoadSU, Pred);
01053     }
01054     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
01055       const SDep &Pred = LoadPreds[i];
01056       RemovePred(SU, Pred);
01057       if (isNewLoad)
01058         AddPred(LoadSU, Pred);
01059     }
01060     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
01061       const SDep &Pred = NodePreds[i];
01062       RemovePred(SU, Pred);
01063       AddPred(NewSU, Pred);
01064     }
01065     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
01066       SDep D = NodeSuccs[i];
01067       SUnit *SuccDep = D.getSUnit();
01068       D.setSUnit(SU);
01069       RemovePred(SuccDep, D);
01070       D.setSUnit(NewSU);
01071       AddPred(SuccDep, D);
01072       // Balance register pressure.
01073       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
01074           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
01075         --NewSU->NumRegDefsLeft;
01076     }
01077     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
01078       SDep D = ChainSuccs[i];
01079       SUnit *SuccDep = D.getSUnit();
01080       D.setSUnit(SU);
01081       RemovePred(SuccDep, D);
01082       if (isNewLoad) {
01083         D.setSUnit(LoadSU);
01084         AddPred(SuccDep, D);
01085       }
01086     }
01087 
01088     // Add a data dependency to reflect that NewSU reads the value defined
01089     // by LoadSU.
01090     SDep D(LoadSU, SDep::Data, 0);
01091     D.setLatency(LoadSU->Latency);
01092     AddPred(NewSU, D);
01093 
01094     if (isNewLoad)
01095       AvailableQueue->addNode(LoadSU);
01096     AvailableQueue->addNode(NewSU);
01097 
01098     ++NumUnfolds;
01099 
01100     if (NewSU->NumSuccsLeft == 0) {
01101       NewSU->isAvailable = true;
01102       return NewSU;
01103     }
01104     SU = NewSU;
01105   }
01106 
01107   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
01108   NewSU = CreateClone(SU);
01109 
01110   // New SUnit has the exact same predecessors.
01111   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01112        I != E; ++I)
01113     if (!I->isArtificial())
01114       AddPred(NewSU, *I);
01115 
01116   // Only copy scheduled successors. Cut them from old node's successor
01117   // list and move them over.
01118   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01119   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01120        I != E; ++I) {
01121     if (I->isArtificial())
01122       continue;
01123     SUnit *SuccSU = I->getSUnit();
01124     if (SuccSU->isScheduled) {
01125       SDep D = *I;
01126       D.setSUnit(NewSU);
01127       AddPred(SuccSU, D);
01128       D.setSUnit(SU);
01129       DelDeps.push_back(std::make_pair(SuccSU, D));
01130     }
01131   }
01132   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01133     RemovePred(DelDeps[i].first, DelDeps[i].second);
01134 
01135   AvailableQueue->updateNode(SU);
01136   AvailableQueue->addNode(NewSU);
01137 
01138   ++NumDups;
01139   return NewSU;
01140 }
01141 
01142 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
01143 /// scheduled successors of the given SUnit to the last copy.
01144 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
01145                                               const TargetRegisterClass *DestRC,
01146                                               const TargetRegisterClass *SrcRC,
01147                                               SmallVectorImpl<SUnit*> &Copies) {
01148   SUnit *CopyFromSU = CreateNewSUnit(nullptr);
01149   CopyFromSU->CopySrcRC = SrcRC;
01150   CopyFromSU->CopyDstRC = DestRC;
01151 
01152   SUnit *CopyToSU = CreateNewSUnit(nullptr);
01153   CopyToSU->CopySrcRC = DestRC;
01154   CopyToSU->CopyDstRC = SrcRC;
01155 
01156   // Only copy scheduled successors. Cut them from old node's successor
01157   // list and move them over.
01158   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01159   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01160        I != E; ++I) {
01161     if (I->isArtificial())
01162       continue;
01163     SUnit *SuccSU = I->getSUnit();
01164     if (SuccSU->isScheduled) {
01165       SDep D = *I;
01166       D.setSUnit(CopyToSU);
01167       AddPred(SuccSU, D);
01168       DelDeps.push_back(std::make_pair(SuccSU, *I));
01169     }
01170     else {
01171       // Avoid scheduling the def-side copy before other successors. Otherwise
01172       // we could introduce another physreg interference on the copy and
01173       // continue inserting copies indefinitely.
01174       AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
01175     }
01176   }
01177   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01178     RemovePred(DelDeps[i].first, DelDeps[i].second);
01179 
01180   SDep FromDep(SU, SDep::Data, Reg);
01181   FromDep.setLatency(SU->Latency);
01182   AddPred(CopyFromSU, FromDep);
01183   SDep ToDep(CopyFromSU, SDep::Data, 0);
01184   ToDep.setLatency(CopyFromSU->Latency);
01185   AddPred(CopyToSU, ToDep);
01186 
01187   AvailableQueue->updateNode(SU);
01188   AvailableQueue->addNode(CopyFromSU);
01189   AvailableQueue->addNode(CopyToSU);
01190   Copies.push_back(CopyFromSU);
01191   Copies.push_back(CopyToSU);
01192 
01193   ++NumPRCopies;
01194 }
01195 
01196 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
01197 /// definition of the specified node.
01198 /// FIXME: Move to SelectionDAG?
01199 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
01200                                  const TargetInstrInfo *TII) {
01201   unsigned NumRes;
01202   if (N->getOpcode() == ISD::CopyFromReg) {
01203     // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
01204     NumRes = 1;
01205   } else {
01206     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01207     assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
01208     NumRes = MCID.getNumDefs();
01209     for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
01210       if (Reg == *ImpDef)
01211         break;
01212       ++NumRes;
01213     }
01214   }
01215   return N->getSimpleValueType(NumRes);
01216 }
01217 
01218 /// CheckForLiveRegDef - Return true and update live register vector if the
01219 /// specified register def of the specified SUnit clobbers any "live" registers.
01220 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
01221                                SUnit **LiveRegDefs,
01222                                SmallSet<unsigned, 4> &RegAdded,
01223                                SmallVectorImpl<unsigned> &LRegs,
01224                                const TargetRegisterInfo *TRI) {
01225   for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
01226 
01227     // Check if Ref is live.
01228     if (!LiveRegDefs[*AliasI]) continue;
01229 
01230     // Allow multiple uses of the same def.
01231     if (LiveRegDefs[*AliasI] == SU) continue;
01232 
01233     // Add Reg to the set of interfering live regs.
01234     if (RegAdded.insert(*AliasI).second) {
01235       LRegs.push_back(*AliasI);
01236     }
01237   }
01238 }
01239 
01240 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
01241 /// by RegMask, and add them to LRegs.
01242 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
01243                                      ArrayRef<SUnit*> LiveRegDefs,
01244                                      SmallSet<unsigned, 4> &RegAdded,
01245                                      SmallVectorImpl<unsigned> &LRegs) {
01246   // Look at all live registers. Skip Reg0 and the special CallResource.
01247   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
01248     if (!LiveRegDefs[i]) continue;
01249     if (LiveRegDefs[i] == SU) continue;
01250     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
01251     if (RegAdded.insert(i).second)
01252       LRegs.push_back(i);
01253   }
01254 }
01255 
01256 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
01257 static const uint32_t *getNodeRegMask(const SDNode *N) {
01258   for (const SDValue &Op : N->op_values())
01259     if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
01260       return RegOp->getRegMask();
01261   return nullptr;
01262 }
01263 
01264 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
01265 /// scheduling of the given node to satisfy live physical register dependencies.
01266 /// If the specific node is the last one that's available to schedule, do
01267 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
01268 bool ScheduleDAGRRList::
01269 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
01270   if (NumLiveRegs == 0)
01271     return false;
01272 
01273   SmallSet<unsigned, 4> RegAdded;
01274   // If this node would clobber any "live" register, then it's not ready.
01275   //
01276   // If SU is the currently live definition of the same register that it uses,
01277   // then we are free to schedule it.
01278   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01279        I != E; ++I) {
01280     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
01281       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs.get(),
01282                          RegAdded, LRegs, TRI);
01283   }
01284 
01285   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
01286     if (Node->getOpcode() == ISD::INLINEASM) {
01287       // Inline asm can clobber physical defs.
01288       unsigned NumOps = Node->getNumOperands();
01289       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
01290         --NumOps;  // Ignore the glue operand.
01291 
01292       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
01293         unsigned Flags =
01294           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
01295         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
01296 
01297         ++i; // Skip the ID value.
01298         if (InlineAsm::isRegDefKind(Flags) ||
01299             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
01300             InlineAsm::isClobberKind(Flags)) {
01301           // Check for def of register or earlyclobber register.
01302           for (; NumVals; --NumVals, ++i) {
01303             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
01304             if (TargetRegisterInfo::isPhysicalRegister(Reg))
01305               CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
01306           }
01307         } else
01308           i += NumVals;
01309       }
01310       continue;
01311     }
01312 
01313     if (!Node->isMachineOpcode())
01314       continue;
01315     // If we're in the middle of scheduling a call, don't begin scheduling
01316     // another call. Also, don't allow any physical registers to be live across
01317     // the call.
01318     if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
01319       // Check the special calling-sequence resource.
01320       unsigned CallResource = TRI->getNumRegs();
01321       if (LiveRegDefs[CallResource]) {
01322         SDNode *Gen = LiveRegGens[CallResource]->getNode();
01323         while (SDNode *Glued = Gen->getGluedNode())
01324           Gen = Glued;
01325         if (!IsChainDependent(Gen, Node, 0, TII) &&
01326             RegAdded.insert(CallResource).second)
01327           LRegs.push_back(CallResource);
01328       }
01329     }
01330     if (const uint32_t *RegMask = getNodeRegMask(Node))
01331       CheckForLiveRegDefMasked(SU, RegMask,
01332                                makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
01333                                RegAdded, LRegs);
01334 
01335     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
01336     if (!MCID.ImplicitDefs)
01337       continue;
01338     for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
01339       CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
01340   }
01341 
01342   return !LRegs.empty();
01343 }
01344 
01345 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
01346   // Add the nodes that aren't ready back onto the available list.
01347   for (unsigned i = Interferences.size(); i > 0; --i) {
01348     SUnit *SU = Interferences[i-1];
01349     LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
01350     if (Reg) {
01351       SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
01352       if (std::find(LRegs.begin(), LRegs.end(), Reg) == LRegs.end())
01353         continue;
01354     }
01355     SU->isPending = false;
01356     // The interfering node may no longer be available due to backtracking.
01357     // Furthermore, it may have been made available again, in which case it is
01358     // now already in the AvailableQueue.
01359     if (SU->isAvailable && !SU->NodeQueueId) {
01360       DEBUG(dbgs() << "    Repushing SU #" << SU->NodeNum << '\n');
01361       AvailableQueue->push(SU);
01362     }
01363     if (i < Interferences.size())
01364       Interferences[i-1] = Interferences.back();
01365     Interferences.pop_back();
01366     LRegsMap.erase(LRegsPos);
01367   }
01368 }
01369 
01370 /// Return a node that can be scheduled in this cycle. Requirements:
01371 /// (1) Ready: latency has been satisfied
01372 /// (2) No Hazards: resources are available
01373 /// (3) No Interferences: may unschedule to break register interferences.
01374 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
01375   SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
01376   while (CurSU) {
01377     SmallVector<unsigned, 4> LRegs;
01378     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
01379       break;
01380     DEBUG(dbgs() << "    Interfering reg " <<
01381           (LRegs[0] == TRI->getNumRegs() ? "CallResource"
01382            : TRI->getName(LRegs[0]))
01383            << " SU #" << CurSU->NodeNum << '\n');
01384     std::pair<LRegsMapT::iterator, bool> LRegsPair =
01385       LRegsMap.insert(std::make_pair(CurSU, LRegs));
01386     if (LRegsPair.second) {
01387       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
01388       Interferences.push_back(CurSU);
01389     }
01390     else {
01391       assert(CurSU->isPending && "Interferences are pending");
01392       // Update the interference with current live regs.
01393       LRegsPair.first->second = LRegs;
01394     }
01395     CurSU = AvailableQueue->pop();
01396   }
01397   if (CurSU)
01398     return CurSU;
01399 
01400   // All candidates are delayed due to live physical reg dependencies.
01401   // Try backtracking, code duplication, or inserting cross class copies
01402   // to resolve it.
01403   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
01404     SUnit *TrySU = Interferences[i];
01405     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01406 
01407     // Try unscheduling up to the point where it's safe to schedule
01408     // this node.
01409     SUnit *BtSU = nullptr;
01410     unsigned LiveCycle = UINT_MAX;
01411     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
01412       unsigned Reg = LRegs[j];
01413       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
01414         BtSU = LiveRegGens[Reg];
01415         LiveCycle = BtSU->getHeight();
01416       }
01417     }
01418     if (!WillCreateCycle(TrySU, BtSU))  {
01419       // BacktrackBottomUp mutates Interferences!
01420       BacktrackBottomUp(TrySU, BtSU);
01421 
01422       // Force the current node to be scheduled before the node that
01423       // requires the physical reg dep.
01424       if (BtSU->isAvailable) {
01425         BtSU->isAvailable = false;
01426         if (!BtSU->isPending)
01427           AvailableQueue->remove(BtSU);
01428       }
01429       DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
01430             << TrySU->NodeNum << ")\n");
01431       AddPred(TrySU, SDep(BtSU, SDep::Artificial));
01432 
01433       // If one or more successors has been unscheduled, then the current
01434       // node is no longer available.
01435       if (!TrySU->isAvailable || !TrySU->NodeQueueId)
01436         CurSU = AvailableQueue->pop();
01437       else {
01438         // Available and in AvailableQueue
01439         AvailableQueue->remove(TrySU);
01440         CurSU = TrySU;
01441       }
01442       // Interferences has been mutated. We must break.
01443       break;
01444     }
01445   }
01446 
01447   if (!CurSU) {
01448     // Can't backtrack. If it's too expensive to copy the value, then try
01449     // duplicate the nodes that produces these "too expensive to copy"
01450     // values to break the dependency. In case even that doesn't work,
01451     // insert cross class copies.
01452     // If it's not too expensive, i.e. cost != -1, issue copies.
01453     SUnit *TrySU = Interferences[0];
01454     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01455     assert(LRegs.size() == 1 && "Can't handle this yet!");
01456     unsigned Reg = LRegs[0];
01457     SUnit *LRDef = LiveRegDefs[Reg];
01458     MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
01459     const TargetRegisterClass *RC =
01460       TRI->getMinimalPhysRegClass(Reg, VT);
01461     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
01462 
01463     // If cross copy register class is the same as RC, then it must be possible
01464     // copy the value directly. Do not try duplicate the def.
01465     // If cross copy register class is not the same as RC, then it's possible to
01466     // copy the value but it require cross register class copies and it is
01467     // expensive.
01468     // If cross copy register class is null, then it's not possible to copy
01469     // the value at all.
01470     SUnit *NewDef = nullptr;
01471     if (DestRC != RC) {
01472       NewDef = CopyAndMoveSuccessors(LRDef);
01473       if (!DestRC && !NewDef)
01474         report_fatal_error("Can't handle live physical register dependency!");
01475     }
01476     if (!NewDef) {
01477       // Issue copies, these can be expensive cross register class copies.
01478       SmallVector<SUnit*, 2> Copies;
01479       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
01480       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
01481             << " to SU #" << Copies.front()->NodeNum << "\n");
01482       AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
01483       NewDef = Copies.back();
01484     }
01485 
01486     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
01487           << " to SU #" << TrySU->NodeNum << "\n");
01488     LiveRegDefs[Reg] = NewDef;
01489     AddPred(NewDef, SDep(TrySU, SDep::Artificial));
01490     TrySU->isAvailable = false;
01491     CurSU = NewDef;
01492   }
01493   assert(CurSU && "Unable to resolve live physical register dependencies!");
01494   return CurSU;
01495 }
01496 
01497 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
01498 /// schedulers.
01499 void ScheduleDAGRRList::ListScheduleBottomUp() {
01500   // Release any predecessors of the special Exit node.
01501   ReleasePredecessors(&ExitSU);
01502 
01503   // Add root to Available queue.
01504   if (!SUnits.empty()) {
01505     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
01506     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
01507     RootSU->isAvailable = true;
01508     AvailableQueue->push(RootSU);
01509   }
01510 
01511   // While Available queue is not empty, grab the node with the highest
01512   // priority. If it is not ready put it back.  Schedule the node.
01513   Sequence.reserve(SUnits.size());
01514   while (!AvailableQueue->empty() || !Interferences.empty()) {
01515     DEBUG(dbgs() << "\nExamining Available:\n";
01516           AvailableQueue->dump(this));
01517 
01518     // Pick the best node to schedule taking all constraints into
01519     // consideration.
01520     SUnit *SU = PickNodeToScheduleBottomUp();
01521 
01522     AdvancePastStalls(SU);
01523 
01524     ScheduleNodeBottomUp(SU);
01525 
01526     while (AvailableQueue->empty() && !PendingQueue.empty()) {
01527       // Advance the cycle to free resources. Skip ahead to the next ready SU.
01528       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
01529       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
01530     }
01531   }
01532 
01533   // Reverse the order if it is bottom up.
01534   std::reverse(Sequence.begin(), Sequence.end());
01535 
01536 #ifndef NDEBUG
01537   VerifyScheduledSequence(/*isBottomUp=*/true);
01538 #endif
01539 }
01540 
01541 //===----------------------------------------------------------------------===//
01542 //                RegReductionPriorityQueue Definition
01543 //===----------------------------------------------------------------------===//
01544 //
01545 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
01546 // to reduce register pressure.
01547 //
01548 namespace {
01549 class RegReductionPQBase;
01550 
01551 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
01552   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
01553 };
01554 
01555 #ifndef NDEBUG
01556 template<class SF>
01557 struct reverse_sort : public queue_sort {
01558   SF &SortFunc;
01559   reverse_sort(SF &sf) : SortFunc(sf) {}
01560 
01561   bool operator()(SUnit* left, SUnit* right) const {
01562     // reverse left/right rather than simply !SortFunc(left, right)
01563     // to expose different paths in the comparison logic.
01564     return SortFunc(right, left);
01565   }
01566 };
01567 #endif // NDEBUG
01568 
01569 /// bu_ls_rr_sort - Priority function for bottom up register pressure
01570 // reduction scheduler.
01571 struct bu_ls_rr_sort : public queue_sort {
01572   enum {
01573     IsBottomUp = true,
01574     HasReadyFilter = false
01575   };
01576 
01577   RegReductionPQBase *SPQ;
01578   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
01579 
01580   bool operator()(SUnit* left, SUnit* right) const;
01581 };
01582 
01583 // src_ls_rr_sort - Priority function for source order scheduler.
01584 struct src_ls_rr_sort : public queue_sort {
01585   enum {
01586     IsBottomUp = true,
01587     HasReadyFilter = false
01588   };
01589 
01590   RegReductionPQBase *SPQ;
01591   src_ls_rr_sort(RegReductionPQBase *spq)
01592     : SPQ(spq) {}
01593 
01594   bool operator()(SUnit* left, SUnit* right) const;
01595 };
01596 
01597 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
01598 struct hybrid_ls_rr_sort : public queue_sort {
01599   enum {
01600     IsBottomUp = true,
01601     HasReadyFilter = false
01602   };
01603 
01604   RegReductionPQBase *SPQ;
01605   hybrid_ls_rr_sort(RegReductionPQBase *spq)
01606     : SPQ(spq) {}
01607 
01608   bool isReady(SUnit *SU, unsigned CurCycle) const;
01609 
01610   bool operator()(SUnit* left, SUnit* right) const;
01611 };
01612 
01613 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
01614 // scheduler.
01615 struct ilp_ls_rr_sort : public queue_sort {
01616   enum {
01617     IsBottomUp = true,
01618     HasReadyFilter = false
01619   };
01620 
01621   RegReductionPQBase *SPQ;
01622   ilp_ls_rr_sort(RegReductionPQBase *spq)
01623     : SPQ(spq) {}
01624 
01625   bool isReady(SUnit *SU, unsigned CurCycle) const;
01626 
01627   bool operator()(SUnit* left, SUnit* right) const;
01628 };
01629 
01630 class RegReductionPQBase : public SchedulingPriorityQueue {
01631 protected:
01632   std::vector<SUnit*> Queue;
01633   unsigned CurQueueId;
01634   bool TracksRegPressure;
01635   bool SrcOrder;
01636 
01637   // SUnits - The SUnits for the current graph.
01638   std::vector<SUnit> *SUnits;
01639 
01640   MachineFunction &MF;
01641   const TargetInstrInfo *TII;
01642   const TargetRegisterInfo *TRI;
01643   const TargetLowering *TLI;
01644   ScheduleDAGRRList *scheduleDAG;
01645 
01646   // SethiUllmanNumbers - The SethiUllman number for each node.
01647   std::vector<unsigned> SethiUllmanNumbers;
01648 
01649   /// RegPressure - Tracking current reg pressure per register class.
01650   ///
01651   std::vector<unsigned> RegPressure;
01652 
01653   /// RegLimit - Tracking the number of allocatable registers per register
01654   /// class.
01655   std::vector<unsigned> RegLimit;
01656 
01657 public:
01658   RegReductionPQBase(MachineFunction &mf,
01659                      bool hasReadyFilter,
01660                      bool tracksrp,
01661                      bool srcorder,
01662                      const TargetInstrInfo *tii,
01663                      const TargetRegisterInfo *tri,
01664                      const TargetLowering *tli)
01665     : SchedulingPriorityQueue(hasReadyFilter),
01666       CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
01667       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
01668     if (TracksRegPressure) {
01669       unsigned NumRC = TRI->getNumRegClasses();
01670       RegLimit.resize(NumRC);
01671       RegPressure.resize(NumRC);
01672       std::fill(RegLimit.begin(), RegLimit.end(), 0);
01673       std::fill(RegPressure.begin(), RegPressure.end(), 0);
01674       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01675              E = TRI->regclass_end(); I != E; ++I)
01676         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
01677     }
01678   }
01679 
01680   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
01681     scheduleDAG = scheduleDag;
01682   }
01683 
01684   ScheduleHazardRecognizer* getHazardRec() {
01685     return scheduleDAG->getHazardRec();
01686   }
01687 
01688   void initNodes(std::vector<SUnit> &sunits) override;
01689 
01690   void addNode(const SUnit *SU) override;
01691 
01692   void updateNode(const SUnit *SU) override;
01693 
01694   void releaseState() override {
01695     SUnits = nullptr;
01696     SethiUllmanNumbers.clear();
01697     std::fill(RegPressure.begin(), RegPressure.end(), 0);
01698   }
01699 
01700   unsigned getNodePriority(const SUnit *SU) const;
01701 
01702   unsigned getNodeOrdering(const SUnit *SU) const {
01703     if (!SU->getNode()) return 0;
01704 
01705     return SU->getNode()->getIROrder();
01706   }
01707 
01708   bool empty() const override { return Queue.empty(); }
01709 
01710   void push(SUnit *U) override {
01711     assert(!U->NodeQueueId && "Node in the queue already");
01712     U->NodeQueueId = ++CurQueueId;
01713     Queue.push_back(U);
01714   }
01715 
01716   void remove(SUnit *SU) override {
01717     assert(!Queue.empty() && "Queue is empty!");
01718     assert(SU->NodeQueueId != 0 && "Not in queue!");
01719     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
01720                                                  SU);
01721     if (I != std::prev(Queue.end()))
01722       std::swap(*I, Queue.back());
01723     Queue.pop_back();
01724     SU->NodeQueueId = 0;
01725   }
01726 
01727   bool tracksRegPressure() const override { return TracksRegPressure; }
01728 
01729   void dumpRegPressure() const;
01730 
01731   bool HighRegPressure(const SUnit *SU) const;
01732 
01733   bool MayReduceRegPressure(SUnit *SU) const;
01734 
01735   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
01736 
01737   void scheduledNode(SUnit *SU) override;
01738 
01739   void unscheduledNode(SUnit *SU) override;
01740 
01741 protected:
01742   bool canClobber(const SUnit *SU, const SUnit *Op);
01743   void AddPseudoTwoAddrDeps();
01744   void PrescheduleNodesWithMultipleUses();
01745   void CalculateSethiUllmanNumbers();
01746 };
01747 
01748 template<class SF>
01749 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
01750   std::vector<SUnit *>::iterator Best = Q.begin();
01751   for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
01752          E = Q.end(); I != E; ++I)
01753     if (Picker(*Best, *I))
01754       Best = I;
01755   SUnit *V = *Best;
01756   if (Best != std::prev(Q.end()))
01757     std::swap(*Best, Q.back());
01758   Q.pop_back();
01759   return V;
01760 }
01761 
01762 template<class SF>
01763 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
01764 #ifndef NDEBUG
01765   if (DAG->StressSched) {
01766     reverse_sort<SF> RPicker(Picker);
01767     return popFromQueueImpl(Q, RPicker);
01768   }
01769 #endif
01770   (void)DAG;
01771   return popFromQueueImpl(Q, Picker);
01772 }
01773 
01774 template<class SF>
01775 class RegReductionPriorityQueue : public RegReductionPQBase {
01776   SF Picker;
01777 
01778 public:
01779   RegReductionPriorityQueue(MachineFunction &mf,
01780                             bool tracksrp,
01781                             bool srcorder,
01782                             const TargetInstrInfo *tii,
01783                             const TargetRegisterInfo *tri,
01784                             const TargetLowering *tli)
01785     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
01786                          tii, tri, tli),
01787       Picker(this) {}
01788 
01789   bool isBottomUp() const override { return SF::IsBottomUp; }
01790 
01791   bool isReady(SUnit *U) const override {
01792     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
01793   }
01794 
01795   SUnit *pop() override {
01796     if (Queue.empty()) return nullptr;
01797 
01798     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
01799     V->NodeQueueId = 0;
01800     return V;
01801   }
01802 
01803 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01804   void dump(ScheduleDAG *DAG) const override {
01805     // Emulate pop() without clobbering NodeQueueIds.
01806     std::vector<SUnit*> DumpQueue = Queue;
01807     SF DumpPicker = Picker;
01808     while (!DumpQueue.empty()) {
01809       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
01810       dbgs() << "Height " << SU->getHeight() << ": ";
01811       SU->dump(DAG);
01812     }
01813   }
01814 #endif
01815 };
01816 
01817 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
01818 BURegReductionPriorityQueue;
01819 
01820 typedef RegReductionPriorityQueue<src_ls_rr_sort>
01821 SrcRegReductionPriorityQueue;
01822 
01823 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
01824 HybridBURRPriorityQueue;
01825 
01826 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
01827 ILPBURRPriorityQueue;
01828 } // end anonymous namespace
01829 
01830 //===----------------------------------------------------------------------===//
01831 //           Static Node Priority for Register Pressure Reduction
01832 //===----------------------------------------------------------------------===//
01833 
01834 // Check for special nodes that bypass scheduling heuristics.
01835 // Currently this pushes TokenFactor nodes down, but may be used for other
01836 // pseudo-ops as well.
01837 //
01838 // Return -1 to schedule right above left, 1 for left above right.
01839 // Return 0 if no bias exists.
01840 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
01841   bool LSchedLow = left->isScheduleLow;
01842   bool RSchedLow = right->isScheduleLow;
01843   if (LSchedLow != RSchedLow)
01844     return LSchedLow < RSchedLow ? 1 : -1;
01845   return 0;
01846 }
01847 
01848 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
01849 /// Smaller number is the higher priority.
01850 static unsigned
01851 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
01852   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
01853   if (SethiUllmanNumber != 0)
01854     return SethiUllmanNumber;
01855 
01856   unsigned Extra = 0;
01857   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01858        I != E; ++I) {
01859     if (I->isCtrl()) continue;  // ignore chain preds
01860     SUnit *PredSU = I->getSUnit();
01861     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
01862     if (PredSethiUllman > SethiUllmanNumber) {
01863       SethiUllmanNumber = PredSethiUllman;
01864       Extra = 0;
01865     } else if (PredSethiUllman == SethiUllmanNumber)
01866       ++Extra;
01867   }
01868 
01869   SethiUllmanNumber += Extra;
01870 
01871   if (SethiUllmanNumber == 0)
01872     SethiUllmanNumber = 1;
01873 
01874   return SethiUllmanNumber;
01875 }
01876 
01877 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
01878 /// scheduling units.
01879 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
01880   SethiUllmanNumbers.assign(SUnits->size(), 0);
01881 
01882   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
01883     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
01884 }
01885 
01886 void RegReductionPQBase::addNode(const SUnit *SU) {
01887   unsigned SUSize = SethiUllmanNumbers.size();
01888   if (SUnits->size() > SUSize)
01889     SethiUllmanNumbers.resize(SUSize*2, 0);
01890   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01891 }
01892 
01893 void RegReductionPQBase::updateNode(const SUnit *SU) {
01894   SethiUllmanNumbers[SU->NodeNum] = 0;
01895   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01896 }
01897 
01898 // Lower priority means schedule further down. For bottom-up scheduling, lower
01899 // priority SUs are scheduled before higher priority SUs.
01900 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
01901   assert(SU->NodeNum < SethiUllmanNumbers.size());
01902   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
01903   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
01904     // CopyToReg should be close to its uses to facilitate coalescing and
01905     // avoid spilling.
01906     return 0;
01907   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
01908       Opc == TargetOpcode::SUBREG_TO_REG ||
01909       Opc == TargetOpcode::INSERT_SUBREG)
01910     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
01911     // close to their uses to facilitate coalescing.
01912     return 0;
01913   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
01914     // If SU does not have a register use, i.e. it doesn't produce a value
01915     // that would be consumed (e.g. store), then it terminates a chain of
01916     // computation.  Give it a large SethiUllman number so it will be
01917     // scheduled right before its predecessors that it doesn't lengthen
01918     // their live ranges.
01919     return 0xffff;
01920   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
01921     // If SU does not have a register def, schedule it close to its uses
01922     // because it does not lengthen any live ranges.
01923     return 0;
01924 #if 1
01925   return SethiUllmanNumbers[SU->NodeNum];
01926 #else
01927   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
01928   if (SU->isCallOp) {
01929     // FIXME: This assumes all of the defs are used as call operands.
01930     int NP = (int)Priority - SU->getNode()->getNumValues();
01931     return (NP > 0) ? NP : 0;
01932   }
01933   return Priority;
01934 #endif
01935 }
01936 
01937 //===----------------------------------------------------------------------===//
01938 //                     Register Pressure Tracking
01939 //===----------------------------------------------------------------------===//
01940 
01941 void RegReductionPQBase::dumpRegPressure() const {
01942 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01943   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01944          E = TRI->regclass_end(); I != E; ++I) {
01945     const TargetRegisterClass *RC = *I;
01946     unsigned Id = RC->getID();
01947     unsigned RP = RegPressure[Id];
01948     if (!RP) continue;
01949     DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
01950           << RegLimit[Id] << '\n');
01951   }
01952 #endif
01953 }
01954 
01955 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
01956   if (!TLI)
01957     return false;
01958 
01959   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
01960        I != E; ++I) {
01961     if (I->isCtrl())
01962       continue;
01963     SUnit *PredSU = I->getSUnit();
01964     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
01965     // to cover the number of registers defined (they are all live).
01966     if (PredSU->NumRegDefsLeft == 0) {
01967       continue;
01968     }
01969     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
01970          RegDefPos.IsValid(); RegDefPos.Advance()) {
01971       unsigned RCId, Cost;
01972       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
01973 
01974       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
01975         return true;
01976     }
01977   }
01978   return false;
01979 }
01980 
01981 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
01982   const SDNode *N = SU->getNode();
01983 
01984   if (!N->isMachineOpcode() || !SU->NumSuccs)
01985     return false;
01986 
01987   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
01988   for (unsigned i = 0; i != NumDefs; ++i) {
01989     MVT VT = N->getSimpleValueType(i);
01990     if (!N->hasAnyUseOfValue(i))
01991       continue;
01992     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
01993     if (RegPressure[RCId] >= RegLimit[RCId])
01994       return true;
01995   }
01996   return false;
01997 }
01998 
01999 // Compute the register pressure contribution by this instruction by count up
02000 // for uses that are not live and down for defs. Only count register classes
02001 // that are already under high pressure. As a side effect, compute the number of
02002 // uses of registers that are already live.
02003 //
02004 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
02005 // so could probably be factored.
02006 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
02007   LiveUses = 0;
02008   int PDiff = 0;
02009   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02010        I != E; ++I) {
02011     if (I->isCtrl())
02012       continue;
02013     SUnit *PredSU = I->getSUnit();
02014     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02015     // to cover the number of registers defined (they are all live).
02016     if (PredSU->NumRegDefsLeft == 0) {
02017       if (PredSU->getNode()->isMachineOpcode())
02018         ++LiveUses;
02019       continue;
02020     }
02021     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02022          RegDefPos.IsValid(); RegDefPos.Advance()) {
02023       MVT VT = RegDefPos.GetValue();
02024       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02025       if (RegPressure[RCId] >= RegLimit[RCId])
02026         ++PDiff;
02027     }
02028   }
02029   const SDNode *N = SU->getNode();
02030 
02031   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
02032     return PDiff;
02033 
02034   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02035   for (unsigned i = 0; i != NumDefs; ++i) {
02036     MVT VT = N->getSimpleValueType(i);
02037     if (!N->hasAnyUseOfValue(i))
02038       continue;
02039     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02040     if (RegPressure[RCId] >= RegLimit[RCId])
02041       --PDiff;
02042   }
02043   return PDiff;
02044 }
02045 
02046 void RegReductionPQBase::scheduledNode(SUnit *SU) {
02047   if (!TracksRegPressure)
02048     return;
02049 
02050   if (!SU->getNode())
02051     return;
02052 
02053   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02054        I != E; ++I) {
02055     if (I->isCtrl())
02056       continue;
02057     SUnit *PredSU = I->getSUnit();
02058     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02059     // to cover the number of registers defined (they are all live).
02060     if (PredSU->NumRegDefsLeft == 0) {
02061       continue;
02062     }
02063     // FIXME: The ScheduleDAG currently loses information about which of a
02064     // node's values is consumed by each dependence. Consequently, if the node
02065     // defines multiple register classes, we don't know which to pressurize
02066     // here. Instead the following loop consumes the register defs in an
02067     // arbitrary order. At least it handles the common case of clustered loads
02068     // to the same class. For precise liveness, each SDep needs to indicate the
02069     // result number. But that tightly couples the ScheduleDAG with the
02070     // SelectionDAG making updates tricky. A simpler hack would be to attach a
02071     // value type or register class to SDep.
02072     //
02073     // The most important aspect of register tracking is balancing the increase
02074     // here with the reduction further below. Note that this SU may use multiple
02075     // defs in PredSU. The can't be determined here, but we've already
02076     // compensated by reducing NumRegDefsLeft in PredSU during
02077     // ScheduleDAGSDNodes::AddSchedEdges.
02078     --PredSU->NumRegDefsLeft;
02079     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
02080     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02081          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02082       if (SkipRegDefs)
02083         continue;
02084 
02085       unsigned RCId, Cost;
02086       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02087       RegPressure[RCId] += Cost;
02088       break;
02089     }
02090   }
02091 
02092   // We should have this assert, but there may be dead SDNodes that never
02093   // materialize as SUnits, so they don't appear to generate liveness.
02094   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
02095   int SkipRegDefs = (int)SU->NumRegDefsLeft;
02096   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
02097        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02098     if (SkipRegDefs > 0)
02099       continue;
02100     unsigned RCId, Cost;
02101     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02102     if (RegPressure[RCId] < Cost) {
02103       // Register pressure tracking is imprecise. This can happen. But we try
02104       // hard not to let it happen because it likely results in poor scheduling.
02105       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
02106       RegPressure[RCId] = 0;
02107     }
02108     else {
02109       RegPressure[RCId] -= Cost;
02110     }
02111   }
02112   dumpRegPressure();
02113 }
02114 
02115 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
02116   if (!TracksRegPressure)
02117     return;
02118 
02119   const SDNode *N = SU->getNode();
02120   if (!N) return;
02121 
02122   if (!N->isMachineOpcode()) {
02123     if (N->getOpcode() != ISD::CopyToReg)
02124       return;
02125   } else {
02126     unsigned Opc = N->getMachineOpcode();
02127     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02128         Opc == TargetOpcode::INSERT_SUBREG ||
02129         Opc == TargetOpcode::SUBREG_TO_REG ||
02130         Opc == TargetOpcode::REG_SEQUENCE ||
02131         Opc == TargetOpcode::IMPLICIT_DEF)
02132       return;
02133   }
02134 
02135   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02136        I != E; ++I) {
02137     if (I->isCtrl())
02138       continue;
02139     SUnit *PredSU = I->getSUnit();
02140     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
02141     // counts data deps.
02142     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
02143       continue;
02144     const SDNode *PN = PredSU->getNode();
02145     if (!PN->isMachineOpcode()) {
02146       if (PN->getOpcode() == ISD::CopyFromReg) {
02147         MVT VT = PN->getSimpleValueType(0);
02148         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02149         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02150       }
02151       continue;
02152     }
02153     unsigned POpc = PN->getMachineOpcode();
02154     if (POpc == TargetOpcode::IMPLICIT_DEF)
02155       continue;
02156     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
02157         POpc == TargetOpcode::INSERT_SUBREG ||
02158         POpc == TargetOpcode::SUBREG_TO_REG) {
02159       MVT VT = PN->getSimpleValueType(0);
02160       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02161       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02162       continue;
02163     }
02164     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
02165     for (unsigned i = 0; i != NumDefs; ++i) {
02166       MVT VT = PN->getSimpleValueType(i);
02167       if (!PN->hasAnyUseOfValue(i))
02168         continue;
02169       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02170       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
02171         // Register pressure tracking is imprecise. This can happen.
02172         RegPressure[RCId] = 0;
02173       else
02174         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
02175     }
02176   }
02177 
02178   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
02179   // may transfer data dependencies to CopyToReg.
02180   if (SU->NumSuccs && N->isMachineOpcode()) {
02181     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02182     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02183       MVT VT = N->getSimpleValueType(i);
02184       if (VT == MVT::Glue || VT == MVT::Other)
02185         continue;
02186       if (!N->hasAnyUseOfValue(i))
02187         continue;
02188       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02189       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02190     }
02191   }
02192 
02193   dumpRegPressure();
02194 }
02195 
02196 //===----------------------------------------------------------------------===//
02197 //           Dynamic Node Priority for Register Pressure Reduction
02198 //===----------------------------------------------------------------------===//
02199 
02200 /// closestSucc - Returns the scheduled cycle of the successor which is
02201 /// closest to the current cycle.
02202 static unsigned closestSucc(const SUnit *SU) {
02203   unsigned MaxHeight = 0;
02204   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02205        I != E; ++I) {
02206     if (I->isCtrl()) continue;  // ignore chain succs
02207     unsigned Height = I->getSUnit()->getHeight();
02208     // If there are bunch of CopyToRegs stacked up, they should be considered
02209     // to be at the same position.
02210     if (I->getSUnit()->getNode() &&
02211         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
02212       Height = closestSucc(I->getSUnit())+1;
02213     if (Height > MaxHeight)
02214       MaxHeight = Height;
02215   }
02216   return MaxHeight;
02217 }
02218 
02219 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
02220 /// for scratch registers, i.e. number of data dependencies.
02221 static unsigned calcMaxScratches(const SUnit *SU) {
02222   unsigned Scratches = 0;
02223   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02224        I != E; ++I) {
02225     if (I->isCtrl()) continue;  // ignore chain preds
02226     Scratches++;
02227   }
02228   return Scratches;
02229 }
02230 
02231 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
02232 /// CopyFromReg from a virtual register.
02233 static bool hasOnlyLiveInOpers(const SUnit *SU) {
02234   bool RetVal = false;
02235   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02236        I != E; ++I) {
02237     if (I->isCtrl()) continue;
02238     const SUnit *PredSU = I->getSUnit();
02239     if (PredSU->getNode() &&
02240         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
02241       unsigned Reg =
02242         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
02243       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02244         RetVal = true;
02245         continue;
02246       }
02247     }
02248     return false;
02249   }
02250   return RetVal;
02251 }
02252 
02253 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
02254 /// CopyToReg to a virtual register. This SU def is probably a liveout and
02255 /// it has no other use. It should be scheduled closer to the terminator.
02256 static bool hasOnlyLiveOutUses(const SUnit *SU) {
02257   bool RetVal = false;
02258   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02259        I != E; ++I) {
02260     if (I->isCtrl()) continue;
02261     const SUnit *SuccSU = I->getSUnit();
02262     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
02263       unsigned Reg =
02264         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
02265       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02266         RetVal = true;
02267         continue;
02268       }
02269     }
02270     return false;
02271   }
02272   return RetVal;
02273 }
02274 
02275 // Set isVRegCycle for a node with only live in opers and live out uses. Also
02276 // set isVRegCycle for its CopyFromReg operands.
02277 //
02278 // This is only relevant for single-block loops, in which case the VRegCycle
02279 // node is likely an induction variable in which the operand and target virtual
02280 // registers should be coalesced (e.g. pre/post increment values). Setting the
02281 // isVRegCycle flag helps the scheduler prioritize other uses of the same
02282 // CopyFromReg so that this node becomes the virtual register "kill". This
02283 // avoids interference between the values live in and out of the block and
02284 // eliminates a copy inside the loop.
02285 static void initVRegCycle(SUnit *SU) {
02286   if (DisableSchedVRegCycle)
02287     return;
02288 
02289   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
02290     return;
02291 
02292   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
02293 
02294   SU->isVRegCycle = true;
02295 
02296   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02297        I != E; ++I) {
02298     if (I->isCtrl()) continue;
02299     I->getSUnit()->isVRegCycle = true;
02300   }
02301 }
02302 
02303 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
02304 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
02305 static void resetVRegCycle(SUnit *SU) {
02306   if (!SU->isVRegCycle)
02307     return;
02308 
02309   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02310        I != E; ++I) {
02311     if (I->isCtrl()) continue;  // ignore chain preds
02312     SUnit *PredSU = I->getSUnit();
02313     if (PredSU->isVRegCycle) {
02314       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
02315              "VRegCycle def must be CopyFromReg");
02316       I->getSUnit()->isVRegCycle = 0;
02317     }
02318   }
02319 }
02320 
02321 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
02322 // means a node that defines the VRegCycle has not been scheduled yet.
02323 static bool hasVRegCycleUse(const SUnit *SU) {
02324   // If this SU also defines the VReg, don't hoist it as a "use".
02325   if (SU->isVRegCycle)
02326     return false;
02327 
02328   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02329        I != E; ++I) {
02330     if (I->isCtrl()) continue;  // ignore chain preds
02331     if (I->getSUnit()->isVRegCycle &&
02332         I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
02333       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
02334       return true;
02335     }
02336   }
02337   return false;
02338 }
02339 
02340 // Check for either a dependence (latency) or resource (hazard) stall.
02341 //
02342 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
02343 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
02344   if ((int)SPQ->getCurCycle() < Height) return true;
02345   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02346       != ScheduleHazardRecognizer::NoHazard)
02347     return true;
02348   return false;
02349 }
02350 
02351 // Return -1 if left has higher priority, 1 if right has higher priority.
02352 // Return 0 if latency-based priority is equivalent.
02353 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
02354                             RegReductionPQBase *SPQ) {
02355   // Scheduling an instruction that uses a VReg whose postincrement has not yet
02356   // been scheduled will induce a copy. Model this as an extra cycle of latency.
02357   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
02358   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
02359   int LHeight = (int)left->getHeight() + LPenalty;
02360   int RHeight = (int)right->getHeight() + RPenalty;
02361 
02362   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
02363     BUHasStall(left, LHeight, SPQ);
02364   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
02365     BUHasStall(right, RHeight, SPQ);
02366 
02367   // If scheduling one of the node will cause a pipeline stall, delay it.
02368   // If scheduling either one of the node will cause a pipeline stall, sort
02369   // them according to their height.
02370   if (LStall) {
02371     if (!RStall)
02372       return 1;
02373     if (LHeight != RHeight)
02374       return LHeight > RHeight ? 1 : -1;
02375   } else if (RStall)
02376     return -1;
02377 
02378   // If either node is scheduling for latency, sort them by height/depth
02379   // and latency.
02380   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
02381                      right->SchedulingPref == Sched::ILP)) {
02382     // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
02383     // is enabled, grouping instructions by cycle, then its height is already
02384     // covered so only its depth matters. We also reach this point if both stall
02385     // but have the same height.
02386     if (!SPQ->getHazardRec()->isEnabled()) {
02387       if (LHeight != RHeight)
02388         return LHeight > RHeight ? 1 : -1;
02389     }
02390     int LDepth = left->getDepth() - LPenalty;
02391     int RDepth = right->getDepth() - RPenalty;
02392     if (LDepth != RDepth) {
02393       DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
02394             << ") depth " << LDepth << " vs SU (" << right->NodeNum
02395             << ") depth " << RDepth << "\n");
02396       return LDepth < RDepth ? 1 : -1;
02397     }
02398     if (left->Latency != right->Latency)
02399       return left->Latency > right->Latency ? 1 : -1;
02400   }
02401   return 0;
02402 }
02403 
02404 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
02405   // Schedule physical register definitions close to their use. This is
02406   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
02407   // long as shortening physreg live ranges is generally good, we can defer
02408   // creating a subtarget hook.
02409   if (!DisableSchedPhysRegJoin) {
02410     bool LHasPhysReg = left->hasPhysRegDefs;
02411     bool RHasPhysReg = right->hasPhysRegDefs;
02412     if (LHasPhysReg != RHasPhysReg) {
02413       #ifndef NDEBUG
02414       static const char *const PhysRegMsg[] = { " has no physreg",
02415                                                 " defines a physreg" };
02416       #endif
02417       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
02418             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
02419             << PhysRegMsg[RHasPhysReg] << "\n");
02420       return LHasPhysReg < RHasPhysReg;
02421     }
02422   }
02423 
02424   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
02425   unsigned LPriority = SPQ->getNodePriority(left);
02426   unsigned RPriority = SPQ->getNodePriority(right);
02427 
02428   // Be really careful about hoisting call operands above previous calls.
02429   // Only allows it if it would reduce register pressure.
02430   if (left->isCall && right->isCallOp) {
02431     unsigned RNumVals = right->getNode()->getNumValues();
02432     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
02433   }
02434   if (right->isCall && left->isCallOp) {
02435     unsigned LNumVals = left->getNode()->getNumValues();
02436     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
02437   }
02438 
02439   if (LPriority != RPriority)
02440     return LPriority > RPriority;
02441 
02442   // One or both of the nodes are calls and their sethi-ullman numbers are the
02443   // same, then keep source order.
02444   if (left->isCall || right->isCall) {
02445     unsigned LOrder = SPQ->getNodeOrdering(left);
02446     unsigned ROrder = SPQ->getNodeOrdering(right);
02447 
02448     // Prefer an ordering where the lower the non-zero order number, the higher
02449     // the preference.
02450     if ((LOrder || ROrder) && LOrder != ROrder)
02451       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02452   }
02453 
02454   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
02455   // e.g.
02456   // t1 = op t2, c1
02457   // t3 = op t4, c2
02458   //
02459   // and the following instructions are both ready.
02460   // t2 = op c3
02461   // t4 = op c4
02462   //
02463   // Then schedule t2 = op first.
02464   // i.e.
02465   // t4 = op c4
02466   // t2 = op c3
02467   // t1 = op t2, c1
02468   // t3 = op t4, c2
02469   //
02470   // This creates more short live intervals.
02471   unsigned LDist = closestSucc(left);
02472   unsigned RDist = closestSucc(right);
02473   if (LDist != RDist)
02474     return LDist < RDist;
02475 
02476   // How many registers becomes live when the node is scheduled.
02477   unsigned LScratch = calcMaxScratches(left);
02478   unsigned RScratch = calcMaxScratches(right);
02479   if (LScratch != RScratch)
02480     return LScratch > RScratch;
02481 
02482   // Comparing latency against a call makes little sense unless the node
02483   // is register pressure-neutral.
02484   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
02485     return (left->NodeQueueId > right->NodeQueueId);
02486 
02487   // Do not compare latencies when one or both of the nodes are calls.
02488   if (!DisableSchedCycles &&
02489       !(left->isCall || right->isCall)) {
02490     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
02491     if (result != 0)
02492       return result > 0;
02493   }
02494   else {
02495     if (left->getHeight() != right->getHeight())
02496       return left->getHeight() > right->getHeight();
02497 
02498     if (left->getDepth() != right->getDepth())
02499       return left->getDepth() < right->getDepth();
02500   }
02501 
02502   assert(left->NodeQueueId && right->NodeQueueId &&
02503          "NodeQueueId cannot be zero");
02504   return (left->NodeQueueId > right->NodeQueueId);
02505 }
02506 
02507 // Bottom up
02508 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02509   if (int res = checkSpecialNodes(left, right))
02510     return res > 0;
02511 
02512   return BURRSort(left, right, SPQ);
02513 }
02514 
02515 // Source order, otherwise bottom up.
02516 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02517   if (int res = checkSpecialNodes(left, right))
02518     return res > 0;
02519 
02520   unsigned LOrder = SPQ->getNodeOrdering(left);
02521   unsigned ROrder = SPQ->getNodeOrdering(right);
02522 
02523   // Prefer an ordering where the lower the non-zero order number, the higher
02524   // the preference.
02525   if ((LOrder || ROrder) && LOrder != ROrder)
02526     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02527 
02528   return BURRSort(left, right, SPQ);
02529 }
02530 
02531 // If the time between now and when the instruction will be ready can cover
02532 // the spill code, then avoid adding it to the ready queue. This gives long
02533 // stalls highest priority and allows hoisting across calls. It should also
02534 // speed up processing the available queue.
02535 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02536   static const unsigned ReadyDelay = 3;
02537 
02538   if (SPQ->MayReduceRegPressure(SU)) return true;
02539 
02540   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
02541 
02542   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
02543       != ScheduleHazardRecognizer::NoHazard)
02544     return false;
02545 
02546   return true;
02547 }
02548 
02549 // Return true if right should be scheduled with higher priority than left.
02550 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02551   if (int res = checkSpecialNodes(left, right))
02552     return res > 0;
02553 
02554   if (left->isCall || right->isCall)
02555     // No way to compute latency of calls.
02556     return BURRSort(left, right, SPQ);
02557 
02558   bool LHigh = SPQ->HighRegPressure(left);
02559   bool RHigh = SPQ->HighRegPressure(right);
02560   // Avoid causing spills. If register pressure is high, schedule for
02561   // register pressure reduction.
02562   if (LHigh && !RHigh) {
02563     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
02564           << right->NodeNum << ")\n");
02565     return true;
02566   }
02567   else if (!LHigh && RHigh) {
02568     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
02569           << left->NodeNum << ")\n");
02570     return false;
02571   }
02572   if (!LHigh && !RHigh) {
02573     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
02574     if (result != 0)
02575       return result > 0;
02576   }
02577   return BURRSort(left, right, SPQ);
02578 }
02579 
02580 // Schedule as many instructions in each cycle as possible. So don't make an
02581 // instruction available unless it is ready in the current cycle.
02582 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02583   if (SU->getHeight() > CurCycle) return false;
02584 
02585   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02586       != ScheduleHazardRecognizer::NoHazard)
02587     return false;
02588 
02589   return true;
02590 }
02591 
02592 static bool canEnableCoalescing(SUnit *SU) {
02593   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
02594   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
02595     // CopyToReg should be close to its uses to facilitate coalescing and
02596     // avoid spilling.
02597     return true;
02598 
02599   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02600       Opc == TargetOpcode::SUBREG_TO_REG ||
02601       Opc == TargetOpcode::INSERT_SUBREG)
02602     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
02603     // close to their uses to facilitate coalescing.
02604     return true;
02605 
02606   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
02607     // If SU does not have a register def, schedule it close to its uses
02608     // because it does not lengthen any live ranges.
02609     return true;
02610 
02611   return false;
02612 }
02613 
02614 // list-ilp is currently an experimental scheduler that allows various
02615 // heuristics to be enabled prior to the normal register reduction logic.
02616 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02617   if (int res = checkSpecialNodes(left, right))
02618     return res > 0;
02619 
02620   if (left->isCall || right->isCall)
02621     // No way to compute latency of calls.
02622     return BURRSort(left, right, SPQ);
02623 
02624   unsigned LLiveUses = 0, RLiveUses = 0;
02625   int LPDiff = 0, RPDiff = 0;
02626   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
02627     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
02628     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
02629   }
02630   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
02631     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
02632           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
02633     return LPDiff > RPDiff;
02634   }
02635 
02636   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
02637     bool LReduce = canEnableCoalescing(left);
02638     bool RReduce = canEnableCoalescing(right);
02639     if (LReduce && !RReduce) return false;
02640     if (RReduce && !LReduce) return true;
02641   }
02642 
02643   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
02644     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
02645           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
02646     return LLiveUses < RLiveUses;
02647   }
02648 
02649   if (!DisableSchedStalls) {
02650     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
02651     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
02652     if (LStall != RStall)
02653       return left->getHeight() > right->getHeight();
02654   }
02655 
02656   if (!DisableSchedCriticalPath) {
02657     int spread = (int)left->getDepth() - (int)right->getDepth();
02658     if (std::abs(spread) > MaxReorderWindow) {
02659       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
02660             << left->getDepth() << " != SU(" << right->NodeNum << "): "
02661             << right->getDepth() << "\n");
02662       return left->getDepth() < right->getDepth();
02663     }
02664   }
02665 
02666   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
02667     int spread = (int)left->getHeight() - (int)right->getHeight();
02668     if (std::abs(spread) > MaxReorderWindow)
02669       return left->getHeight() > right->getHeight();
02670   }
02671 
02672   return BURRSort(left, right, SPQ);
02673 }
02674 
02675 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
02676   SUnits = &sunits;
02677   // Add pseudo dependency edges for two-address nodes.
02678   if (!Disable2AddrHack)
02679     AddPseudoTwoAddrDeps();
02680   // Reroute edges to nodes with multiple uses.
02681   if (!TracksRegPressure && !SrcOrder)
02682     PrescheduleNodesWithMultipleUses();
02683   // Calculate node priorities.
02684   CalculateSethiUllmanNumbers();
02685 
02686   // For single block loops, mark nodes that look like canonical IV increments.
02687   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
02688     for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
02689       initVRegCycle(&sunits[i]);
02690     }
02691   }
02692 }
02693 
02694 //===----------------------------------------------------------------------===//
02695 //                    Preschedule for Register Pressure
02696 //===----------------------------------------------------------------------===//
02697 
02698 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
02699   if (SU->isTwoAddress) {
02700     unsigned Opc = SU->getNode()->getMachineOpcode();
02701     const MCInstrDesc &MCID = TII->get(Opc);
02702     unsigned NumRes = MCID.getNumDefs();
02703     unsigned NumOps = MCID.getNumOperands() - NumRes;
02704     for (unsigned i = 0; i != NumOps; ++i) {
02705       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
02706         SDNode *DU = SU->getNode()->getOperand(i).getNode();
02707         if (DU->getNodeId() != -1 &&
02708             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
02709           return true;
02710       }
02711     }
02712   }
02713   return false;
02714 }
02715 
02716 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
02717 /// successor's explicit physregs whose definition can reach DepSU.
02718 /// i.e. DepSU should not be scheduled above SU.
02719 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
02720                                          ScheduleDAGRRList *scheduleDAG,
02721                                          const TargetInstrInfo *TII,
02722                                          const TargetRegisterInfo *TRI) {
02723   const MCPhysReg *ImpDefs
02724     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
02725   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
02726   if(!ImpDefs && !RegMask)
02727     return false;
02728 
02729   for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
02730        SI != SE; ++SI) {
02731     SUnit *SuccSU = SI->getSUnit();
02732     for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
02733            PE = SuccSU->Preds.end(); PI != PE; ++PI) {
02734       if (!PI->isAssignedRegDep())
02735         continue;
02736 
02737       if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
02738           scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02739         return true;
02740 
02741       if (ImpDefs)
02742         for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
02743           // Return true if SU clobbers this physical register use and the
02744           // definition of the register reaches from DepSU. IsReachable queries
02745           // a topological forward sort of the DAG (following the successors).
02746           if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
02747               scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02748             return true;
02749     }
02750   }
02751   return false;
02752 }
02753 
02754 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
02755 /// physical register defs.
02756 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
02757                                   const TargetInstrInfo *TII,
02758                                   const TargetRegisterInfo *TRI) {
02759   SDNode *N = SuccSU->getNode();
02760   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02761   const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
02762   assert(ImpDefs && "Caller should check hasPhysRegDefs");
02763   for (const SDNode *SUNode = SU->getNode(); SUNode;
02764        SUNode = SUNode->getGluedNode()) {
02765     if (!SUNode->isMachineOpcode())
02766       continue;
02767     const MCPhysReg *SUImpDefs =
02768       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
02769     const uint32_t *SURegMask = getNodeRegMask(SUNode);
02770     if (!SUImpDefs && !SURegMask)
02771       continue;
02772     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02773       MVT VT = N->getSimpleValueType(i);
02774       if (VT == MVT::Glue || VT == MVT::Other)
02775         continue;
02776       if (!N->hasAnyUseOfValue(i))
02777         continue;
02778       unsigned Reg = ImpDefs[i - NumDefs];
02779       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
02780         return true;
02781       if (!SUImpDefs)
02782         continue;
02783       for (;*SUImpDefs; ++SUImpDefs) {
02784         unsigned SUReg = *SUImpDefs;
02785         if (TRI->regsOverlap(Reg, SUReg))
02786           return true;
02787       }
02788     }
02789   }
02790   return false;
02791 }
02792 
02793 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
02794 /// are not handled well by the general register pressure reduction
02795 /// heuristics. When presented with code like this:
02796 ///
02797 ///      N
02798 ///    / |
02799 ///   /  |
02800 ///  U  store
02801 ///  |
02802 /// ...
02803 ///
02804 /// the heuristics tend to push the store up, but since the
02805 /// operand of the store has another use (U), this would increase
02806 /// the length of that other use (the U->N edge).
02807 ///
02808 /// This function transforms code like the above to route U's
02809 /// dependence through the store when possible, like this:
02810 ///
02811 ///      N
02812 ///      ||
02813 ///      ||
02814 ///     store
02815 ///       |
02816 ///       U
02817 ///       |
02818 ///      ...
02819 ///
02820 /// This results in the store being scheduled immediately
02821 /// after N, which shortens the U->N live range, reducing
02822 /// register pressure.
02823 ///
02824 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
02825   // Visit all the nodes in topological order, working top-down.
02826   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02827     SUnit *SU = &(*SUnits)[i];
02828     // For now, only look at nodes with no data successors, such as stores.
02829     // These are especially important, due to the heuristics in
02830     // getNodePriority for nodes with no data successors.
02831     if (SU->NumSuccs != 0)
02832       continue;
02833     // For now, only look at nodes with exactly one data predecessor.
02834     if (SU->NumPreds != 1)
02835       continue;
02836     // Avoid prescheduling copies to virtual registers, which don't behave
02837     // like other nodes from the perspective of scheduling heuristics.
02838     if (SDNode *N = SU->getNode())
02839       if (N->getOpcode() == ISD::CopyToReg &&
02840           TargetRegisterInfo::isVirtualRegister
02841             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02842         continue;
02843 
02844     // Locate the single data predecessor.
02845     SUnit *PredSU = nullptr;
02846     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
02847          EE = SU->Preds.end(); II != EE; ++II)
02848       if (!II->isCtrl()) {
02849         PredSU = II->getSUnit();
02850         break;
02851       }
02852     assert(PredSU);
02853 
02854     // Don't rewrite edges that carry physregs, because that requires additional
02855     // support infrastructure.
02856     if (PredSU->hasPhysRegDefs)
02857       continue;
02858     // Short-circuit the case where SU is PredSU's only data successor.
02859     if (PredSU->NumSuccs == 1)
02860       continue;
02861     // Avoid prescheduling to copies from virtual registers, which don't behave
02862     // like other nodes from the perspective of scheduling heuristics.
02863     if (SDNode *N = SU->getNode())
02864       if (N->getOpcode() == ISD::CopyFromReg &&
02865           TargetRegisterInfo::isVirtualRegister
02866             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02867         continue;
02868 
02869     // Perform checks on the successors of PredSU.
02870     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
02871          EE = PredSU->Succs.end(); II != EE; ++II) {
02872       SUnit *PredSuccSU = II->getSUnit();
02873       if (PredSuccSU == SU) continue;
02874       // If PredSU has another successor with no data successors, for
02875       // now don't attempt to choose either over the other.
02876       if (PredSuccSU->NumSuccs == 0)
02877         goto outer_loop_continue;
02878       // Don't break physical register dependencies.
02879       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
02880         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
02881           goto outer_loop_continue;
02882       // Don't introduce graph cycles.
02883       if (scheduleDAG->IsReachable(SU, PredSuccSU))
02884         goto outer_loop_continue;
02885     }
02886 
02887     // Ok, the transformation is safe and the heuristics suggest it is
02888     // profitable. Update the graph.
02889     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
02890                  << " next to PredSU #" << PredSU->NodeNum
02891                  << " to guide scheduling in the presence of multiple uses\n");
02892     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
02893       SDep Edge = PredSU->Succs[i];
02894       assert(!Edge.isAssignedRegDep());
02895       SUnit *SuccSU = Edge.getSUnit();
02896       if (SuccSU != SU) {
02897         Edge.setSUnit(PredSU);
02898         scheduleDAG->RemovePred(SuccSU, Edge);
02899         scheduleDAG->AddPred(SU, Edge);
02900         Edge.setSUnit(SU);
02901         scheduleDAG->AddPred(SuccSU, Edge);
02902         --i;
02903       }
02904     }
02905   outer_loop_continue:;
02906   }
02907 }
02908 
02909 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
02910 /// it as a def&use operand. Add a pseudo control edge from it to the other
02911 /// node (if it won't create a cycle) so the two-address one will be scheduled
02912 /// first (lower in the schedule). If both nodes are two-address, favor the
02913 /// one that has a CopyToReg use (more likely to be a loop induction update).
02914 /// If both are two-address, but one is commutable while the other is not
02915 /// commutable, favor the one that's not commutable.
02916 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
02917   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02918     SUnit *SU = &(*SUnits)[i];
02919     if (!SU->isTwoAddress)
02920       continue;
02921 
02922     SDNode *Node = SU->getNode();
02923     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
02924       continue;
02925 
02926     bool isLiveOut = hasOnlyLiveOutUses(SU);
02927     unsigned Opc = Node->getMachineOpcode();
02928     const MCInstrDesc &MCID = TII->get(Opc);
02929     unsigned NumRes = MCID.getNumDefs();
02930     unsigned NumOps = MCID.getNumOperands() - NumRes;
02931     for (unsigned j = 0; j != NumOps; ++j) {
02932       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
02933         continue;
02934       SDNode *DU = SU->getNode()->getOperand(j).getNode();
02935       if (DU->getNodeId() == -1)
02936         continue;
02937       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
02938       if (!DUSU) continue;
02939       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
02940            E = DUSU->Succs.end(); I != E; ++I) {
02941         if (I->isCtrl()) continue;
02942         SUnit *SuccSU = I->getSUnit();
02943         if (SuccSU == SU)
02944           continue;
02945         // Be conservative. Ignore if nodes aren't at roughly the same
02946         // depth and height.
02947         if (SuccSU->getHeight() < SU->getHeight() &&
02948             (SU->getHeight() - SuccSU->getHeight()) > 1)
02949           continue;
02950         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
02951         // constrains whatever is using the copy, instead of the copy
02952         // itself. In the case that the copy is coalesced, this
02953         // preserves the intent of the pseudo two-address heurietics.
02954         while (SuccSU->Succs.size() == 1 &&
02955                SuccSU->getNode()->isMachineOpcode() &&
02956                SuccSU->getNode()->getMachineOpcode() ==
02957                  TargetOpcode::COPY_TO_REGCLASS)
02958           SuccSU = SuccSU->Succs.front().getSUnit();
02959         // Don't constrain non-instruction nodes.
02960         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
02961           continue;
02962         // Don't constrain nodes with physical register defs if the
02963         // predecessor can clobber them.
02964         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
02965           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
02966             continue;
02967         }
02968         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
02969         // these may be coalesced away. We want them close to their uses.
02970         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
02971         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
02972             SuccOpc == TargetOpcode::INSERT_SUBREG ||
02973             SuccOpc == TargetOpcode::SUBREG_TO_REG)
02974           continue;
02975         if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
02976             (!canClobber(SuccSU, DUSU) ||
02977              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
02978              (!SU->isCommutable && SuccSU->isCommutable)) &&
02979             !scheduleDAG->IsReachable(SuccSU, SU)) {
02980           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
02981                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
02982           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Artificial));
02983         }
02984       }
02985     }
02986   }
02987 }
02988 
02989 //===----------------------------------------------------------------------===//
02990 //                         Public Constructor Functions
02991 //===----------------------------------------------------------------------===//
02992 
02993 llvm::ScheduleDAGSDNodes *
02994 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
02995                                  CodeGenOpt::Level OptLevel) {
02996   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
02997   const TargetInstrInfo *TII = STI.getInstrInfo();
02998   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
02999 
03000   BURegReductionPriorityQueue *PQ =
03001     new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
03002   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
03003   PQ->setScheduleDAG(SD);
03004   return SD;
03005 }
03006 
03007 llvm::ScheduleDAGSDNodes *
03008 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
03009                                    CodeGenOpt::Level OptLevel) {
03010   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03011   const TargetInstrInfo *TII = STI.getInstrInfo();
03012   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03013 
03014   SrcRegReductionPriorityQueue *PQ =
03015     new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
03016   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
03017   PQ->setScheduleDAG(SD);
03018   return SD;
03019 }
03020 
03021 llvm::ScheduleDAGSDNodes *
03022 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
03023                                    CodeGenOpt::Level OptLevel) {
03024   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03025   const TargetInstrInfo *TII = STI.getInstrInfo();
03026   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03027   const TargetLowering *TLI = IS->TLI;
03028 
03029   HybridBURRPriorityQueue *PQ =
03030     new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03031 
03032   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03033   PQ->setScheduleDAG(SD);
03034   return SD;
03035 }
03036 
03037 llvm::ScheduleDAGSDNodes *
03038 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
03039                                 CodeGenOpt::Level OptLevel) {
03040   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03041   const TargetInstrInfo *TII = STI.getInstrInfo();
03042   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03043   const TargetLowering *TLI = IS->TLI;
03044 
03045   ILPBURRPriorityQueue *PQ =
03046     new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03047   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03048   PQ->setScheduleDAG(SD);
03049   return SD;
03050 }