LiveIntervals.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- LiveIntervals.h - Live Interval Analysis -----------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file This file implements the LiveInterval analysis pass. Given some
  15. /// numbering of each the machine instructions (in this implemention depth-first
  16. /// order) an interval [i, j) is said to be a live interval for register v if
  17. /// there is no instruction with number j' > j such that v is live at j' and
  18. /// there is no instruction with number i' < i such that v is live at i'. In
  19. /// this implementation intervals can have holes, i.e. an interval might look
  20. /// like [1,20), [50,65), [1000,1001).
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #ifndef LLVM_CODEGEN_LIVEINTERVALS_H
  24. #define LLVM_CODEGEN_LIVEINTERVALS_H
  25. #include "llvm/ADT/ArrayRef.h"
  26. #include "llvm/ADT/IndexedMap.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/CodeGen/LiveInterval.h"
  29. #include "llvm/CodeGen/MachineBasicBlock.h"
  30. #include "llvm/CodeGen/MachineFunctionPass.h"
  31. #include "llvm/CodeGen/SlotIndexes.h"
  32. #include "llvm/CodeGen/TargetRegisterInfo.h"
  33. #include "llvm/MC/LaneBitmask.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Compiler.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include <cassert>
  38. #include <cstdint>
  39. #include <utility>
  40. namespace llvm {
  41. extern cl::opt<bool> UseSegmentSetForPhysRegs;
  42. class AAResults;
  43. class BitVector;
  44. class LiveIntervalCalc;
  45. class MachineBlockFrequencyInfo;
  46. class MachineDominatorTree;
  47. class MachineFunction;
  48. class MachineInstr;
  49. class MachineRegisterInfo;
  50. class raw_ostream;
  51. class TargetInstrInfo;
  52. class VirtRegMap;
  53. class LiveIntervals : public MachineFunctionPass {
  54. MachineFunction* MF;
  55. MachineRegisterInfo* MRI;
  56. const TargetRegisterInfo* TRI;
  57. const TargetInstrInfo* TII;
  58. AAResults *AA;
  59. SlotIndexes* Indexes;
  60. MachineDominatorTree *DomTree = nullptr;
  61. LiveIntervalCalc *LICalc = nullptr;
  62. /// Special pool allocator for VNInfo's (LiveInterval val#).
  63. VNInfo::Allocator VNInfoAllocator;
  64. /// Live interval pointers for all the virtual registers.
  65. IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals;
  66. /// Sorted list of instructions with register mask operands. Always use the
  67. /// 'r' slot, RegMasks are normal clobbers, not early clobbers.
  68. SmallVector<SlotIndex, 8> RegMaskSlots;
  69. /// This vector is parallel to RegMaskSlots, it holds a pointer to the
  70. /// corresponding register mask. This pointer can be recomputed as:
  71. ///
  72. /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]);
  73. /// unsigned OpNum = findRegMaskOperand(MI);
  74. /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask();
  75. ///
  76. /// This is kept in a separate vector partly because some standard
  77. /// libraries don't support lower_bound() with mixed objects, partly to
  78. /// improve locality when searching in RegMaskSlots.
  79. /// Also see the comment in LiveInterval::find().
  80. SmallVector<const uint32_t*, 8> RegMaskBits;
  81. /// For each basic block number, keep (begin, size) pairs indexing into the
  82. /// RegMaskSlots and RegMaskBits arrays.
  83. /// Note that basic block numbers may not be layout contiguous, that's why
  84. /// we can't just keep track of the first register mask in each basic
  85. /// block.
  86. SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
  87. /// Keeps a live range set for each register unit to track fixed physreg
  88. /// interference.
  89. SmallVector<LiveRange*, 0> RegUnitRanges;
  90. public:
  91. static char ID;
  92. LiveIntervals();
  93. ~LiveIntervals() override;
  94. /// Calculate the spill weight to assign to a single instruction.
  95. static float getSpillWeight(bool isDef, bool isUse,
  96. const MachineBlockFrequencyInfo *MBFI,
  97. const MachineInstr &MI);
  98. /// Calculate the spill weight to assign to a single instruction.
  99. static float getSpillWeight(bool isDef, bool isUse,
  100. const MachineBlockFrequencyInfo *MBFI,
  101. const MachineBasicBlock *MBB);
  102. LiveInterval &getInterval(Register Reg) {
  103. if (hasInterval(Reg))
  104. return *VirtRegIntervals[Reg.id()];
  105. return createAndComputeVirtRegInterval(Reg);
  106. }
  107. const LiveInterval &getInterval(Register Reg) const {
  108. return const_cast<LiveIntervals*>(this)->getInterval(Reg);
  109. }
  110. bool hasInterval(Register Reg) const {
  111. return VirtRegIntervals.inBounds(Reg.id()) &&
  112. VirtRegIntervals[Reg.id()];
  113. }
  114. /// Interval creation.
  115. LiveInterval &createEmptyInterval(Register Reg) {
  116. assert(!hasInterval(Reg) && "Interval already exists!");
  117. VirtRegIntervals.grow(Reg.id());
  118. VirtRegIntervals[Reg.id()] = createInterval(Reg);
  119. return *VirtRegIntervals[Reg.id()];
  120. }
  121. LiveInterval &createAndComputeVirtRegInterval(Register Reg) {
  122. LiveInterval &LI = createEmptyInterval(Reg);
  123. computeVirtRegInterval(LI);
  124. return LI;
  125. }
  126. /// Interval removal.
  127. void removeInterval(Register Reg) {
  128. delete VirtRegIntervals[Reg];
  129. VirtRegIntervals[Reg] = nullptr;
  130. }
  131. /// Given a register and an instruction, adds a live segment from that
  132. /// instruction to the end of its MBB.
  133. LiveInterval::Segment addSegmentToEndOfBlock(Register Reg,
  134. MachineInstr &startInst);
  135. /// After removing some uses of a register, shrink its live range to just
  136. /// the remaining uses. This method does not compute reaching defs for new
  137. /// uses, and it doesn't remove dead defs.
  138. /// Dead PHIDef values are marked as unused. New dead machine instructions
  139. /// are added to the dead vector. Returns true if the interval may have been
  140. /// separated into multiple connected components.
  141. bool shrinkToUses(LiveInterval *li,
  142. SmallVectorImpl<MachineInstr*> *dead = nullptr);
  143. /// Specialized version of
  144. /// shrinkToUses(LiveInterval *li, SmallVectorImpl<MachineInstr*> *dead)
  145. /// that works on a subregister live range and only looks at uses matching
  146. /// the lane mask of the subregister range.
  147. /// This may leave the subrange empty which needs to be cleaned up with
  148. /// LiveInterval::removeEmptySubranges() afterwards.
  149. void shrinkToUses(LiveInterval::SubRange &SR, Register Reg);
  150. /// Extend the live range \p LR to reach all points in \p Indices. The
  151. /// points in the \p Indices array must be jointly dominated by the union
  152. /// of the existing defs in \p LR and points in \p Undefs.
  153. ///
  154. /// PHI-defs are added as needed to maintain SSA form.
  155. ///
  156. /// If a SlotIndex in \p Indices is the end index of a basic block, \p LR
  157. /// will be extended to be live out of the basic block.
  158. /// If a SlotIndex in \p Indices is jointy dominated only by points in
  159. /// \p Undefs, the live range will not be extended to that point.
  160. ///
  161. /// See also LiveRangeCalc::extend().
  162. void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices,
  163. ArrayRef<SlotIndex> Undefs);
  164. void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices) {
  165. extendToIndices(LR, Indices, /*Undefs=*/{});
  166. }
  167. /// If \p LR has a live value at \p Kill, prune its live range by removing
  168. /// any liveness reachable from Kill. Add live range end points to
  169. /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the
  170. /// value's live range.
  171. ///
  172. /// Calling pruneValue() and extendToIndices() can be used to reconstruct
  173. /// SSA form after adding defs to a virtual register.
  174. void pruneValue(LiveRange &LR, SlotIndex Kill,
  175. SmallVectorImpl<SlotIndex> *EndPoints);
  176. /// This function should not be used. Its intent is to tell you that you are
  177. /// doing something wrong if you call pruneValue directly on a
  178. /// LiveInterval. Indeed, you are supposed to call pruneValue on the main
  179. /// LiveRange and all the LiveRanges of the subranges if any.
  180. LLVM_ATTRIBUTE_UNUSED void pruneValue(LiveInterval &, SlotIndex,
  181. SmallVectorImpl<SlotIndex> *) {
  182. llvm_unreachable(
  183. "Use pruneValue on the main LiveRange and on each subrange");
  184. }
  185. SlotIndexes *getSlotIndexes() const {
  186. return Indexes;
  187. }
  188. AAResults *getAliasAnalysis() const {
  189. return AA;
  190. }
  191. /// Returns true if the specified machine instr has been removed or was
  192. /// never entered in the map.
  193. bool isNotInMIMap(const MachineInstr &Instr) const {
  194. return !Indexes->hasIndex(Instr);
  195. }
  196. /// Returns the base index of the given instruction.
  197. SlotIndex getInstructionIndex(const MachineInstr &Instr) const {
  198. return Indexes->getInstructionIndex(Instr);
  199. }
  200. /// Returns the instruction associated with the given index.
  201. MachineInstr* getInstructionFromIndex(SlotIndex index) const {
  202. return Indexes->getInstructionFromIndex(index);
  203. }
  204. /// Return the first index in the given basic block.
  205. SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const {
  206. return Indexes->getMBBStartIdx(mbb);
  207. }
  208. /// Return the last index in the given basic block.
  209. SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const {
  210. return Indexes->getMBBEndIdx(mbb);
  211. }
  212. bool isLiveInToMBB(const LiveRange &LR,
  213. const MachineBasicBlock *mbb) const {
  214. return LR.liveAt(getMBBStartIdx(mbb));
  215. }
  216. bool isLiveOutOfMBB(const LiveRange &LR,
  217. const MachineBasicBlock *mbb) const {
  218. return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot());
  219. }
  220. MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
  221. return Indexes->getMBBFromIndex(index);
  222. }
  223. void insertMBBInMaps(MachineBasicBlock *MBB) {
  224. Indexes->insertMBBInMaps(MBB);
  225. assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
  226. "Blocks must be added in order.");
  227. RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
  228. }
  229. SlotIndex InsertMachineInstrInMaps(MachineInstr &MI) {
  230. return Indexes->insertMachineInstrInMaps(MI);
  231. }
  232. void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,
  233. MachineBasicBlock::iterator E) {
  234. for (MachineBasicBlock::iterator I = B; I != E; ++I)
  235. Indexes->insertMachineInstrInMaps(*I);
  236. }
  237. void RemoveMachineInstrFromMaps(MachineInstr &MI) {
  238. Indexes->removeMachineInstrFromMaps(MI);
  239. }
  240. SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI) {
  241. return Indexes->replaceMachineInstrInMaps(MI, NewMI);
  242. }
  243. VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
  244. void getAnalysisUsage(AnalysisUsage &AU) const override;
  245. void releaseMemory() override;
  246. /// Pass entry point; Calculates LiveIntervals.
  247. bool runOnMachineFunction(MachineFunction&) override;
  248. /// Implement the dump method.
  249. void print(raw_ostream &O, const Module* = nullptr) const override;
  250. /// If LI is confined to a single basic block, return a pointer to that
  251. /// block. If LI is live in to or out of any block, return NULL.
  252. MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
  253. /// Returns true if VNI is killed by any PHI-def values in LI.
  254. /// This may conservatively return true to avoid expensive computations.
  255. bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const;
  256. /// Add kill flags to any instruction that kills a virtual register.
  257. void addKillFlags(const VirtRegMap*);
  258. /// Call this method to notify LiveIntervals that instruction \p MI has been
  259. /// moved within a basic block. This will update the live intervals for all
  260. /// operands of \p MI. Moves between basic blocks are not supported.
  261. ///
  262. /// \param UpdateFlags Update live intervals for nonallocatable physregs.
  263. void handleMove(MachineInstr &MI, bool UpdateFlags = false);
  264. /// Update intervals of operands of all instructions in the newly
  265. /// created bundle specified by \p BundleStart.
  266. ///
  267. /// \param UpdateFlags Update live intervals for nonallocatable physregs.
  268. ///
  269. /// Assumes existing liveness is accurate.
  270. /// \pre BundleStart should be the first instruction in the Bundle.
  271. /// \pre BundleStart should not have a have SlotIndex as one will be assigned.
  272. void handleMoveIntoNewBundle(MachineInstr &BundleStart,
  273. bool UpdateFlags = false);
  274. /// Update live intervals for instructions in a range of iterators. It is
  275. /// intended for use after target hooks that may insert or remove
  276. /// instructions, and is only efficient for a small number of instructions.
  277. ///
  278. /// OrigRegs is a vector of registers that were originally used by the
  279. /// instructions in the range between the two iterators.
  280. ///
  281. /// Currently, the only only changes that are supported are simple removal
  282. /// and addition of uses.
  283. void repairIntervalsInRange(MachineBasicBlock *MBB,
  284. MachineBasicBlock::iterator Begin,
  285. MachineBasicBlock::iterator End,
  286. ArrayRef<Register> OrigRegs);
  287. // Register mask functions.
  288. //
  289. // Machine instructions may use a register mask operand to indicate that a
  290. // large number of registers are clobbered by the instruction. This is
  291. // typically used for calls.
  292. //
  293. // For compile time performance reasons, these clobbers are not recorded in
  294. // the live intervals for individual physical registers. Instead,
  295. // LiveIntervalAnalysis maintains a sorted list of instructions with
  296. // register mask operands.
  297. /// Returns a sorted array of slot indices of all instructions with
  298. /// register mask operands.
  299. ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
  300. /// Returns a sorted array of slot indices of all instructions with register
  301. /// mask operands in the basic block numbered \p MBBNum.
  302. ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
  303. std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
  304. return getRegMaskSlots().slice(P.first, P.second);
  305. }
  306. /// Returns an array of register mask pointers corresponding to
  307. /// getRegMaskSlots().
  308. ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; }
  309. /// Returns an array of mask pointers corresponding to
  310. /// getRegMaskSlotsInBlock(MBBNum).
  311. ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const {
  312. std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum];
  313. return getRegMaskBits().slice(P.first, P.second);
  314. }
  315. /// Test if \p LI is live across any register mask instructions, and
  316. /// compute a bit mask of physical registers that are not clobbered by any
  317. /// of them.
  318. ///
  319. /// Returns false if \p LI doesn't cross any register mask instructions. In
  320. /// that case, the bit vector is not filled in.
  321. bool checkRegMaskInterference(LiveInterval &LI,
  322. BitVector &UsableRegs);
  323. // Register unit functions.
  324. //
  325. // Fixed interference occurs when MachineInstrs use physregs directly
  326. // instead of virtual registers. This typically happens when passing
  327. // arguments to a function call, or when instructions require operands in
  328. // fixed registers.
  329. //
  330. // Each physreg has one or more register units, see MCRegisterInfo. We
  331. // track liveness per register unit to handle aliasing registers more
  332. // efficiently.
  333. /// Return the live range for register unit \p Unit. It will be computed if
  334. /// it doesn't exist.
  335. LiveRange &getRegUnit(unsigned Unit) {
  336. LiveRange *LR = RegUnitRanges[Unit];
  337. if (!LR) {
  338. // Compute missing ranges on demand.
  339. // Use segment set to speed-up initial computation of the live range.
  340. RegUnitRanges[Unit] = LR = new LiveRange(UseSegmentSetForPhysRegs);
  341. computeRegUnitRange(*LR, Unit);
  342. }
  343. return *LR;
  344. }
  345. /// Return the live range for register unit \p Unit if it has already been
  346. /// computed, or nullptr if it hasn't been computed yet.
  347. LiveRange *getCachedRegUnit(unsigned Unit) {
  348. return RegUnitRanges[Unit];
  349. }
  350. const LiveRange *getCachedRegUnit(unsigned Unit) const {
  351. return RegUnitRanges[Unit];
  352. }
  353. /// Remove computed live range for register unit \p Unit. Subsequent uses
  354. /// should rely on on-demand recomputation.
  355. void removeRegUnit(unsigned Unit) {
  356. delete RegUnitRanges[Unit];
  357. RegUnitRanges[Unit] = nullptr;
  358. }
  359. /// Remove associated live ranges for the register units associated with \p
  360. /// Reg. Subsequent uses should rely on on-demand recomputation. \note This
  361. /// method can result in inconsistent liveness tracking if multiple phyical
  362. /// registers share a regunit, and should be used cautiously.
  363. void removeAllRegUnitsForPhysReg(MCRegister Reg) {
  364. for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
  365. removeRegUnit(*Units);
  366. }
  367. /// Remove value numbers and related live segments starting at position
  368. /// \p Pos that are part of any liverange of physical register \p Reg or one
  369. /// of its subregisters.
  370. void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos);
  371. /// Remove value number and related live segments of \p LI and its subranges
  372. /// that start at position \p Pos.
  373. void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos);
  374. /// Split separate components in LiveInterval \p LI into separate intervals.
  375. void splitSeparateComponents(LiveInterval &LI,
  376. SmallVectorImpl<LiveInterval*> &SplitLIs);
  377. /// For live interval \p LI with correct SubRanges construct matching
  378. /// information for the main live range. Expects the main live range to not
  379. /// have any segments or value numbers.
  380. void constructMainRangeFromSubranges(LiveInterval &LI);
  381. private:
  382. /// Compute live intervals for all virtual registers.
  383. void computeVirtRegs();
  384. /// Compute RegMaskSlots and RegMaskBits.
  385. void computeRegMasks();
  386. /// Walk the values in \p LI and check for dead values:
  387. /// - Dead PHIDef values are marked as unused.
  388. /// - Dead operands are marked as such.
  389. /// - Completely dead machine instructions are added to the \p dead vector
  390. /// if it is not nullptr.
  391. /// Returns true if any PHI value numbers have been removed which may
  392. /// have separated the interval into multiple connected components.
  393. bool computeDeadValues(LiveInterval &LI,
  394. SmallVectorImpl<MachineInstr*> *dead);
  395. static LiveInterval *createInterval(Register Reg);
  396. void printInstrs(raw_ostream &O) const;
  397. void dumpInstrs() const;
  398. void computeLiveInRegUnits();
  399. void computeRegUnitRange(LiveRange&, unsigned Unit);
  400. bool computeVirtRegInterval(LiveInterval&);
  401. using ShrinkToUsesWorkList = SmallVector<std::pair<SlotIndex, VNInfo*>, 16>;
  402. void extendSegmentsToUses(LiveRange &Segments,
  403. ShrinkToUsesWorkList &WorkList, Register Reg,
  404. LaneBitmask LaneMask);
  405. /// Helper function for repairIntervalsInRange(), walks backwards and
  406. /// creates/modifies live segments in \p LR to match the operands found.
  407. /// Only full operands or operands with subregisters matching \p LaneMask
  408. /// are considered.
  409. void repairOldRegInRange(MachineBasicBlock::iterator Begin,
  410. MachineBasicBlock::iterator End,
  411. const SlotIndex endIdx, LiveRange &LR,
  412. Register Reg,
  413. LaneBitmask LaneMask = LaneBitmask::getAll());
  414. class HMEditor;
  415. };
  416. } // end namespace llvm
  417. #endif
  418. #ifdef __GNUC__
  419. #pragma GCC diagnostic pop
  420. #endif