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