RegAllocEvictionAdvisor.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. //===- RegAllocEvictionAdvisor.h - Interference resolution ------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLVM_CODEGEN_REGALLOCEVICTIONADVISOR_H
  9. #define LLVM_CODEGEN_REGALLOCEVICTIONADVISOR_H
  10. #include "AllocationOrder.h"
  11. #include "llvm/ADT/IndexedMap.h"
  12. #include "llvm/ADT/SmallSet.h"
  13. #include "llvm/CodeGen/LiveInterval.h"
  14. #include "llvm/CodeGen/LiveIntervals.h"
  15. #include "llvm/CodeGen/LiveRegMatrix.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/Register.h"
  18. #include "llvm/CodeGen/TargetRegisterInfo.h"
  19. #include "llvm/Config/llvm-config.h"
  20. #include "llvm/Pass.h"
  21. namespace llvm {
  22. using SmallVirtRegSet = SmallSet<Register, 16>;
  23. // Live ranges pass through a number of stages as we try to allocate them.
  24. // Some of the stages may also create new live ranges:
  25. //
  26. // - Region splitting.
  27. // - Per-block splitting.
  28. // - Local splitting.
  29. // - Spilling.
  30. //
  31. // Ranges produced by one of the stages skip the previous stages when they are
  32. // dequeued. This improves performance because we can skip interference checks
  33. // that are unlikely to give any results. It also guarantees that the live
  34. // range splitting algorithm terminates, something that is otherwise hard to
  35. // ensure.
  36. enum LiveRangeStage {
  37. /// Newly created live range that has never been queued.
  38. RS_New,
  39. /// Only attempt assignment and eviction. Then requeue as RS_Split.
  40. RS_Assign,
  41. /// Attempt live range splitting if assignment is impossible.
  42. RS_Split,
  43. /// Attempt more aggressive live range splitting that is guaranteed to make
  44. /// progress. This is used for split products that may not be making
  45. /// progress.
  46. RS_Split2,
  47. /// Live range will be spilled. No more splitting will be attempted.
  48. RS_Spill,
  49. /// Live range is in memory. Because of other evictions, it might get moved
  50. /// in a register in the end.
  51. RS_Memory,
  52. /// There is nothing more we can do to this live range. Abort compilation
  53. /// if it can't be assigned.
  54. RS_Done
  55. };
  56. /// Cost of evicting interference - used by default advisor, and the eviction
  57. /// chain heuristic in RegAllocGreedy.
  58. // FIXME: this can be probably made an implementation detail of the default
  59. // advisor, if the eviction chain logic can be refactored.
  60. struct EvictionCost {
  61. unsigned BrokenHints = 0; ///< Total number of broken hints.
  62. float MaxWeight = 0; ///< Maximum spill weight evicted.
  63. EvictionCost() = default;
  64. bool isMax() const { return BrokenHints == ~0u; }
  65. void setMax() { BrokenHints = ~0u; }
  66. void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
  67. bool operator<(const EvictionCost &O) const {
  68. return std::tie(BrokenHints, MaxWeight) <
  69. std::tie(O.BrokenHints, O.MaxWeight);
  70. }
  71. };
  72. /// Interface to the eviction advisor, which is responsible for making a
  73. /// decision as to which live ranges should be evicted (if any).
  74. class RAGreedy;
  75. class RegAllocEvictionAdvisor {
  76. public:
  77. RegAllocEvictionAdvisor(const RegAllocEvictionAdvisor &) = delete;
  78. RegAllocEvictionAdvisor(RegAllocEvictionAdvisor &&) = delete;
  79. virtual ~RegAllocEvictionAdvisor() = default;
  80. /// Find a physical register that can be freed by evicting the FixedRegisters,
  81. /// or return NoRegister. The eviction decision is assumed to be correct (i.e.
  82. /// no fixed live ranges are evicted) and profitable.
  83. virtual MCRegister
  84. tryFindEvictionCandidate(LiveInterval &VirtReg, const AllocationOrder &Order,
  85. uint8_t CostPerUseLimit,
  86. const SmallVirtRegSet &FixedRegisters) const = 0;
  87. /// Find out if we can evict the live ranges occupying the given PhysReg,
  88. /// which is a hint (preferred register) for VirtReg.
  89. virtual bool
  90. canEvictHintInterference(LiveInterval &VirtReg, MCRegister PhysReg,
  91. const SmallVirtRegSet &FixedRegisters) const = 0;
  92. /// Returns true if the given \p PhysReg is a callee saved register and has
  93. /// not been used for allocation yet.
  94. bool isUnusedCalleeSavedReg(MCRegister PhysReg) const;
  95. protected:
  96. RegAllocEvictionAdvisor(MachineFunction &MF, const RAGreedy &RA);
  97. Register canReassign(LiveInterval &VirtReg, Register PrevReg) const;
  98. // Get the upper limit of elements in the given Order we need to analize.
  99. // TODO: is this heuristic, we could consider learning it.
  100. Optional<unsigned> getOrderLimit(const LiveInterval &VirtReg,
  101. const AllocationOrder &Order,
  102. unsigned CostPerUseLimit) const;
  103. // Determine if it's worth trying to allocate this reg, given the
  104. // CostPerUseLimit
  105. // TODO: this is a heuristic component we could consider learning, too.
  106. bool canAllocatePhysReg(unsigned CostPerUseLimit, MCRegister PhysReg) const;
  107. const MachineFunction &MF;
  108. const RAGreedy &RA;
  109. LiveRegMatrix *const Matrix;
  110. LiveIntervals *const LIS;
  111. VirtRegMap *const VRM;
  112. MachineRegisterInfo *const MRI;
  113. const TargetRegisterInfo *const TRI;
  114. const RegisterClassInfo &RegClassInfo;
  115. const ArrayRef<uint8_t> RegCosts;
  116. /// Run or not the local reassignment heuristic. This information is
  117. /// obtained from the TargetSubtargetInfo.
  118. const bool EnableLocalReassign;
  119. private:
  120. unsigned NextCascade = 1;
  121. };
  122. /// ImmutableAnalysis abstraction for fetching the Eviction Advisor. We model it
  123. /// as an analysis to decouple the user from the implementation insofar as
  124. /// dependencies on other analyses goes. The motivation for it being an
  125. /// immutable pass is twofold:
  126. /// - in the ML implementation case, the evaluator is stateless but (especially
  127. /// in the development mode) expensive to set up. With an immutable pass, we set
  128. /// it up once.
  129. /// - in the 'development' mode ML case, we want to capture the training log
  130. /// during allocation (this is a log of features encountered and decisions
  131. /// made), and then measure a score, potentially a few steps after allocation
  132. /// completes. So we need the properties of an immutable pass to keep the logger
  133. /// state around until we can make that measurement.
  134. ///
  135. /// Because we need to offer additional services in 'development' mode, the
  136. /// implementations of this analysis need to implement RTTI support.
  137. class RegAllocEvictionAdvisorAnalysis : public ImmutablePass {
  138. public:
  139. enum class AdvisorMode : int { Default, Release, Development };
  140. RegAllocEvictionAdvisorAnalysis(AdvisorMode Mode)
  141. : ImmutablePass(ID), Mode(Mode){};
  142. static char ID;
  143. /// Get an advisor for the given context (i.e. machine function, etc)
  144. virtual std::unique_ptr<RegAllocEvictionAdvisor>
  145. getAdvisor(MachineFunction &MF, const RAGreedy &RA) = 0;
  146. AdvisorMode getAdvisorMode() const { return Mode; }
  147. protected:
  148. // This analysis preserves everything, and subclasses may have additional
  149. // requirements.
  150. void getAnalysisUsage(AnalysisUsage &AU) const override {
  151. AU.setPreservesAll();
  152. }
  153. private:
  154. StringRef getPassName() const override;
  155. const AdvisorMode Mode;
  156. };
  157. /// Specialization for the API used by the analysis infrastructure to create
  158. /// an instance of the eviction advisor.
  159. template <> Pass *callDefaultCtor<RegAllocEvictionAdvisorAnalysis>();
  160. RegAllocEvictionAdvisorAnalysis *createReleaseModeAdvisor();
  161. RegAllocEvictionAdvisorAnalysis *createDevelopmentModeAdvisor();
  162. // TODO: move to RegAllocEvictionAdvisor.cpp when we move implementation
  163. // out of RegAllocGreedy.cpp
  164. class DefaultEvictionAdvisor : public RegAllocEvictionAdvisor {
  165. public:
  166. DefaultEvictionAdvisor(MachineFunction &MF, const RAGreedy &RA)
  167. : RegAllocEvictionAdvisor(MF, RA) {}
  168. private:
  169. MCRegister tryFindEvictionCandidate(LiveInterval &, const AllocationOrder &,
  170. uint8_t,
  171. const SmallVirtRegSet &) const override;
  172. bool canEvictHintInterference(LiveInterval &, MCRegister,
  173. const SmallVirtRegSet &) const override;
  174. bool canEvictInterferenceBasedOnCost(LiveInterval &, MCRegister, bool,
  175. EvictionCost &,
  176. const SmallVirtRegSet &) const;
  177. bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool) const;
  178. };
  179. } // namespace llvm
  180. #endif // LLVM_CODEGEN_REGALLOCEVICTIONADVISOR_H