LLVM API Documentation

RegAllocGreedy.cpp
Go to the documentation of this file.
00001 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
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 file defines the RAGreedy function pass for register allocation in
00011 // optimized builds.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "AllocationOrder.h"
00017 #include "InterferenceCache.h"
00018 #include "LiveDebugVariables.h"
00019 #include "RegAllocBase.h"
00020 #include "SpillPlacement.h"
00021 #include "Spiller.h"
00022 #include "SplitKit.h"
00023 #include "llvm/ADT/Statistic.h"
00024 #include "llvm/Analysis/AliasAnalysis.h"
00025 #include "llvm/CodeGen/CalcSpillWeights.h"
00026 #include "llvm/CodeGen/EdgeBundles.h"
00027 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00028 #include "llvm/CodeGen/LiveRangeEdit.h"
00029 #include "llvm/CodeGen/LiveRegMatrix.h"
00030 #include "llvm/CodeGen/LiveStackAnalysis.h"
00031 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00032 #include "llvm/CodeGen/MachineDominators.h"
00033 #include "llvm/CodeGen/MachineFunctionPass.h"
00034 #include "llvm/CodeGen/MachineLoopInfo.h"
00035 #include "llvm/CodeGen/MachineRegisterInfo.h"
00036 #include "llvm/CodeGen/RegAllocRegistry.h"
00037 #include "llvm/CodeGen/RegisterClassInfo.h"
00038 #include "llvm/CodeGen/VirtRegMap.h"
00039 #include "llvm/IR/LLVMContext.h"
00040 #include "llvm/PassAnalysisSupport.h"
00041 #include "llvm/Support/BranchProbability.h"
00042 #include "llvm/Support/CommandLine.h"
00043 #include "llvm/Support/Debug.h"
00044 #include "llvm/Support/ErrorHandling.h"
00045 #include "llvm/Support/Timer.h"
00046 #include "llvm/Support/raw_ostream.h"
00047 #include "llvm/Target/TargetSubtargetInfo.h"
00048 #include <queue>
00049 
00050 using namespace llvm;
00051 
00052 #define DEBUG_TYPE "regalloc"
00053 
00054 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
00055 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
00056 STATISTIC(NumEvicted,      "Number of interferences evicted");
00057 
00058 static cl::opt<SplitEditor::ComplementSpillMode>
00059 SplitSpillMode("split-spill-mode", cl::Hidden,
00060   cl::desc("Spill mode for splitting live ranges"),
00061   cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
00062              clEnumValN(SplitEditor::SM_Size,  "size",  "Optimize for size"),
00063              clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
00064              clEnumValEnd),
00065   cl::init(SplitEditor::SM_Partition));
00066 
00067 static cl::opt<unsigned>
00068 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
00069                              cl::desc("Last chance recoloring max depth"),
00070                              cl::init(5));
00071 
00072 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
00073     "lcr-max-interf", cl::Hidden,
00074     cl::desc("Last chance recoloring maximum number of considered"
00075              " interference at a time"),
00076     cl::init(8));
00077 
00078 static cl::opt<bool>
00079 ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
00080                  cl::desc("Exhaustive Search for registers bypassing the depth "
00081                           "and interference cutoffs of last chance recoloring"));
00082 
00083 static cl::opt<bool> EnableLocalReassignment(
00084     "enable-local-reassign", cl::Hidden,
00085     cl::desc("Local reassignment can yield better allocation decisions, but "
00086              "may be compile time intensive"),
00087     cl::init(false));
00088 
00089 // FIXME: Find a good default for this flag and remove the flag.
00090 static cl::opt<unsigned>
00091 CSRFirstTimeCost("regalloc-csr-first-time-cost",
00092               cl::desc("Cost for first time use of callee-saved register."),
00093               cl::init(0), cl::Hidden);
00094 
00095 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
00096                                        createGreedyRegisterAllocator);
00097 
00098 namespace {
00099 class RAGreedy : public MachineFunctionPass,
00100                  public RegAllocBase,
00101                  private LiveRangeEdit::Delegate {
00102   // Convenient shortcuts.
00103   typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
00104   typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
00105   typedef SmallSet<unsigned, 16> SmallVirtRegSet;
00106 
00107   // context
00108   MachineFunction *MF;
00109 
00110   // Shortcuts to some useful interface.
00111   const TargetInstrInfo *TII;
00112   const TargetRegisterInfo *TRI;
00113   RegisterClassInfo RCI;
00114 
00115   // analyses
00116   SlotIndexes *Indexes;
00117   MachineBlockFrequencyInfo *MBFI;
00118   MachineDominatorTree *DomTree;
00119   MachineLoopInfo *Loops;
00120   EdgeBundles *Bundles;
00121   SpillPlacement *SpillPlacer;
00122   LiveDebugVariables *DebugVars;
00123 
00124   // state
00125   std::unique_ptr<Spiller> SpillerInstance;
00126   PQueue Queue;
00127   unsigned NextCascade;
00128 
00129   // Live ranges pass through a number of stages as we try to allocate them.
00130   // Some of the stages may also create new live ranges:
00131   //
00132   // - Region splitting.
00133   // - Per-block splitting.
00134   // - Local splitting.
00135   // - Spilling.
00136   //
00137   // Ranges produced by one of the stages skip the previous stages when they are
00138   // dequeued. This improves performance because we can skip interference checks
00139   // that are unlikely to give any results. It also guarantees that the live
00140   // range splitting algorithm terminates, something that is otherwise hard to
00141   // ensure.
00142   enum LiveRangeStage {
00143     /// Newly created live range that has never been queued.
00144     RS_New,
00145 
00146     /// Only attempt assignment and eviction. Then requeue as RS_Split.
00147     RS_Assign,
00148 
00149     /// Attempt live range splitting if assignment is impossible.
00150     RS_Split,
00151 
00152     /// Attempt more aggressive live range splitting that is guaranteed to make
00153     /// progress.  This is used for split products that may not be making
00154     /// progress.
00155     RS_Split2,
00156 
00157     /// Live range will be spilled.  No more splitting will be attempted.
00158     RS_Spill,
00159 
00160     /// There is nothing more we can do to this live range.  Abort compilation
00161     /// if it can't be assigned.
00162     RS_Done
00163   };
00164 
00165   // Enum CutOffStage to keep a track whether the register allocation failed
00166   // because of the cutoffs encountered in last chance recoloring.
00167   // Note: This is used as bitmask. New value should be next power of 2.
00168   enum CutOffStage {
00169     // No cutoffs encountered
00170     CO_None = 0,
00171 
00172     // lcr-max-depth cutoff encountered
00173     CO_Depth = 1,
00174 
00175     // lcr-max-interf cutoff encountered
00176     CO_Interf = 2
00177   };
00178 
00179   uint8_t CutOffInfo;
00180 
00181 #ifndef NDEBUG
00182   static const char *const StageName[];
00183 #endif
00184 
00185   // RegInfo - Keep additional information about each live range.
00186   struct RegInfo {
00187     LiveRangeStage Stage;
00188 
00189     // Cascade - Eviction loop prevention. See canEvictInterference().
00190     unsigned Cascade;
00191 
00192     RegInfo() : Stage(RS_New), Cascade(0) {}
00193   };
00194 
00195   IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
00196 
00197   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
00198     return ExtraRegInfo[VirtReg.reg].Stage;
00199   }
00200 
00201   void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
00202     ExtraRegInfo.resize(MRI->getNumVirtRegs());
00203     ExtraRegInfo[VirtReg.reg].Stage = Stage;
00204   }
00205 
00206   template<typename Iterator>
00207   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
00208     ExtraRegInfo.resize(MRI->getNumVirtRegs());
00209     for (;Begin != End; ++Begin) {
00210       unsigned Reg = *Begin;
00211       if (ExtraRegInfo[Reg].Stage == RS_New)
00212         ExtraRegInfo[Reg].Stage = NewStage;
00213     }
00214   }
00215 
00216   /// Cost of evicting interference.
00217   struct EvictionCost {
00218     unsigned BrokenHints; ///< Total number of broken hints.
00219     float MaxWeight;      ///< Maximum spill weight evicted.
00220 
00221     EvictionCost(): BrokenHints(0), MaxWeight(0) {}
00222 
00223     bool isMax() const { return BrokenHints == ~0u; }
00224 
00225     void setMax() { BrokenHints = ~0u; }
00226 
00227     void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
00228 
00229     bool operator<(const EvictionCost &O) const {
00230       return std::tie(BrokenHints, MaxWeight) <
00231              std::tie(O.BrokenHints, O.MaxWeight);
00232     }
00233   };
00234 
00235   // splitting state.
00236   std::unique_ptr<SplitAnalysis> SA;
00237   std::unique_ptr<SplitEditor> SE;
00238 
00239   /// Cached per-block interference maps
00240   InterferenceCache IntfCache;
00241 
00242   /// All basic blocks where the current register has uses.
00243   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
00244 
00245   /// Global live range splitting candidate info.
00246   struct GlobalSplitCandidate {
00247     // Register intended for assignment, or 0.
00248     unsigned PhysReg;
00249 
00250     // SplitKit interval index for this candidate.
00251     unsigned IntvIdx;
00252 
00253     // Interference for PhysReg.
00254     InterferenceCache::Cursor Intf;
00255 
00256     // Bundles where this candidate should be live.
00257     BitVector LiveBundles;
00258     SmallVector<unsigned, 8> ActiveBlocks;
00259 
00260     void reset(InterferenceCache &Cache, unsigned Reg) {
00261       PhysReg = Reg;
00262       IntvIdx = 0;
00263       Intf.setPhysReg(Cache, Reg);
00264       LiveBundles.clear();
00265       ActiveBlocks.clear();
00266     }
00267 
00268     // Set B[i] = C for every live bundle where B[i] was NoCand.
00269     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
00270       unsigned Count = 0;
00271       for (int i = LiveBundles.find_first(); i >= 0;
00272            i = LiveBundles.find_next(i))
00273         if (B[i] == NoCand) {
00274           B[i] = C;
00275           Count++;
00276         }
00277       return Count;
00278     }
00279   };
00280 
00281   /// Candidate info for each PhysReg in AllocationOrder.
00282   /// This vector never shrinks, but grows to the size of the largest register
00283   /// class.
00284   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
00285 
00286   enum : unsigned { NoCand = ~0u };
00287 
00288   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
00289   /// NoCand which indicates the stack interval.
00290   SmallVector<unsigned, 32> BundleCand;
00291 
00292   /// Callee-save register cost, calculated once per machine function.
00293   BlockFrequency CSRCost;
00294 
00295   /// Run or not the local reassignment heuristic. This information is
00296   /// obtained from the TargetSubtargetInfo.
00297   bool EnableLocalReassign;
00298 
00299   /// Set of broken hints that may be reconciled later because of eviction.
00300   SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
00301 
00302 public:
00303   RAGreedy();
00304 
00305   /// Return the pass name.
00306   const char* getPassName() const override {
00307     return "Greedy Register Allocator";
00308   }
00309 
00310   /// RAGreedy analysis usage.
00311   void getAnalysisUsage(AnalysisUsage &AU) const override;
00312   void releaseMemory() override;
00313   Spiller &spiller() override { return *SpillerInstance; }
00314   void enqueue(LiveInterval *LI) override;
00315   LiveInterval *dequeue() override;
00316   unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
00317   void aboutToRemoveInterval(LiveInterval &) override;
00318 
00319   /// Perform register allocation.
00320   bool runOnMachineFunction(MachineFunction &mf) override;
00321 
00322   static char ID;
00323 
00324 private:
00325   unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
00326                              SmallVirtRegSet &, unsigned = 0);
00327 
00328   bool LRE_CanEraseVirtReg(unsigned) override;
00329   void LRE_WillShrinkVirtReg(unsigned) override;
00330   void LRE_DidCloneVirtReg(unsigned, unsigned) override;
00331   void enqueue(PQueue &CurQueue, LiveInterval *LI);
00332   LiveInterval *dequeue(PQueue &CurQueue);
00333 
00334   BlockFrequency calcSpillCost();
00335   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
00336   void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
00337   void growRegion(GlobalSplitCandidate &Cand);
00338   BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
00339   bool calcCompactRegion(GlobalSplitCandidate&);
00340   void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
00341   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
00342   unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
00343   bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
00344   bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
00345   void evictInterference(LiveInterval&, unsigned,
00346                          SmallVectorImpl<unsigned>&);
00347   bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
00348                                   SmallLISet &RecoloringCandidates,
00349                                   const SmallVirtRegSet &FixedRegisters);
00350 
00351   unsigned tryAssign(LiveInterval&, AllocationOrder&,
00352                      SmallVectorImpl<unsigned>&);
00353   unsigned tryEvict(LiveInterval&, AllocationOrder&,
00354                     SmallVectorImpl<unsigned>&, unsigned = ~0u);
00355   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
00356                           SmallVectorImpl<unsigned>&);
00357   /// Calculate cost of region splitting.
00358   unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
00359                                     AllocationOrder &Order,
00360                                     BlockFrequency &BestCost,
00361                                     unsigned &NumCands, bool IgnoreCSR);
00362   /// Perform region splitting.
00363   unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
00364                          bool HasCompact,
00365                          SmallVectorImpl<unsigned> &NewVRegs);
00366   /// Check other options before using a callee-saved register for the first
00367   /// time.
00368   unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
00369                                  unsigned PhysReg, unsigned &CostPerUseLimit,
00370                                  SmallVectorImpl<unsigned> &NewVRegs);
00371   void initializeCSRCost();
00372   unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
00373                          SmallVectorImpl<unsigned>&);
00374   unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
00375                                SmallVectorImpl<unsigned>&);
00376   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
00377     SmallVectorImpl<unsigned>&);
00378   unsigned trySplit(LiveInterval&, AllocationOrder&,
00379                     SmallVectorImpl<unsigned>&);
00380   unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
00381                                    SmallVectorImpl<unsigned> &,
00382                                    SmallVirtRegSet &, unsigned);
00383   bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
00384                                SmallVirtRegSet &, unsigned);
00385   void tryHintRecoloring(LiveInterval &);
00386   void tryHintsRecoloring();
00387 
00388   /// Model the information carried by one end of a copy.
00389   struct HintInfo {
00390     /// The frequency of the copy.
00391     BlockFrequency Freq;
00392     /// The virtual register or physical register.
00393     unsigned Reg;
00394     /// Its currently assigned register.
00395     /// In case of a physical register Reg == PhysReg.
00396     unsigned PhysReg;
00397     HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
00398         : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
00399   };
00400   typedef SmallVector<HintInfo, 4> HintsInfo;
00401   BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
00402   void collectHintInfo(unsigned, HintsInfo &);
00403 };
00404 } // end anonymous namespace
00405 
00406 char RAGreedy::ID = 0;
00407 
00408 #ifndef NDEBUG
00409 const char *const RAGreedy::StageName[] = {
00410     "RS_New",
00411     "RS_Assign",
00412     "RS_Split",
00413     "RS_Split2",
00414     "RS_Spill",
00415     "RS_Done"
00416 };
00417 #endif
00418 
00419 // Hysteresis to use when comparing floats.
00420 // This helps stabilize decisions based on float comparisons.
00421 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
00422 
00423 
00424 FunctionPass* llvm::createGreedyRegisterAllocator() {
00425   return new RAGreedy();
00426 }
00427 
00428 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
00429   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
00430   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
00431   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
00432   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
00433   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
00434   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
00435   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
00436   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
00437   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
00438   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
00439   initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
00440   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
00441   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
00442 }
00443 
00444 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
00445   AU.setPreservesCFG();
00446   AU.addRequired<MachineBlockFrequencyInfo>();
00447   AU.addPreserved<MachineBlockFrequencyInfo>();
00448   AU.addRequired<AliasAnalysis>();
00449   AU.addPreserved<AliasAnalysis>();
00450   AU.addRequired<LiveIntervals>();
00451   AU.addPreserved<LiveIntervals>();
00452   AU.addRequired<SlotIndexes>();
00453   AU.addPreserved<SlotIndexes>();
00454   AU.addRequired<LiveDebugVariables>();
00455   AU.addPreserved<LiveDebugVariables>();
00456   AU.addRequired<LiveStacks>();
00457   AU.addPreserved<LiveStacks>();
00458   AU.addRequired<MachineDominatorTree>();
00459   AU.addPreserved<MachineDominatorTree>();
00460   AU.addRequired<MachineLoopInfo>();
00461   AU.addPreserved<MachineLoopInfo>();
00462   AU.addRequired<VirtRegMap>();
00463   AU.addPreserved<VirtRegMap>();
00464   AU.addRequired<LiveRegMatrix>();
00465   AU.addPreserved<LiveRegMatrix>();
00466   AU.addRequired<EdgeBundles>();
00467   AU.addRequired<SpillPlacement>();
00468   MachineFunctionPass::getAnalysisUsage(AU);
00469 }
00470 
00471 
00472 //===----------------------------------------------------------------------===//
00473 //                     LiveRangeEdit delegate methods
00474 //===----------------------------------------------------------------------===//
00475 
00476 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
00477   if (VRM->hasPhys(VirtReg)) {
00478     LiveInterval &LI = LIS->getInterval(VirtReg);
00479     Matrix->unassign(LI);
00480     aboutToRemoveInterval(LI);
00481     return true;
00482   }
00483   // Unassigned virtreg is probably in the priority queue.
00484   // RegAllocBase will erase it after dequeueing.
00485   return false;
00486 }
00487 
00488 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
00489   if (!VRM->hasPhys(VirtReg))
00490     return;
00491 
00492   // Register is assigned, put it back on the queue for reassignment.
00493   LiveInterval &LI = LIS->getInterval(VirtReg);
00494   Matrix->unassign(LI);
00495   enqueue(&LI);
00496 }
00497 
00498 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
00499   // Cloning a register we haven't even heard about yet?  Just ignore it.
00500   if (!ExtraRegInfo.inBounds(Old))
00501     return;
00502 
00503   // LRE may clone a virtual register because dead code elimination causes it to
00504   // be split into connected components. The new components are much smaller
00505   // than the original, so they should get a new chance at being assigned.
00506   // same stage as the parent.
00507   ExtraRegInfo[Old].Stage = RS_Assign;
00508   ExtraRegInfo.grow(New);
00509   ExtraRegInfo[New] = ExtraRegInfo[Old];
00510 }
00511 
00512 void RAGreedy::releaseMemory() {
00513   SpillerInstance.reset();
00514   ExtraRegInfo.clear();
00515   GlobalCand.clear();
00516 }
00517 
00518 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
00519 
00520 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
00521   // Prioritize live ranges by size, assigning larger ranges first.
00522   // The queue holds (size, reg) pairs.
00523   const unsigned Size = LI->getSize();
00524   const unsigned Reg = LI->reg;
00525   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
00526          "Can only enqueue virtual registers");
00527   unsigned Prio;
00528 
00529   ExtraRegInfo.grow(Reg);
00530   if (ExtraRegInfo[Reg].Stage == RS_New)
00531     ExtraRegInfo[Reg].Stage = RS_Assign;
00532 
00533   if (ExtraRegInfo[Reg].Stage == RS_Split) {
00534     // Unsplit ranges that couldn't be allocated immediately are deferred until
00535     // everything else has been allocated.
00536     Prio = Size;
00537   } else {
00538     // Giant live ranges fall back to the global assignment heuristic, which
00539     // prevents excessive spilling in pathological cases.
00540     bool ReverseLocal = TRI->reverseLocalAssignment();
00541     bool ForceGlobal = !ReverseLocal &&
00542       (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
00543 
00544     if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
00545         LIS->intervalIsInOneMBB(*LI)) {
00546       // Allocate original local ranges in linear instruction order. Since they
00547       // are singly defined, this produces optimal coloring in the absence of
00548       // global interference and other constraints.
00549       if (!ReverseLocal)
00550         Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
00551       else {
00552         // Allocating bottom up may allow many short LRGs to be assigned first
00553         // to one of the cheap registers. This could be much faster for very
00554         // large blocks on targets with many physical registers.
00555         Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
00556       }
00557     }
00558     else {
00559       // Allocate global and split ranges in long->short order. Long ranges that
00560       // don't fit should be spilled (or split) ASAP so they don't create
00561       // interference.  Mark a bit to prioritize global above local ranges.
00562       Prio = (1u << 29) + Size;
00563     }
00564     // Mark a higher bit to prioritize global and local above RS_Split.
00565     Prio |= (1u << 31);
00566 
00567     // Boost ranges that have a physical register hint.
00568     if (VRM->hasKnownPreference(Reg))
00569       Prio |= (1u << 30);
00570   }
00571   // The virtual register number is a tie breaker for same-sized ranges.
00572   // Give lower vreg numbers higher priority to assign them first.
00573   CurQueue.push(std::make_pair(Prio, ~Reg));
00574 }
00575 
00576 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
00577 
00578 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
00579   if (CurQueue.empty())
00580     return nullptr;
00581   LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
00582   CurQueue.pop();
00583   return LI;
00584 }
00585 
00586 
00587 //===----------------------------------------------------------------------===//
00588 //                            Direct Assignment
00589 //===----------------------------------------------------------------------===//
00590 
00591 /// tryAssign - Try to assign VirtReg to an available register.
00592 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
00593                              AllocationOrder &Order,
00594                              SmallVectorImpl<unsigned> &NewVRegs) {
00595   Order.rewind();
00596   unsigned PhysReg;
00597   while ((PhysReg = Order.next()))
00598     if (!Matrix->checkInterference(VirtReg, PhysReg))
00599       break;
00600   if (!PhysReg || Order.isHint())
00601     return PhysReg;
00602 
00603   // PhysReg is available, but there may be a better choice.
00604 
00605   // If we missed a simple hint, try to cheaply evict interference from the
00606   // preferred register.
00607   if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
00608     if (Order.isHint(Hint)) {
00609       DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
00610       EvictionCost MaxCost;
00611       MaxCost.setBrokenHints(1);
00612       if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
00613         evictInterference(VirtReg, Hint, NewVRegs);
00614         return Hint;
00615       }
00616     }
00617 
00618   // Try to evict interference from a cheaper alternative.
00619   unsigned Cost = TRI->getCostPerUse(PhysReg);
00620 
00621   // Most registers have 0 additional cost.
00622   if (!Cost)
00623     return PhysReg;
00624 
00625   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
00626                << '\n');
00627   unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
00628   return CheapReg ? CheapReg : PhysReg;
00629 }
00630 
00631 
00632 //===----------------------------------------------------------------------===//
00633 //                         Interference eviction
00634 //===----------------------------------------------------------------------===//
00635 
00636 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
00637   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
00638   unsigned PhysReg;
00639   while ((PhysReg = Order.next())) {
00640     if (PhysReg == PrevReg)
00641       continue;
00642 
00643     MCRegUnitIterator Units(PhysReg, TRI);
00644     for (; Units.isValid(); ++Units) {
00645       // Instantiate a "subquery", not to be confused with the Queries array.
00646       LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
00647       if (subQ.checkInterference())
00648         break;
00649     }
00650     // If no units have interference, break out with the current PhysReg.
00651     if (!Units.isValid())
00652       break;
00653   }
00654   if (PhysReg)
00655     DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
00656           << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
00657           << '\n');
00658   return PhysReg;
00659 }
00660 
00661 /// shouldEvict - determine if A should evict the assigned live range B. The
00662 /// eviction policy defined by this function together with the allocation order
00663 /// defined by enqueue() decides which registers ultimately end up being split
00664 /// and spilled.
00665 ///
00666 /// Cascade numbers are used to prevent infinite loops if this function is a
00667 /// cyclic relation.
00668 ///
00669 /// @param A          The live range to be assigned.
00670 /// @param IsHint     True when A is about to be assigned to its preferred
00671 ///                   register.
00672 /// @param B          The live range to be evicted.
00673 /// @param BreaksHint True when B is already assigned to its preferred register.
00674 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
00675                            LiveInterval &B, bool BreaksHint) {
00676   bool CanSplit = getStage(B) < RS_Spill;
00677 
00678   // Be fairly aggressive about following hints as long as the evictee can be
00679   // split.
00680   if (CanSplit && IsHint && !BreaksHint)
00681     return true;
00682 
00683   if (A.weight > B.weight) {
00684     DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
00685     return true;
00686   }
00687   return false;
00688 }
00689 
00690 /// canEvictInterference - Return true if all interferences between VirtReg and
00691 /// PhysReg can be evicted.
00692 ///
00693 /// @param VirtReg Live range that is about to be assigned.
00694 /// @param PhysReg Desired register for assignment.
00695 /// @param IsHint  True when PhysReg is VirtReg's preferred register.
00696 /// @param MaxCost Only look for cheaper candidates and update with new cost
00697 ///                when returning true.
00698 /// @returns True when interference can be evicted cheaper than MaxCost.
00699 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
00700                                     bool IsHint, EvictionCost &MaxCost) {
00701   // It is only possible to evict virtual register interference.
00702   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
00703     return false;
00704 
00705   bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
00706 
00707   // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
00708   // involved in an eviction before. If a cascade number was assigned, deny
00709   // evicting anything with the same or a newer cascade number. This prevents
00710   // infinite eviction loops.
00711   //
00712   // This works out so a register without a cascade number is allowed to evict
00713   // anything, and it can be evicted by anything.
00714   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
00715   if (!Cascade)
00716     Cascade = NextCascade;
00717 
00718   EvictionCost Cost;
00719   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
00720     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
00721     // If there is 10 or more interferences, chances are one is heavier.
00722     if (Q.collectInterferingVRegs(10) >= 10)
00723       return false;
00724 
00725     // Check if any interfering live range is heavier than MaxWeight.
00726     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
00727       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
00728       assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
00729              "Only expecting virtual register interference from query");
00730       // Never evict spill products. They cannot split or spill.
00731       if (getStage(*Intf) == RS_Done)
00732         return false;
00733       // Once a live range becomes small enough, it is urgent that we find a
00734       // register for it. This is indicated by an infinite spill weight. These
00735       // urgent live ranges get to evict almost anything.
00736       //
00737       // Also allow urgent evictions of unspillable ranges from a strictly
00738       // larger allocation order.
00739       bool Urgent = !VirtReg.isSpillable() &&
00740         (Intf->isSpillable() ||
00741          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
00742          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
00743       // Only evict older cascades or live ranges without a cascade.
00744       unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
00745       if (Cascade <= IntfCascade) {
00746         if (!Urgent)
00747           return false;
00748         // We permit breaking cascades for urgent evictions. It should be the
00749         // last resort, though, so make it really expensive.
00750         Cost.BrokenHints += 10;
00751       }
00752       // Would this break a satisfied hint?
00753       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
00754       // Update eviction cost.
00755       Cost.BrokenHints += BreaksHint;
00756       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
00757       // Abort if this would be too expensive.
00758       if (!(Cost < MaxCost))
00759         return false;
00760       if (Urgent)
00761         continue;
00762       // Apply the eviction policy for non-urgent evictions.
00763       if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
00764         return false;
00765       // If !MaxCost.isMax(), then we're just looking for a cheap register.
00766       // Evicting another local live range in this case could lead to suboptimal
00767       // coloring.
00768       if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
00769           (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
00770         return false;
00771       }
00772     }
00773   }
00774   MaxCost = Cost;
00775   return true;
00776 }
00777 
00778 /// evictInterference - Evict any interferring registers that prevent VirtReg
00779 /// from being assigned to Physreg. This assumes that canEvictInterference
00780 /// returned true.
00781 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
00782                                  SmallVectorImpl<unsigned> &NewVRegs) {
00783   // Make sure that VirtReg has a cascade number, and assign that cascade
00784   // number to every evicted register. These live ranges than then only be
00785   // evicted by a newer cascade, preventing infinite loops.
00786   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
00787   if (!Cascade)
00788     Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
00789 
00790   DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
00791                << " interference: Cascade " << Cascade << '\n');
00792 
00793   // Collect all interfering virtregs first.
00794   SmallVector<LiveInterval*, 8> Intfs;
00795   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
00796     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
00797     assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
00798     ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
00799     Intfs.append(IVR.begin(), IVR.end());
00800   }
00801 
00802   // Evict them second. This will invalidate the queries.
00803   for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
00804     LiveInterval *Intf = Intfs[i];
00805     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
00806     if (!VRM->hasPhys(Intf->reg))
00807       continue;
00808     Matrix->unassign(*Intf);
00809     assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
00810             VirtReg.isSpillable() < Intf->isSpillable()) &&
00811            "Cannot decrease cascade number, illegal eviction");
00812     ExtraRegInfo[Intf->reg].Cascade = Cascade;
00813     ++NumEvicted;
00814     NewVRegs.push_back(Intf->reg);
00815   }
00816 }
00817 
00818 /// tryEvict - Try to evict all interferences for a physreg.
00819 /// @param  VirtReg Currently unassigned virtual register.
00820 /// @param  Order   Physregs to try.
00821 /// @return         Physreg to assign VirtReg, or 0.
00822 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
00823                             AllocationOrder &Order,
00824                             SmallVectorImpl<unsigned> &NewVRegs,
00825                             unsigned CostPerUseLimit) {
00826   NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
00827 
00828   // Keep track of the cheapest interference seen so far.
00829   EvictionCost BestCost;
00830   BestCost.setMax();
00831   unsigned BestPhys = 0;
00832   unsigned OrderLimit = Order.getOrder().size();
00833 
00834   // When we are just looking for a reduced cost per use, don't break any
00835   // hints, and only evict smaller spill weights.
00836   if (CostPerUseLimit < ~0u) {
00837     BestCost.BrokenHints = 0;
00838     BestCost.MaxWeight = VirtReg.weight;
00839 
00840     // Check of any registers in RC are below CostPerUseLimit.
00841     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
00842     unsigned MinCost = RegClassInfo.getMinCost(RC);
00843     if (MinCost >= CostPerUseLimit) {
00844       DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
00845                    << ", no cheaper registers to be found.\n");
00846       return 0;
00847     }
00848 
00849     // It is normal for register classes to have a long tail of registers with
00850     // the same cost. We don't need to look at them if they're too expensive.
00851     if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
00852       OrderLimit = RegClassInfo.getLastCostChange(RC);
00853       DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
00854     }
00855   }
00856 
00857   Order.rewind();
00858   while (unsigned PhysReg = Order.next(OrderLimit)) {
00859     if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
00860       continue;
00861     // The first use of a callee-saved register in a function has cost 1.
00862     // Don't start using a CSR when the CostPerUseLimit is low.
00863     if (CostPerUseLimit == 1)
00864      if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
00865        if (!MRI->isPhysRegUsed(CSR)) {
00866          DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
00867                       << PrintReg(CSR, TRI) << '\n');
00868          continue;
00869        }
00870 
00871     if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
00872       continue;
00873 
00874     // Best so far.
00875     BestPhys = PhysReg;
00876 
00877     // Stop if the hint can be used.
00878     if (Order.isHint())
00879       break;
00880   }
00881 
00882   if (!BestPhys)
00883     return 0;
00884 
00885   evictInterference(VirtReg, BestPhys, NewVRegs);
00886   return BestPhys;
00887 }
00888 
00889 
00890 //===----------------------------------------------------------------------===//
00891 //                              Region Splitting
00892 //===----------------------------------------------------------------------===//
00893 
00894 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
00895 /// interference pattern in Physreg and its aliases. Add the constraints to
00896 /// SpillPlacement and return the static cost of this split in Cost, assuming
00897 /// that all preferences in SplitConstraints are met.
00898 /// Return false if there are no bundles with positive bias.
00899 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
00900                                    BlockFrequency &Cost) {
00901   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
00902 
00903   // Reset interference dependent info.
00904   SplitConstraints.resize(UseBlocks.size());
00905   BlockFrequency StaticCost = 0;
00906   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
00907     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
00908     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
00909 
00910     BC.Number = BI.MBB->getNumber();
00911     Intf.moveToBlock(BC.Number);
00912     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
00913     BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
00914     BC.ChangesValue = BI.FirstDef.isValid();
00915 
00916     if (!Intf.hasInterference())
00917       continue;
00918 
00919     // Number of spill code instructions to insert.
00920     unsigned Ins = 0;
00921 
00922     // Interference for the live-in value.
00923     if (BI.LiveIn) {
00924       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
00925         BC.Entry = SpillPlacement::MustSpill, ++Ins;
00926       else if (Intf.first() < BI.FirstInstr)
00927         BC.Entry = SpillPlacement::PrefSpill, ++Ins;
00928       else if (Intf.first() < BI.LastInstr)
00929         ++Ins;
00930     }
00931 
00932     // Interference for the live-out value.
00933     if (BI.LiveOut) {
00934       if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
00935         BC.Exit = SpillPlacement::MustSpill, ++Ins;
00936       else if (Intf.last() > BI.LastInstr)
00937         BC.Exit = SpillPlacement::PrefSpill, ++Ins;
00938       else if (Intf.last() > BI.FirstInstr)
00939         ++Ins;
00940     }
00941 
00942     // Accumulate the total frequency of inserted spill code.
00943     while (Ins--)
00944       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
00945   }
00946   Cost = StaticCost;
00947 
00948   // Add constraints for use-blocks. Note that these are the only constraints
00949   // that may add a positive bias, it is downhill from here.
00950   SpillPlacer->addConstraints(SplitConstraints);
00951   return SpillPlacer->scanActiveBundles();
00952 }
00953 
00954 
00955 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
00956 /// live-through blocks in Blocks.
00957 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
00958                                      ArrayRef<unsigned> Blocks) {
00959   const unsigned GroupSize = 8;
00960   SpillPlacement::BlockConstraint BCS[GroupSize];
00961   unsigned TBS[GroupSize];
00962   unsigned B = 0, T = 0;
00963 
00964   for (unsigned i = 0; i != Blocks.size(); ++i) {
00965     unsigned Number = Blocks[i];
00966     Intf.moveToBlock(Number);
00967 
00968     if (!Intf.hasInterference()) {
00969       assert(T < GroupSize && "Array overflow");
00970       TBS[T] = Number;
00971       if (++T == GroupSize) {
00972         SpillPlacer->addLinks(makeArrayRef(TBS, T));
00973         T = 0;
00974       }
00975       continue;
00976     }
00977 
00978     assert(B < GroupSize && "Array overflow");
00979     BCS[B].Number = Number;
00980 
00981     // Interference for the live-in value.
00982     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
00983       BCS[B].Entry = SpillPlacement::MustSpill;
00984     else
00985       BCS[B].Entry = SpillPlacement::PrefSpill;
00986 
00987     // Interference for the live-out value.
00988     if (Intf.last() >= SA->getLastSplitPoint(Number))
00989       BCS[B].Exit = SpillPlacement::MustSpill;
00990     else
00991       BCS[B].Exit = SpillPlacement::PrefSpill;
00992 
00993     if (++B == GroupSize) {
00994       SpillPlacer->addConstraints(makeArrayRef(BCS, B));
00995       B = 0;
00996     }
00997   }
00998 
00999   SpillPlacer->addConstraints(makeArrayRef(BCS, B));
01000   SpillPlacer->addLinks(makeArrayRef(TBS, T));
01001 }
01002 
01003 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
01004   // Keep track of through blocks that have not been added to SpillPlacer.
01005   BitVector Todo = SA->getThroughBlocks();
01006   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
01007   unsigned AddedTo = 0;
01008 #ifndef NDEBUG
01009   unsigned Visited = 0;
01010 #endif
01011 
01012   for (;;) {
01013     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
01014     // Find new through blocks in the periphery of PrefRegBundles.
01015     for (int i = 0, e = NewBundles.size(); i != e; ++i) {
01016       unsigned Bundle = NewBundles[i];
01017       // Look at all blocks connected to Bundle in the full graph.
01018       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
01019       for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
01020            I != E; ++I) {
01021         unsigned Block = *I;
01022         if (!Todo.test(Block))
01023           continue;
01024         Todo.reset(Block);
01025         // This is a new through block. Add it to SpillPlacer later.
01026         ActiveBlocks.push_back(Block);
01027 #ifndef NDEBUG
01028         ++Visited;
01029 #endif
01030       }
01031     }
01032     // Any new blocks to add?
01033     if (ActiveBlocks.size() == AddedTo)
01034       break;
01035 
01036     // Compute through constraints from the interference, or assume that all
01037     // through blocks prefer spilling when forming compact regions.
01038     auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
01039     if (Cand.PhysReg)
01040       addThroughConstraints(Cand.Intf, NewBlocks);
01041     else
01042       // Provide a strong negative bias on through blocks to prevent unwanted
01043       // liveness on loop backedges.
01044       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
01045     AddedTo = ActiveBlocks.size();
01046 
01047     // Perhaps iterating can enable more bundles?
01048     SpillPlacer->iterate();
01049   }
01050   DEBUG(dbgs() << ", v=" << Visited);
01051 }
01052 
01053 /// calcCompactRegion - Compute the set of edge bundles that should be live
01054 /// when splitting the current live range into compact regions.  Compact
01055 /// regions can be computed without looking at interference.  They are the
01056 /// regions formed by removing all the live-through blocks from the live range.
01057 ///
01058 /// Returns false if the current live range is already compact, or if the
01059 /// compact regions would form single block regions anyway.
01060 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
01061   // Without any through blocks, the live range is already compact.
01062   if (!SA->getNumThroughBlocks())
01063     return false;
01064 
01065   // Compact regions don't correspond to any physreg.
01066   Cand.reset(IntfCache, 0);
01067 
01068   DEBUG(dbgs() << "Compact region bundles");
01069 
01070   // Use the spill placer to determine the live bundles. GrowRegion pretends
01071   // that all the through blocks have interference when PhysReg is unset.
01072   SpillPlacer->prepare(Cand.LiveBundles);
01073 
01074   // The static split cost will be zero since Cand.Intf reports no interference.
01075   BlockFrequency Cost;
01076   if (!addSplitConstraints(Cand.Intf, Cost)) {
01077     DEBUG(dbgs() << ", none.\n");
01078     return false;
01079   }
01080 
01081   growRegion(Cand);
01082   SpillPlacer->finish();
01083 
01084   if (!Cand.LiveBundles.any()) {
01085     DEBUG(dbgs() << ", none.\n");
01086     return false;
01087   }
01088 
01089   DEBUG({
01090     for (int i = Cand.LiveBundles.find_first(); i>=0;
01091          i = Cand.LiveBundles.find_next(i))
01092     dbgs() << " EB#" << i;
01093     dbgs() << ".\n";
01094   });
01095   return true;
01096 }
01097 
01098 /// calcSpillCost - Compute how expensive it would be to split the live range in
01099 /// SA around all use blocks instead of forming bundle regions.
01100 BlockFrequency RAGreedy::calcSpillCost() {
01101   BlockFrequency Cost = 0;
01102   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
01103   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
01104     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
01105     unsigned Number = BI.MBB->getNumber();
01106     // We normally only need one spill instruction - a load or a store.
01107     Cost += SpillPlacer->getBlockFrequency(Number);
01108 
01109     // Unless the value is redefined in the block.
01110     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
01111       Cost += SpillPlacer->getBlockFrequency(Number);
01112   }
01113   return Cost;
01114 }
01115 
01116 /// calcGlobalSplitCost - Return the global split cost of following the split
01117 /// pattern in LiveBundles. This cost should be added to the local cost of the
01118 /// interference pattern in SplitConstraints.
01119 ///
01120 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
01121   BlockFrequency GlobalCost = 0;
01122   const BitVector &LiveBundles = Cand.LiveBundles;
01123   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
01124   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
01125     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
01126     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
01127     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, 0)];
01128     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
01129     unsigned Ins = 0;
01130 
01131     if (BI.LiveIn)
01132       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
01133     if (BI.LiveOut)
01134       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
01135     while (Ins--)
01136       GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
01137   }
01138 
01139   for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
01140     unsigned Number = Cand.ActiveBlocks[i];
01141     bool RegIn  = LiveBundles[Bundles->getBundle(Number, 0)];
01142     bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
01143     if (!RegIn && !RegOut)
01144       continue;
01145     if (RegIn && RegOut) {
01146       // We need double spill code if this block has interference.
01147       Cand.Intf.moveToBlock(Number);
01148       if (Cand.Intf.hasInterference()) {
01149         GlobalCost += SpillPlacer->getBlockFrequency(Number);
01150         GlobalCost += SpillPlacer->getBlockFrequency(Number);
01151       }
01152       continue;
01153     }
01154     // live-in / stack-out or stack-in live-out.
01155     GlobalCost += SpillPlacer->getBlockFrequency(Number);
01156   }
01157   return GlobalCost;
01158 }
01159 
01160 /// splitAroundRegion - Split the current live range around the regions
01161 /// determined by BundleCand and GlobalCand.
01162 ///
01163 /// Before calling this function, GlobalCand and BundleCand must be initialized
01164 /// so each bundle is assigned to a valid candidate, or NoCand for the
01165 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
01166 /// objects must be initialized for the current live range, and intervals
01167 /// created for the used candidates.
01168 ///
01169 /// @param LREdit    The LiveRangeEdit object handling the current split.
01170 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
01171 ///                  must appear in this list.
01172 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
01173                                  ArrayRef<unsigned> UsedCands) {
01174   // These are the intervals created for new global ranges. We may create more
01175   // intervals for local ranges.
01176   const unsigned NumGlobalIntvs = LREdit.size();
01177   DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
01178   assert(NumGlobalIntvs && "No global intervals configured");
01179 
01180   // Isolate even single instructions when dealing with a proper sub-class.
01181   // That guarantees register class inflation for the stack interval because it
01182   // is all copies.
01183   unsigned Reg = SA->getParent().reg;
01184   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
01185 
01186   // First handle all the blocks with uses.
01187   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
01188   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
01189     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
01190     unsigned Number = BI.MBB->getNumber();
01191     unsigned IntvIn = 0, IntvOut = 0;
01192     SlotIndex IntfIn, IntfOut;
01193     if (BI.LiveIn) {
01194       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
01195       if (CandIn != NoCand) {
01196         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
01197         IntvIn = Cand.IntvIdx;
01198         Cand.Intf.moveToBlock(Number);
01199         IntfIn = Cand.Intf.first();
01200       }
01201     }
01202     if (BI.LiveOut) {
01203       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
01204       if (CandOut != NoCand) {
01205         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
01206         IntvOut = Cand.IntvIdx;
01207         Cand.Intf.moveToBlock(Number);
01208         IntfOut = Cand.Intf.last();
01209       }
01210     }
01211 
01212     // Create separate intervals for isolated blocks with multiple uses.
01213     if (!IntvIn && !IntvOut) {
01214       DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
01215       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
01216         SE->splitSingleBlock(BI);
01217       continue;
01218     }
01219 
01220     if (IntvIn && IntvOut)
01221       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
01222     else if (IntvIn)
01223       SE->splitRegInBlock(BI, IntvIn, IntfIn);
01224     else
01225       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
01226   }
01227 
01228   // Handle live-through blocks. The relevant live-through blocks are stored in
01229   // the ActiveBlocks list with each candidate. We need to filter out
01230   // duplicates.
01231   BitVector Todo = SA->getThroughBlocks();
01232   for (unsigned c = 0; c != UsedCands.size(); ++c) {
01233     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
01234     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
01235       unsigned Number = Blocks[i];
01236       if (!Todo.test(Number))
01237         continue;
01238       Todo.reset(Number);
01239 
01240       unsigned IntvIn = 0, IntvOut = 0;
01241       SlotIndex IntfIn, IntfOut;
01242 
01243       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
01244       if (CandIn != NoCand) {
01245         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
01246         IntvIn = Cand.IntvIdx;
01247         Cand.Intf.moveToBlock(Number);
01248         IntfIn = Cand.Intf.first();
01249       }
01250 
01251       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
01252       if (CandOut != NoCand) {
01253         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
01254         IntvOut = Cand.IntvIdx;
01255         Cand.Intf.moveToBlock(Number);
01256         IntfOut = Cand.Intf.last();
01257       }
01258       if (!IntvIn && !IntvOut)
01259         continue;
01260       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
01261     }
01262   }
01263 
01264   ++NumGlobalSplits;
01265 
01266   SmallVector<unsigned, 8> IntvMap;
01267   SE->finish(&IntvMap);
01268   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
01269 
01270   ExtraRegInfo.resize(MRI->getNumVirtRegs());
01271   unsigned OrigBlocks = SA->getNumLiveBlocks();
01272 
01273   // Sort out the new intervals created by splitting. We get four kinds:
01274   // - Remainder intervals should not be split again.
01275   // - Candidate intervals can be assigned to Cand.PhysReg.
01276   // - Block-local splits are candidates for local splitting.
01277   // - DCE leftovers should go back on the queue.
01278   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
01279     LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
01280 
01281     // Ignore old intervals from DCE.
01282     if (getStage(Reg) != RS_New)
01283       continue;
01284 
01285     // Remainder interval. Don't try splitting again, spill if it doesn't
01286     // allocate.
01287     if (IntvMap[i] == 0) {
01288       setStage(Reg, RS_Spill);
01289       continue;
01290     }
01291 
01292     // Global intervals. Allow repeated splitting as long as the number of live
01293     // blocks is strictly decreasing.
01294     if (IntvMap[i] < NumGlobalIntvs) {
01295       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
01296         DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
01297                      << " blocks as original.\n");
01298         // Don't allow repeated splitting as a safe guard against looping.
01299         setStage(Reg, RS_Split2);
01300       }
01301       continue;
01302     }
01303 
01304     // Other intervals are treated as new. This includes local intervals created
01305     // for blocks with multiple uses, and anything created by DCE.
01306   }
01307 
01308   if (VerifyEnabled)
01309     MF->verify(this, "After splitting live range around region");
01310 }
01311 
01312 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
01313                                   SmallVectorImpl<unsigned> &NewVRegs) {
01314   unsigned NumCands = 0;
01315   BlockFrequency BestCost;
01316 
01317   // Check if we can split this live range around a compact region.
01318   bool HasCompact = calcCompactRegion(GlobalCand.front());
01319   if (HasCompact) {
01320     // Yes, keep GlobalCand[0] as the compact region candidate.
01321     NumCands = 1;
01322     BestCost = BlockFrequency::getMaxFrequency();
01323   } else {
01324     // No benefit from the compact region, our fallback will be per-block
01325     // splitting. Make sure we find a solution that is cheaper than spilling.
01326     BestCost = calcSpillCost();
01327     DEBUG(dbgs() << "Cost of isolating all blocks = ";
01328                  MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
01329   }
01330 
01331   unsigned BestCand =
01332       calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
01333                                false/*IgnoreCSR*/);
01334 
01335   // No solutions found, fall back to single block splitting.
01336   if (!HasCompact && BestCand == NoCand)
01337     return 0;
01338 
01339   return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
01340 }
01341 
01342 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
01343                                             AllocationOrder &Order,
01344                                             BlockFrequency &BestCost,
01345                                             unsigned &NumCands,
01346                                             bool IgnoreCSR) {
01347   unsigned BestCand = NoCand;
01348   Order.rewind();
01349   while (unsigned PhysReg = Order.next()) {
01350    if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
01351      if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
01352        continue;
01353 
01354     // Discard bad candidates before we run out of interference cache cursors.
01355     // This will only affect register classes with a lot of registers (>32).
01356     if (NumCands == IntfCache.getMaxCursors()) {
01357       unsigned WorstCount = ~0u;
01358       unsigned Worst = 0;
01359       for (unsigned i = 0; i != NumCands; ++i) {
01360         if (i == BestCand || !GlobalCand[i].PhysReg)
01361           continue;
01362         unsigned Count = GlobalCand[i].LiveBundles.count();
01363         if (Count < WorstCount)
01364           Worst = i, WorstCount = Count;
01365       }
01366       --NumCands;
01367       GlobalCand[Worst] = GlobalCand[NumCands];
01368       if (BestCand == NumCands)
01369         BestCand = Worst;
01370     }
01371 
01372     if (GlobalCand.size() <= NumCands)
01373       GlobalCand.resize(NumCands+1);
01374     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
01375     Cand.reset(IntfCache, PhysReg);
01376 
01377     SpillPlacer->prepare(Cand.LiveBundles);
01378     BlockFrequency Cost;
01379     if (!addSplitConstraints(Cand.Intf, Cost)) {
01380       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
01381       continue;
01382     }
01383     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
01384                  MBFI->printBlockFreq(dbgs(), Cost));
01385     if (Cost >= BestCost) {
01386       DEBUG({
01387         if (BestCand == NoCand)
01388           dbgs() << " worse than no bundles\n";
01389         else
01390           dbgs() << " worse than "
01391                  << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
01392       });
01393       continue;
01394     }
01395     growRegion(Cand);
01396 
01397     SpillPlacer->finish();
01398 
01399     // No live bundles, defer to splitSingleBlocks().
01400     if (!Cand.LiveBundles.any()) {
01401       DEBUG(dbgs() << " no bundles.\n");
01402       continue;
01403     }
01404 
01405     Cost += calcGlobalSplitCost(Cand);
01406     DEBUG({
01407       dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
01408                                 << " with bundles";
01409       for (int i = Cand.LiveBundles.find_first(); i>=0;
01410            i = Cand.LiveBundles.find_next(i))
01411         dbgs() << " EB#" << i;
01412       dbgs() << ".\n";
01413     });
01414     if (Cost < BestCost) {
01415       BestCand = NumCands;
01416       BestCost = Cost;
01417     }
01418     ++NumCands;
01419   }
01420   return BestCand;
01421 }
01422 
01423 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
01424                                  bool HasCompact,
01425                                  SmallVectorImpl<unsigned> &NewVRegs) {
01426   SmallVector<unsigned, 8> UsedCands;
01427   // Prepare split editor.
01428   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
01429   SE->reset(LREdit, SplitSpillMode);
01430 
01431   // Assign all edge bundles to the preferred candidate, or NoCand.
01432   BundleCand.assign(Bundles->getNumBundles(), NoCand);
01433 
01434   // Assign bundles for the best candidate region.
01435   if (BestCand != NoCand) {
01436     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
01437     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
01438       UsedCands.push_back(BestCand);
01439       Cand.IntvIdx = SE->openIntv();
01440       DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
01441                    << B << " bundles, intv " << Cand.IntvIdx << ".\n");
01442       (void)B;
01443     }
01444   }
01445 
01446   // Assign bundles for the compact region.
01447   if (HasCompact) {
01448     GlobalSplitCandidate &Cand = GlobalCand.front();
01449     assert(!Cand.PhysReg && "Compact region has no physreg");
01450     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
01451       UsedCands.push_back(0);
01452       Cand.IntvIdx = SE->openIntv();
01453       DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
01454                    << Cand.IntvIdx << ".\n");
01455       (void)B;
01456     }
01457   }
01458 
01459   splitAroundRegion(LREdit, UsedCands);
01460   return 0;
01461 }
01462 
01463 
01464 //===----------------------------------------------------------------------===//
01465 //                            Per-Block Splitting
01466 //===----------------------------------------------------------------------===//
01467 
01468 /// tryBlockSplit - Split a global live range around every block with uses. This
01469 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
01470 /// they don't allocate.
01471 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
01472                                  SmallVectorImpl<unsigned> &NewVRegs) {
01473   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
01474   unsigned Reg = VirtReg.reg;
01475   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
01476   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
01477   SE->reset(LREdit, SplitSpillMode);
01478   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
01479   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
01480     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
01481     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
01482       SE->splitSingleBlock(BI);
01483   }
01484   // No blocks were split.
01485   if (LREdit.empty())
01486     return 0;
01487 
01488   // We did split for some blocks.
01489   SmallVector<unsigned, 8> IntvMap;
01490   SE->finish(&IntvMap);
01491 
01492   // Tell LiveDebugVariables about the new ranges.
01493   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
01494 
01495   ExtraRegInfo.resize(MRI->getNumVirtRegs());
01496 
01497   // Sort out the new intervals created by splitting. The remainder interval
01498   // goes straight to spilling, the new local ranges get to stay RS_New.
01499   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
01500     LiveInterval &LI = LIS->getInterval(LREdit.get(i));
01501     if (getStage(LI) == RS_New && IntvMap[i] == 0)
01502       setStage(LI, RS_Spill);
01503   }
01504 
01505   if (VerifyEnabled)
01506     MF->verify(this, "After splitting live range around basic blocks");
01507   return 0;
01508 }
01509 
01510 
01511 //===----------------------------------------------------------------------===//
01512 //                         Per-Instruction Splitting
01513 //===----------------------------------------------------------------------===//
01514 
01515 /// Get the number of allocatable registers that match the constraints of \p Reg
01516 /// on \p MI and that are also in \p SuperRC.
01517 static unsigned getNumAllocatableRegsForConstraints(
01518     const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
01519     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
01520     const RegisterClassInfo &RCI) {
01521   assert(SuperRC && "Invalid register class");
01522 
01523   const TargetRegisterClass *ConstrainedRC =
01524       MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
01525                                              /* ExploreBundle */ true);
01526   if (!ConstrainedRC)
01527     return 0;
01528   return RCI.getNumAllocatableRegs(ConstrainedRC);
01529 }
01530 
01531 /// tryInstructionSplit - Split a live range around individual instructions.
01532 /// This is normally not worthwhile since the spiller is doing essentially the
01533 /// same thing. However, when the live range is in a constrained register
01534 /// class, it may help to insert copies such that parts of the live range can
01535 /// be moved to a larger register class.
01536 ///
01537 /// This is similar to spilling to a larger register class.
01538 unsigned
01539 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
01540                               SmallVectorImpl<unsigned> &NewVRegs) {
01541   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
01542   // There is no point to this if there are no larger sub-classes.
01543   if (!RegClassInfo.isProperSubClass(CurRC))
01544     return 0;
01545 
01546   // Always enable split spill mode, since we're effectively spilling to a
01547   // register.
01548   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
01549   SE->reset(LREdit, SplitEditor::SM_Size);
01550 
01551   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
01552   if (Uses.size() <= 1)
01553     return 0;
01554 
01555   DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
01556 
01557   const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
01558   unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
01559   // Split around every non-copy instruction if this split will relax
01560   // the constraints on the virtual register.
01561   // Otherwise, splitting just inserts uncoalescable copies that do not help
01562   // the allocation.
01563   for (unsigned i = 0; i != Uses.size(); ++i) {
01564     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
01565       if (MI->isFullCopy() ||
01566           SuperRCNumAllocatableRegs ==
01567               getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
01568                                                   TRI, RCI)) {
01569         DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
01570         continue;
01571       }
01572     SE->openIntv();
01573     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
01574     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
01575     SE->useIntv(SegStart, SegStop);
01576   }
01577 
01578   if (LREdit.empty()) {
01579     DEBUG(dbgs() << "All uses were copies.\n");
01580     return 0;
01581   }
01582 
01583   SmallVector<unsigned, 8> IntvMap;
01584   SE->finish(&IntvMap);
01585   DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
01586   ExtraRegInfo.resize(MRI->getNumVirtRegs());
01587 
01588   // Assign all new registers to RS_Spill. This was the last chance.
01589   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
01590   return 0;
01591 }
01592 
01593 
01594 //===----------------------------------------------------------------------===//
01595 //                             Local Splitting
01596 //===----------------------------------------------------------------------===//
01597 
01598 
01599 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
01600 /// in order to use PhysReg between two entries in SA->UseSlots.
01601 ///
01602 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
01603 ///
01604 void RAGreedy::calcGapWeights(unsigned PhysReg,
01605                               SmallVectorImpl<float> &GapWeight) {
01606   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
01607   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
01608   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
01609   const unsigned NumGaps = Uses.size()-1;
01610 
01611   // Start and end points for the interference check.
01612   SlotIndex StartIdx =
01613     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
01614   SlotIndex StopIdx =
01615     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
01616 
01617   GapWeight.assign(NumGaps, 0.0f);
01618 
01619   // Add interference from each overlapping register.
01620   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
01621     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
01622           .checkInterference())
01623       continue;
01624 
01625     // We know that VirtReg is a continuous interval from FirstInstr to
01626     // LastInstr, so we don't need InterferenceQuery.
01627     //
01628     // Interference that overlaps an instruction is counted in both gaps
01629     // surrounding the instruction. The exception is interference before
01630     // StartIdx and after StopIdx.
01631     //
01632     LiveIntervalUnion::SegmentIter IntI =
01633       Matrix->getLiveUnions()[*Units] .find(StartIdx);
01634     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
01635       // Skip the gaps before IntI.
01636       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
01637         if (++Gap == NumGaps)
01638           break;
01639       if (Gap == NumGaps)
01640         break;
01641 
01642       // Update the gaps covered by IntI.
01643       const float weight = IntI.value()->weight;
01644       for (; Gap != NumGaps; ++Gap) {
01645         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
01646         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
01647           break;
01648       }
01649       if (Gap == NumGaps)
01650         break;
01651     }
01652   }
01653 
01654   // Add fixed interference.
01655   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
01656     const LiveRange &LR = LIS->getRegUnit(*Units);
01657     LiveRange::const_iterator I = LR.find(StartIdx);
01658     LiveRange::const_iterator E = LR.end();
01659 
01660     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
01661     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
01662       while (Uses[Gap+1].getBoundaryIndex() < I->start)
01663         if (++Gap == NumGaps)
01664           break;
01665       if (Gap == NumGaps)
01666         break;
01667 
01668       for (; Gap != NumGaps; ++Gap) {
01669         GapWeight[Gap] = llvm::huge_valf;
01670         if (Uses[Gap+1].getBaseIndex() >= I->end)
01671           break;
01672       }
01673       if (Gap == NumGaps)
01674         break;
01675     }
01676   }
01677 }
01678 
01679 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
01680 /// basic block.
01681 ///
01682 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
01683                                  SmallVectorImpl<unsigned> &NewVRegs) {
01684   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
01685   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
01686 
01687   // Note that it is possible to have an interval that is live-in or live-out
01688   // while only covering a single block - A phi-def can use undef values from
01689   // predecessors, and the block could be a single-block loop.
01690   // We don't bother doing anything clever about such a case, we simply assume
01691   // that the interval is continuous from FirstInstr to LastInstr. We should
01692   // make sure that we don't do anything illegal to such an interval, though.
01693 
01694   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
01695   if (Uses.size() <= 2)
01696     return 0;
01697   const unsigned NumGaps = Uses.size()-1;
01698 
01699   DEBUG({
01700     dbgs() << "tryLocalSplit: ";
01701     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
01702       dbgs() << ' ' << Uses[i];
01703     dbgs() << '\n';
01704   });
01705 
01706   // If VirtReg is live across any register mask operands, compute a list of
01707   // gaps with register masks.
01708   SmallVector<unsigned, 8> RegMaskGaps;
01709   if (Matrix->checkRegMaskInterference(VirtReg)) {
01710     // Get regmask slots for the whole block.
01711     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
01712     DEBUG(dbgs() << RMS.size() << " regmasks in block:");
01713     // Constrain to VirtReg's live range.
01714     unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
01715                                    Uses.front().getRegSlot()) - RMS.begin();
01716     unsigned re = RMS.size();
01717     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
01718       // Look for Uses[i] <= RMS <= Uses[i+1].
01719       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
01720       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
01721         continue;
01722       // Skip a regmask on the same instruction as the last use. It doesn't
01723       // overlap the live range.
01724       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
01725         break;
01726       DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
01727       RegMaskGaps.push_back(i);
01728       // Advance ri to the next gap. A regmask on one of the uses counts in
01729       // both gaps.
01730       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
01731         ++ri;
01732     }
01733     DEBUG(dbgs() << '\n');
01734   }
01735 
01736   // Since we allow local split results to be split again, there is a risk of
01737   // creating infinite loops. It is tempting to require that the new live
01738   // ranges have less instructions than the original. That would guarantee
01739   // convergence, but it is too strict. A live range with 3 instructions can be
01740   // split 2+3 (including the COPY), and we want to allow that.
01741   //
01742   // Instead we use these rules:
01743   //
01744   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
01745   //    noop split, of course).
01746   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
01747   //    the new ranges must have fewer instructions than before the split.
01748   // 3. New ranges with the same number of instructions are marked RS_Split2,
01749   //    smaller ranges are marked RS_New.
01750   //
01751   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
01752   // excessive splitting and infinite loops.
01753   //
01754   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
01755 
01756   // Best split candidate.
01757   unsigned BestBefore = NumGaps;
01758   unsigned BestAfter = 0;
01759   float BestDiff = 0;
01760 
01761   const float blockFreq =
01762     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
01763     (1.0f / MBFI->getEntryFreq());
01764   SmallVector<float, 8> GapWeight;
01765 
01766   Order.rewind();
01767   while (unsigned PhysReg = Order.next()) {
01768     // Keep track of the largest spill weight that would need to be evicted in
01769     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
01770     calcGapWeights(PhysReg, GapWeight);
01771 
01772     // Remove any gaps with regmask clobbers.
01773     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
01774       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
01775         GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
01776 
01777     // Try to find the best sequence of gaps to close.
01778     // The new spill weight must be larger than any gap interference.
01779 
01780     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
01781     unsigned SplitBefore = 0, SplitAfter = 1;
01782 
01783     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
01784     // It is the spill weight that needs to be evicted.
01785     float MaxGap = GapWeight[0];
01786 
01787     for (;;) {
01788       // Live before/after split?
01789       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
01790       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
01791 
01792       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
01793                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
01794                    << " i=" << MaxGap);
01795 
01796       // Stop before the interval gets so big we wouldn't be making progress.
01797       if (!LiveBefore && !LiveAfter) {
01798         DEBUG(dbgs() << " all\n");
01799         break;
01800       }
01801       // Should the interval be extended or shrunk?
01802       bool Shrink = true;
01803 
01804       // How many gaps would the new range have?
01805       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
01806 
01807       // Legally, without causing looping?
01808       bool Legal = !ProgressRequired || NewGaps < NumGaps;
01809 
01810       if (Legal && MaxGap < llvm::huge_valf) {
01811         // Estimate the new spill weight. Each instruction reads or writes the
01812         // register. Conservatively assume there are no read-modify-write
01813         // instructions.
01814         //
01815         // Try to guess the size of the new interval.
01816         const float EstWeight = normalizeSpillWeight(
01817             blockFreq * (NewGaps + 1),
01818             Uses[SplitBefore].distance(Uses[SplitAfter]) +
01819                 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
01820             1);
01821         // Would this split be possible to allocate?
01822         // Never allocate all gaps, we wouldn't be making progress.
01823         DEBUG(dbgs() << " w=" << EstWeight);
01824         if (EstWeight * Hysteresis >= MaxGap) {
01825           Shrink = false;
01826           float Diff = EstWeight - MaxGap;
01827           if (Diff > BestDiff) {
01828             DEBUG(dbgs() << " (best)");
01829             BestDiff = Hysteresis * Diff;
01830             BestBefore = SplitBefore;
01831             BestAfter = SplitAfter;
01832           }
01833         }
01834       }
01835 
01836       // Try to shrink.
01837       if (Shrink) {
01838         if (++SplitBefore < SplitAfter) {
01839           DEBUG(dbgs() << " shrink\n");
01840           // Recompute the max when necessary.
01841           if (GapWeight[SplitBefore - 1] >= MaxGap) {
01842             MaxGap = GapWeight[SplitBefore];
01843             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
01844               MaxGap = std::max(MaxGap, GapWeight[i]);
01845           }
01846           continue;
01847         }
01848         MaxGap = 0;
01849       }
01850 
01851       // Try to extend the interval.
01852       if (SplitAfter >= NumGaps) {
01853         DEBUG(dbgs() << " end\n");
01854         break;
01855       }
01856 
01857       DEBUG(dbgs() << " extend\n");
01858       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
01859     }
01860   }
01861 
01862   // Didn't find any candidates?
01863   if (BestBefore == NumGaps)
01864     return 0;
01865 
01866   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
01867                << '-' << Uses[BestAfter] << ", " << BestDiff
01868                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
01869 
01870   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
01871   SE->reset(LREdit);
01872 
01873   SE->openIntv();
01874   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
01875   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
01876   SE->useIntv(SegStart, SegStop);
01877   SmallVector<unsigned, 8> IntvMap;
01878   SE->finish(&IntvMap);
01879   DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
01880 
01881   // If the new range has the same number of instructions as before, mark it as
01882   // RS_Split2 so the next split will be forced to make progress. Otherwise,
01883   // leave the new intervals as RS_New so they can compete.
01884   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
01885   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
01886   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
01887   if (NewGaps >= NumGaps) {
01888     DEBUG(dbgs() << "Tagging non-progress ranges: ");
01889     assert(!ProgressRequired && "Didn't make progress when it was required.");
01890     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
01891       if (IntvMap[i] == 1) {
01892         setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
01893         DEBUG(dbgs() << PrintReg(LREdit.get(i)));
01894       }
01895     DEBUG(dbgs() << '\n');
01896   }
01897   ++NumLocalSplits;
01898 
01899   return 0;
01900 }
01901 
01902 //===----------------------------------------------------------------------===//
01903 //                          Live Range Splitting
01904 //===----------------------------------------------------------------------===//
01905 
01906 /// trySplit - Try to split VirtReg or one of its interferences, making it
01907 /// assignable.
01908 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
01909 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
01910                             SmallVectorImpl<unsigned>&NewVRegs) {
01911   // Ranges must be Split2 or less.
01912   if (getStage(VirtReg) >= RS_Spill)
01913     return 0;
01914 
01915   // Local intervals are handled separately.
01916   if (LIS->intervalIsInOneMBB(VirtReg)) {
01917     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
01918     SA->analyze(&VirtReg);
01919     unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
01920     if (PhysReg || !NewVRegs.empty())
01921       return PhysReg;
01922     return tryInstructionSplit(VirtReg, Order, NewVRegs);
01923   }
01924 
01925   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
01926 
01927   SA->analyze(&VirtReg);
01928 
01929   // FIXME: SplitAnalysis may repair broken live ranges coming from the
01930   // coalescer. That may cause the range to become allocatable which means that
01931   // tryRegionSplit won't be making progress. This check should be replaced with
01932   // an assertion when the coalescer is fixed.
01933   if (SA->didRepairRange()) {
01934     // VirtReg has changed, so all cached queries are invalid.
01935     Matrix->invalidateVirtRegs();
01936     if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
01937       return PhysReg;
01938   }
01939 
01940   // First try to split around a region spanning multiple blocks. RS_Split2
01941   // ranges already made dubious progress with region splitting, so they go
01942   // straight to single block splitting.
01943   if (getStage(VirtReg) < RS_Split2) {
01944     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
01945     if (PhysReg || !NewVRegs.empty())
01946       return PhysReg;
01947   }
01948 
01949   // Then isolate blocks.
01950   return tryBlockSplit(VirtReg, Order, NewVRegs);
01951 }
01952 
01953 //===----------------------------------------------------------------------===//
01954 //                          Last Chance Recoloring
01955 //===----------------------------------------------------------------------===//
01956 
01957 /// mayRecolorAllInterferences - Check if the virtual registers that
01958 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
01959 /// recolored to free \p PhysReg.
01960 /// When true is returned, \p RecoloringCandidates has been augmented with all
01961 /// the live intervals that need to be recolored in order to free \p PhysReg
01962 /// for \p VirtReg.
01963 /// \p FixedRegisters contains all the virtual registers that cannot be
01964 /// recolored.
01965 bool
01966 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
01967                                      SmallLISet &RecoloringCandidates,
01968                                      const SmallVirtRegSet &FixedRegisters) {
01969   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
01970 
01971   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
01972     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
01973     // If there is LastChanceRecoloringMaxInterference or more interferences,
01974     // chances are one would not be recolorable.
01975     if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
01976         LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
01977       DEBUG(dbgs() << "Early abort: too many interferences.\n");
01978       CutOffInfo |= CO_Interf;
01979       return false;
01980     }
01981     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
01982       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
01983       // If Intf is done and sit on the same register class as VirtReg,
01984       // it would not be recolorable as it is in the same state as VirtReg.
01985       if ((getStage(*Intf) == RS_Done &&
01986            MRI->getRegClass(Intf->reg) == CurRC) ||
01987           FixedRegisters.count(Intf->reg)) {
01988         DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
01989         return false;
01990       }
01991       RecoloringCandidates.insert(Intf);
01992     }
01993   }
01994   return true;
01995 }
01996 
01997 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
01998 /// its interferences.
01999 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
02000 /// virtual register that was using it. The recoloring process may recursively
02001 /// use the last chance recoloring. Therefore, when a virtual register has been
02002 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
02003 /// be last-chance-recolored again during this recoloring "session".
02004 /// E.g.,
02005 /// Let
02006 /// vA can use {R1, R2    }
02007 /// vB can use {    R2, R3}
02008 /// vC can use {R1        }
02009 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
02010 /// instance) and they all interfere.
02011 ///
02012 /// vA is assigned R1
02013 /// vB is assigned R2
02014 /// vC tries to evict vA but vA is already done.
02015 /// Regular register allocation fails.
02016 ///
02017 /// Last chance recoloring kicks in:
02018 /// vC does as if vA was evicted => vC uses R1.
02019 /// vC is marked as fixed.
02020 /// vA needs to find a color.
02021 /// None are available.
02022 /// vA cannot evict vC: vC is a fixed virtual register now.
02023 /// vA does as if vB was evicted => vA uses R2.
02024 /// vB needs to find a color.
02025 /// R3 is available.
02026 /// Recoloring => vC = R1, vA = R2, vB = R3
02027 ///
02028 /// \p Order defines the preferred allocation order for \p VirtReg.
02029 /// \p NewRegs will contain any new virtual register that have been created
02030 /// (split, spill) during the process and that must be assigned.
02031 /// \p FixedRegisters contains all the virtual registers that cannot be
02032 /// recolored.
02033 /// \p Depth gives the current depth of the last chance recoloring.
02034 /// \return a physical register that can be used for VirtReg or ~0u if none
02035 /// exists.
02036 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
02037                                            AllocationOrder &Order,
02038                                            SmallVectorImpl<unsigned> &NewVRegs,
02039                                            SmallVirtRegSet &FixedRegisters,
02040                                            unsigned Depth) {
02041   DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
02042   // Ranges must be Done.
02043   assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
02044          "Last chance recoloring should really be last chance");
02045   // Set the max depth to LastChanceRecoloringMaxDepth.
02046   // We may want to reconsider that if we end up with a too large search space
02047   // for target with hundreds of registers.
02048   // Indeed, in that case we may want to cut the search space earlier.
02049   if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
02050     DEBUG(dbgs() << "Abort because max depth has been reached.\n");
02051     CutOffInfo |= CO_Depth;
02052     return ~0u;
02053   }
02054 
02055   // Set of Live intervals that will need to be recolored.
02056   SmallLISet RecoloringCandidates;
02057   // Record the original mapping virtual register to physical register in case
02058   // the recoloring fails.
02059   DenseMap<unsigned, unsigned> VirtRegToPhysReg;
02060   // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
02061   // this recoloring "session".
02062   FixedRegisters.insert(VirtReg.reg);
02063 
02064   Order.rewind();
02065   while (unsigned PhysReg = Order.next()) {
02066     DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
02067                  << PrintReg(PhysReg, TRI) << '\n');
02068     RecoloringCandidates.clear();
02069     VirtRegToPhysReg.clear();
02070 
02071     // It is only possible to recolor virtual register interference.
02072     if (Matrix->checkInterference(VirtReg, PhysReg) >
02073         LiveRegMatrix::IK_VirtReg) {
02074       DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
02075 
02076       continue;
02077     }
02078 
02079     // Early give up on this PhysReg if it is obvious we cannot recolor all
02080     // the interferences.
02081     if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
02082                                     FixedRegisters)) {
02083       DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
02084       continue;
02085     }
02086 
02087     // RecoloringCandidates contains all the virtual registers that interfer
02088     // with VirtReg on PhysReg (or one of its aliases).
02089     // Enqueue them for recoloring and perform the actual recoloring.
02090     PQueue RecoloringQueue;
02091     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
02092                               EndIt = RecoloringCandidates.end();
02093          It != EndIt; ++It) {
02094       unsigned ItVirtReg = (*It)->reg;
02095       enqueue(RecoloringQueue, *It);
02096       assert(VRM->hasPhys(ItVirtReg) &&
02097              "Interferences are supposed to be with allocated vairables");
02098 
02099       // Record the current allocation.
02100       VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
02101       // unset the related struct.
02102       Matrix->unassign(**It);
02103     }
02104 
02105     // Do as if VirtReg was assigned to PhysReg so that the underlying
02106     // recoloring has the right information about the interferes and
02107     // available colors.
02108     Matrix->assign(VirtReg, PhysReg);
02109 
02110     // Save the current recoloring state.
02111     // If we cannot recolor all the interferences, we will have to start again
02112     // at this point for the next physical register.
02113     SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
02114     if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
02115                                 Depth)) {
02116       // Do not mess up with the global assignment process.
02117       // I.e., VirtReg must be unassigned.
02118       Matrix->unassign(VirtReg);
02119       return PhysReg;
02120     }
02121 
02122     DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
02123                  << PrintReg(PhysReg, TRI) << '\n');
02124 
02125     // The recoloring attempt failed, undo the changes.
02126     FixedRegisters = SaveFixedRegisters;
02127     Matrix->unassign(VirtReg);
02128 
02129     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
02130                               EndIt = RecoloringCandidates.end();
02131          It != EndIt; ++It) {
02132       unsigned ItVirtReg = (*It)->reg;
02133       if (VRM->hasPhys(ItVirtReg))
02134         Matrix->unassign(**It);
02135       Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
02136     }
02137   }
02138 
02139   // Last chance recoloring did not worked either, give up.
02140   return ~0u;
02141 }
02142 
02143 /// tryRecoloringCandidates - Try to assign a new color to every register
02144 /// in \RecoloringQueue.
02145 /// \p NewRegs will contain any new virtual register created during the
02146 /// recoloring process.
02147 /// \p FixedRegisters[in/out] contains all the registers that have been
02148 /// recolored.
02149 /// \return true if all virtual registers in RecoloringQueue were successfully
02150 /// recolored, false otherwise.
02151 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
02152                                        SmallVectorImpl<unsigned> &NewVRegs,
02153                                        SmallVirtRegSet &FixedRegisters,
02154                                        unsigned Depth) {
02155   while (!RecoloringQueue.empty()) {
02156     LiveInterval *LI = dequeue(RecoloringQueue);
02157     DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
02158     unsigned PhysReg;
02159     PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
02160     if (PhysReg == ~0u || !PhysReg)
02161       return false;
02162     DEBUG(dbgs() << "Recoloring of " << *LI
02163                  << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
02164     Matrix->assign(*LI, PhysReg);
02165     FixedRegisters.insert(LI->reg);
02166   }
02167   return true;
02168 }
02169 
02170 //===----------------------------------------------------------------------===//
02171 //                            Main Entry Point
02172 //===----------------------------------------------------------------------===//
02173 
02174 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
02175                                  SmallVectorImpl<unsigned> &NewVRegs) {
02176   CutOffInfo = CO_None;
02177   LLVMContext &Ctx = MF->getFunction()->getContext();
02178   SmallVirtRegSet FixedRegisters;
02179   unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
02180   if (Reg == ~0U && (CutOffInfo != CO_None)) {
02181     uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
02182     if (CutOffEncountered == CO_Depth)
02183       Ctx.emitError("register allocation failed: maximum depth for recoloring "
02184                     "reached. Use -fexhaustive-register-search to skip "
02185                     "cutoffs");
02186     else if (CutOffEncountered == CO_Interf)
02187       Ctx.emitError("register allocation failed: maximum interference for "
02188                     "recoloring reached. Use -fexhaustive-register-search "
02189                     "to skip cutoffs");
02190     else if (CutOffEncountered == (CO_Depth | CO_Interf))
02191       Ctx.emitError("register allocation failed: maximum interference and "
02192                     "depth for recoloring reached. Use "
02193                     "-fexhaustive-register-search to skip cutoffs");
02194   }
02195   return Reg;
02196 }
02197 
02198 /// Using a CSR for the first time has a cost because it causes push|pop
02199 /// to be added to prologue|epilogue. Splitting a cold section of the live
02200 /// range can have lower cost than using the CSR for the first time;
02201 /// Spilling a live range in the cold path can have lower cost than using
02202 /// the CSR for the first time. Returns the physical register if we decide
02203 /// to use the CSR; otherwise return 0.
02204 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
02205                                          AllocationOrder &Order,
02206                                          unsigned PhysReg,
02207                                          unsigned &CostPerUseLimit,
02208                                          SmallVectorImpl<unsigned> &NewVRegs) {
02209   if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
02210     // We choose spill over using the CSR for the first time if the spill cost
02211     // is lower than CSRCost.
02212     SA->analyze(&VirtReg);
02213     if (calcSpillCost() >= CSRCost)
02214       return PhysReg;
02215 
02216     // We are going to spill, set CostPerUseLimit to 1 to make sure that
02217     // we will not use a callee-saved register in tryEvict.
02218     CostPerUseLimit = 1;
02219     return 0;
02220   }
02221   if (getStage(VirtReg) < RS_Split) {
02222     // We choose pre-splitting over using the CSR for the first time if
02223     // the cost of splitting is lower than CSRCost.
02224     SA->analyze(&VirtReg);
02225     unsigned NumCands = 0;
02226     BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
02227     unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
02228                                                  NumCands, true /*IgnoreCSR*/);
02229     if (BestCand == NoCand)
02230       // Use the CSR if we can't find a region split below CSRCost.
02231       return PhysReg;
02232 
02233     // Perform the actual pre-splitting.
02234     doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
02235     return 0;
02236   }
02237   return PhysReg;
02238 }
02239 
02240 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
02241   // Do not keep invalid information around.
02242   SetOfBrokenHints.remove(&LI);
02243 }
02244 
02245 void RAGreedy::initializeCSRCost() {
02246   // We use the larger one out of the command-line option and the value report
02247   // by TRI.
02248   CSRCost = BlockFrequency(
02249       std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
02250   if (!CSRCost.getFrequency())
02251     return;
02252 
02253   // Raw cost is relative to Entry == 2^14; scale it appropriately.
02254   uint64_t ActualEntry = MBFI->getEntryFreq();
02255   if (!ActualEntry) {
02256     CSRCost = 0;
02257     return;
02258   }
02259   uint64_t FixedEntry = 1 << 14;
02260   if (ActualEntry < FixedEntry)
02261     CSRCost *= BranchProbability(ActualEntry, FixedEntry);
02262   else if (ActualEntry <= UINT32_MAX)
02263     // Invert the fraction and divide.
02264     CSRCost /= BranchProbability(FixedEntry, ActualEntry);
02265   else
02266     // Can't use BranchProbability in general, since it takes 32-bit numbers.
02267     CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
02268 }
02269 
02270 /// \brief Collect the hint info for \p Reg.
02271 /// The results are stored into \p Out.
02272 /// \p Out is not cleared before being populated.
02273 void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
02274   for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
02275     if (!Instr.isFullCopy())
02276       continue;
02277     // Look for the other end of the copy.
02278     unsigned OtherReg = Instr.getOperand(0).getReg();
02279     if (OtherReg == Reg) {
02280       OtherReg = Instr.getOperand(1).getReg();
02281       if (OtherReg == Reg)
02282         continue;
02283     }
02284     // Get the current assignment.
02285     unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
02286                                 ? OtherReg
02287                                 : VRM->getPhys(OtherReg);
02288     // Push the collected information.
02289     Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
02290                            OtherPhysReg));
02291   }
02292 }
02293 
02294 /// \brief Using the given \p List, compute the cost of the broken hints if
02295 /// \p PhysReg was used.
02296 /// \return The cost of \p List for \p PhysReg.
02297 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
02298                                            unsigned PhysReg) {
02299   BlockFrequency Cost = 0;
02300   for (const HintInfo &Info : List) {
02301     if (Info.PhysReg != PhysReg)
02302       Cost += Info.Freq;
02303   }
02304   return Cost;
02305 }
02306 
02307 /// \brief Using the register assigned to \p VirtReg, try to recolor
02308 /// all the live ranges that are copy-related with \p VirtReg.
02309 /// The recoloring is then propagated to all the live-ranges that have
02310 /// been recolored and so on, until no more copies can be coalesced or
02311 /// it is not profitable.
02312 /// For a given live range, profitability is determined by the sum of the
02313 /// frequencies of the non-identity copies it would introduce with the old
02314 /// and new register.
02315 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
02316   // We have a broken hint, check if it is possible to fix it by
02317   // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
02318   // some register and PhysReg may be available for the other live-ranges.
02319   SmallSet<unsigned, 4> Visited;
02320   SmallVector<unsigned, 2> RecoloringCandidates;
02321   HintsInfo Info;
02322   unsigned Reg = VirtReg.reg;
02323   unsigned PhysReg = VRM->getPhys(Reg);
02324   // Start the recoloring algorithm from the input live-interval, then
02325   // it will propagate to the ones that are copy-related with it.
02326   Visited.insert(Reg);
02327   RecoloringCandidates.push_back(Reg);
02328 
02329   DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
02330                << PrintReg(PhysReg, TRI) << ")\n");
02331 
02332   do {
02333     Reg = RecoloringCandidates.pop_back_val();
02334 
02335     // We cannot recolor physcal register.
02336     if (TargetRegisterInfo::isPhysicalRegister(Reg))
02337       continue;
02338 
02339     assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
02340 
02341     // Get the live interval mapped with this virtual register to be able
02342     // to check for the interference with the new color.
02343     LiveInterval &LI = LIS->getInterval(Reg);
02344     unsigned CurrPhys = VRM->getPhys(Reg);
02345     // Check that the new color matches the register class constraints and
02346     // that it is free for this live range.
02347     if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
02348                                 Matrix->checkInterference(LI, PhysReg)))
02349       continue;
02350 
02351     DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
02352                  << ") is recolorable.\n");
02353 
02354     // Gather the hint info.
02355     Info.clear();
02356     collectHintInfo(Reg, Info);
02357     // Check if recoloring the live-range will increase the cost of the
02358     // non-identity copies.
02359     if (CurrPhys != PhysReg) {
02360       DEBUG(dbgs() << "Checking profitability:\n");
02361       BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
02362       BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
02363       DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
02364                    << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
02365       if (OldCopiesCost < NewCopiesCost) {
02366         DEBUG(dbgs() << "=> Not profitable.\n");
02367         continue;
02368       }
02369       // At this point, the cost is either cheaper or equal. If it is
02370       // equal, we consider this is profitable because it may expose
02371       // more recoloring opportunities.
02372       DEBUG(dbgs() << "=> Profitable.\n");
02373       // Recolor the live-range.
02374       Matrix->unassign(LI);
02375       Matrix->assign(LI, PhysReg);
02376     }
02377     // Push all copy-related live-ranges to keep reconciling the broken
02378     // hints.
02379     for (const HintInfo &HI : Info) {
02380       if (Visited.insert(HI.Reg).second)
02381         RecoloringCandidates.push_back(HI.Reg);
02382     }
02383   } while (!RecoloringCandidates.empty());
02384 }
02385 
02386 /// \brief Try to recolor broken hints.
02387 /// Broken hints may be repaired by recoloring when an evicted variable
02388 /// freed up a register for a larger live-range.
02389 /// Consider the following example:
02390 /// BB1:
02391 ///   a =
02392 ///   b =
02393 /// BB2:
02394 ///   ...
02395 ///   = b
02396 ///   = a
02397 /// Let us assume b gets split:
02398 /// BB1:
02399 ///   a =
02400 ///   b =
02401 /// BB2:
02402 ///   c = b
02403 ///   ...
02404 ///   d = c
02405 ///   = d
02406 ///   = a
02407 /// Because of how the allocation work, b, c, and d may be assigned different
02408 /// colors. Now, if a gets evicted later:
02409 /// BB1:
02410 ///   a =
02411 ///   st a, SpillSlot
02412 ///   b =
02413 /// BB2:
02414 ///   c = b
02415 ///   ...
02416 ///   d = c
02417 ///   = d
02418 ///   e = ld SpillSlot
02419 ///   = e
02420 /// This is likely that we can assign the same register for b, c, and d,
02421 /// getting rid of 2 copies.
02422 void RAGreedy::tryHintsRecoloring() {
02423   for (LiveInterval *LI : SetOfBrokenHints) {
02424     assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
02425            "Recoloring is possible only for virtual registers");
02426     // Some dead defs may be around (e.g., because of debug uses).
02427     // Ignore those.
02428     if (!VRM->hasPhys(LI->reg))
02429       continue;
02430     tryHintRecoloring(*LI);
02431   }
02432 }
02433 
02434 unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
02435                                      SmallVectorImpl<unsigned> &NewVRegs,
02436                                      SmallVirtRegSet &FixedRegisters,
02437                                      unsigned Depth) {
02438   unsigned CostPerUseLimit = ~0u;
02439   // First try assigning a free register.
02440   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
02441   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
02442     // We check other options if we are using a CSR for the first time.
02443     bool CSRFirstUse = false;
02444     if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
02445       if (!MRI->isPhysRegUsed(CSR))
02446         CSRFirstUse = true;
02447 
02448     // When NewVRegs is not empty, we may have made decisions such as evicting
02449     // a virtual register, go with the earlier decisions and use the physical
02450     // register.
02451     if (CSRCost.getFrequency() && CSRFirstUse && NewVRegs.empty()) {
02452       unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
02453                                               CostPerUseLimit, NewVRegs);
02454       if (CSRReg || !NewVRegs.empty())
02455         // Return now if we decide to use a CSR or create new vregs due to
02456         // pre-splitting.
02457         return CSRReg;
02458     } else
02459       return PhysReg;
02460   }
02461 
02462   LiveRangeStage Stage = getStage(VirtReg);
02463   DEBUG(dbgs() << StageName[Stage]
02464                << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
02465 
02466   // Try to evict a less worthy live range, but only for ranges from the primary
02467   // queue. The RS_Split ranges already failed to do this, and they should not
02468   // get a second chance until they have been split.
02469   if (Stage != RS_Split)
02470     if (unsigned PhysReg =
02471             tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
02472       unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
02473       // If VirtReg has a hint and that hint is broken record this
02474       // virtual register as a recoloring candidate for broken hint.
02475       // Indeed, since we evicted a variable in its neighborhood it is
02476       // likely we can at least partially recolor some of the
02477       // copy-related live-ranges.
02478       if (Hint && Hint != PhysReg)
02479         SetOfBrokenHints.insert(&VirtReg);
02480       return PhysReg;
02481     }
02482 
02483   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
02484 
02485   // The first time we see a live range, don't try to split or spill.
02486   // Wait until the second time, when all smaller ranges have been allocated.
02487   // This gives a better picture of the interference to split around.
02488   if (Stage < RS_Split) {
02489     setStage(VirtReg, RS_Split);
02490     DEBUG(dbgs() << "wait for second round\n");
02491     NewVRegs.push_back(VirtReg.reg);
02492     return 0;
02493   }
02494 
02495   // If we couldn't allocate a register from spilling, there is probably some
02496   // invalid inline assembly. The base class wil report it.
02497   if (Stage >= RS_Done || !VirtReg.isSpillable())
02498     return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
02499                                    Depth);
02500 
02501   // Try splitting VirtReg or interferences.
02502   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
02503   if (PhysReg || !NewVRegs.empty())
02504     return PhysReg;
02505 
02506   // Finally spill VirtReg itself.
02507   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
02508   LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
02509   spiller().spill(LRE);
02510   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
02511 
02512   if (VerifyEnabled)
02513     MF->verify(this, "After spilling");
02514 
02515   // The live virtual register requesting allocation was spilled, so tell
02516   // the caller not to allocate anything during this round.
02517   return 0;
02518 }
02519 
02520 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
02521   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
02522                << "********** Function: " << mf.getName() << '\n');
02523 
02524   MF = &mf;
02525   TRI = MF->getSubtarget().getRegisterInfo();
02526   TII = MF->getSubtarget().getInstrInfo();
02527   RCI.runOnMachineFunction(mf);
02528 
02529   EnableLocalReassign = EnableLocalReassignment ||
02530                         MF->getSubtarget().enableRALocalReassignment(
02531                             MF->getTarget().getOptLevel());
02532 
02533   if (VerifyEnabled)
02534     MF->verify(this, "Before greedy register allocator");
02535 
02536   RegAllocBase::init(getAnalysis<VirtRegMap>(),
02537                      getAnalysis<LiveIntervals>(),
02538                      getAnalysis<LiveRegMatrix>());
02539   Indexes = &getAnalysis<SlotIndexes>();
02540   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
02541   DomTree = &getAnalysis<MachineDominatorTree>();
02542   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
02543   Loops = &getAnalysis<MachineLoopInfo>();
02544   Bundles = &getAnalysis<EdgeBundles>();
02545   SpillPlacer = &getAnalysis<SpillPlacement>();
02546   DebugVars = &getAnalysis<LiveDebugVariables>();
02547 
02548   initializeCSRCost();
02549 
02550   calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
02551 
02552   DEBUG(LIS->dump());
02553 
02554   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
02555   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
02556   ExtraRegInfo.clear();
02557   ExtraRegInfo.resize(MRI->getNumVirtRegs());
02558   NextCascade = 1;
02559   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
02560   GlobalCand.resize(32);  // This will grow as needed.
02561   SetOfBrokenHints.clear();
02562 
02563   allocatePhysRegs();
02564   tryHintsRecoloring();
02565   releaseMemory();
02566   return true;
02567 }