SplitKit.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. //===-------- SplitKit.h - Toolkit for splitting live ranges ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the SplitAnalysis class as well as mutator functions for
  11. // live range splitting.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_LIB_CODEGEN_SPLITKIT_H
  15. #define LLVM_LIB_CODEGEN_SPLITKIT_H
  16. #include "LiveRangeCalc.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/IntervalMap.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. namespace llvm {
  22. class ConnectedVNInfoEqClasses;
  23. class LiveInterval;
  24. class LiveIntervals;
  25. class LiveRangeEdit;
  26. class MachineBlockFrequencyInfo;
  27. class MachineInstr;
  28. class MachineLoopInfo;
  29. class MachineRegisterInfo;
  30. class TargetInstrInfo;
  31. class TargetRegisterInfo;
  32. class VirtRegMap;
  33. class VNInfo;
  34. class raw_ostream;
  35. /// SplitAnalysis - Analyze a LiveInterval, looking for live range splitting
  36. /// opportunities.
  37. class LLVM_LIBRARY_VISIBILITY SplitAnalysis {
  38. public:
  39. const MachineFunction &MF;
  40. const VirtRegMap &VRM;
  41. const LiveIntervals &LIS;
  42. const MachineLoopInfo &Loops;
  43. const TargetInstrInfo &TII;
  44. /// Additional information about basic blocks where the current variable is
  45. /// live. Such a block will look like one of these templates:
  46. ///
  47. /// 1. | o---x | Internal to block. Variable is only live in this block.
  48. /// 2. |---x | Live-in, kill.
  49. /// 3. | o---| Def, live-out.
  50. /// 4. |---x o---| Live-in, kill, def, live-out. Counted by NumGapBlocks.
  51. /// 5. |---o---o---| Live-through with uses or defs.
  52. /// 6. |-----------| Live-through without uses. Counted by NumThroughBlocks.
  53. ///
  54. /// Two BlockInfo entries are created for template 4. One for the live-in
  55. /// segment, and one for the live-out segment. These entries look as if the
  56. /// block were split in the middle where the live range isn't live.
  57. ///
  58. /// Live-through blocks without any uses don't get BlockInfo entries. They
  59. /// are simply listed in ThroughBlocks instead.
  60. ///
  61. struct BlockInfo {
  62. MachineBasicBlock *MBB;
  63. SlotIndex FirstInstr; ///< First instr accessing current reg.
  64. SlotIndex LastInstr; ///< Last instr accessing current reg.
  65. SlotIndex FirstDef; ///< First non-phi valno->def, or SlotIndex().
  66. bool LiveIn; ///< Current reg is live in.
  67. bool LiveOut; ///< Current reg is live out.
  68. /// isOneInstr - Returns true when this BlockInfo describes a single
  69. /// instruction.
  70. bool isOneInstr() const {
  71. return SlotIndex::isSameInstr(FirstInstr, LastInstr);
  72. }
  73. };
  74. private:
  75. // Current live interval.
  76. const LiveInterval *CurLI;
  77. // Sorted slot indexes of using instructions.
  78. SmallVector<SlotIndex, 8> UseSlots;
  79. /// LastSplitPoint - Last legal split point in each basic block in the current
  80. /// function. The first entry is the first terminator, the second entry is the
  81. /// last valid split point for a variable that is live in to a landing pad
  82. /// successor.
  83. SmallVector<std::pair<SlotIndex, SlotIndex>, 8> LastSplitPoint;
  84. /// UseBlocks - Blocks where CurLI has uses.
  85. SmallVector<BlockInfo, 8> UseBlocks;
  86. /// NumGapBlocks - Number of duplicate entries in UseBlocks for blocks where
  87. /// the live range has a gap.
  88. unsigned NumGapBlocks;
  89. /// ThroughBlocks - Block numbers where CurLI is live through without uses.
  90. BitVector ThroughBlocks;
  91. /// NumThroughBlocks - Number of live-through blocks.
  92. unsigned NumThroughBlocks;
  93. /// DidRepairRange - analyze was forced to shrinkToUses().
  94. bool DidRepairRange;
  95. SlotIndex computeLastSplitPoint(unsigned Num);
  96. // Sumarize statistics by counting instructions using CurLI.
  97. void analyzeUses();
  98. /// calcLiveBlockInfo - Compute per-block information about CurLI.
  99. bool calcLiveBlockInfo();
  100. public:
  101. SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
  102. const MachineLoopInfo &mli);
  103. /// analyze - set CurLI to the specified interval, and analyze how it may be
  104. /// split.
  105. void analyze(const LiveInterval *li);
  106. /// didRepairRange() - Returns true if CurLI was invalid and has been repaired
  107. /// by analyze(). This really shouldn't happen, but sometimes the coalescer
  108. /// can create live ranges that end in mid-air.
  109. bool didRepairRange() const { return DidRepairRange; }
  110. /// clear - clear all data structures so SplitAnalysis is ready to analyze a
  111. /// new interval.
  112. void clear();
  113. /// getParent - Return the last analyzed interval.
  114. const LiveInterval &getParent() const { return *CurLI; }
  115. /// getLastSplitPoint - Return the base index of the last valid split point
  116. /// in the basic block numbered Num.
  117. SlotIndex getLastSplitPoint(unsigned Num) {
  118. // Inline the common simple case.
  119. if (LastSplitPoint[Num].first.isValid() &&
  120. !LastSplitPoint[Num].second.isValid())
  121. return LastSplitPoint[Num].first;
  122. return computeLastSplitPoint(Num);
  123. }
  124. /// getLastSplitPointIter - Returns the last split point as an iterator.
  125. MachineBasicBlock::iterator getLastSplitPointIter(MachineBasicBlock*);
  126. /// isOriginalEndpoint - Return true if the original live range was killed or
  127. /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/def,
  128. /// and 'use' for an early-clobber def.
  129. /// This can be used to recognize code inserted by earlier live range
  130. /// splitting.
  131. bool isOriginalEndpoint(SlotIndex Idx) const;
  132. /// getUseSlots - Return an array of SlotIndexes of instructions using CurLI.
  133. /// This include both use and def operands, at most one entry per instruction.
  134. ArrayRef<SlotIndex> getUseSlots() const { return UseSlots; }
  135. /// getUseBlocks - Return an array of BlockInfo objects for the basic blocks
  136. /// where CurLI has uses.
  137. ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
  138. /// getNumThroughBlocks - Return the number of through blocks.
  139. unsigned getNumThroughBlocks() const { return NumThroughBlocks; }
  140. /// isThroughBlock - Return true if CurLI is live through MBB without uses.
  141. bool isThroughBlock(unsigned MBB) const { return ThroughBlocks.test(MBB); }
  142. /// getThroughBlocks - Return the set of through blocks.
  143. const BitVector &getThroughBlocks() const { return ThroughBlocks; }
  144. /// getNumLiveBlocks - Return the number of blocks where CurLI is live.
  145. unsigned getNumLiveBlocks() const {
  146. return getUseBlocks().size() - NumGapBlocks + getNumThroughBlocks();
  147. }
  148. /// countLiveBlocks - Return the number of blocks where li is live. This is
  149. /// guaranteed to return the same number as getNumLiveBlocks() after calling
  150. /// analyze(li).
  151. unsigned countLiveBlocks(const LiveInterval *li) const;
  152. typedef SmallPtrSet<const MachineBasicBlock*, 16> BlockPtrSet;
  153. /// shouldSplitSingleBlock - Returns true if it would help to create a local
  154. /// live range for the instructions in BI. There is normally no benefit to
  155. /// creating a live range for a single instruction, but it does enable
  156. /// register class inflation if the instruction has a restricted register
  157. /// class.
  158. ///
  159. /// @param BI The block to be isolated.
  160. /// @param SingleInstrs True when single instructions should be isolated.
  161. bool shouldSplitSingleBlock(const BlockInfo &BI, bool SingleInstrs) const;
  162. };
  163. /// SplitEditor - Edit machine code and LiveIntervals for live range
  164. /// splitting.
  165. ///
  166. /// - Create a SplitEditor from a SplitAnalysis.
  167. /// - Start a new live interval with openIntv.
  168. /// - Mark the places where the new interval is entered using enterIntv*
  169. /// - Mark the ranges where the new interval is used with useIntv*
  170. /// - Mark the places where the interval is exited with exitIntv*.
  171. /// - Finish the current interval with closeIntv and repeat from 2.
  172. /// - Rewrite instructions with finish().
  173. ///
  174. class LLVM_LIBRARY_VISIBILITY SplitEditor {
  175. SplitAnalysis &SA;
  176. LiveIntervals &LIS;
  177. VirtRegMap &VRM;
  178. MachineRegisterInfo &MRI;
  179. MachineDominatorTree &MDT;
  180. const TargetInstrInfo &TII;
  181. const TargetRegisterInfo &TRI;
  182. const MachineBlockFrequencyInfo &MBFI;
  183. public:
  184. /// ComplementSpillMode - Select how the complement live range should be
  185. /// created. SplitEditor automatically creates interval 0 to contain
  186. /// anything that isn't added to another interval. This complement interval
  187. /// can get quite complicated, and it can sometimes be an advantage to allow
  188. /// it to overlap the other intervals. If it is going to spill anyway, no
  189. /// registers are wasted by keeping a value in two places at the same time.
  190. enum ComplementSpillMode {
  191. /// SM_Partition(Default) - Try to create the complement interval so it
  192. /// doesn't overlap any other intervals, and the original interval is
  193. /// partitioned. This may require a large number of back copies and extra
  194. /// PHI-defs. Only segments marked with overlapIntv will be overlapping.
  195. SM_Partition,
  196. /// SM_Size - Overlap intervals to minimize the number of inserted COPY
  197. /// instructions. Copies to the complement interval are hoisted to their
  198. /// common dominator, so only one COPY is required per value in the
  199. /// complement interval. This also means that no extra PHI-defs need to be
  200. /// inserted in the complement interval.
  201. SM_Size,
  202. /// SM_Speed - Overlap intervals to minimize the expected execution
  203. /// frequency of the inserted copies. This is very similar to SM_Size, but
  204. /// the complement interval may get some extra PHI-defs.
  205. SM_Speed
  206. };
  207. private:
  208. /// Edit - The current parent register and new intervals created.
  209. LiveRangeEdit *Edit;
  210. /// Index into Edit of the currently open interval.
  211. /// The index 0 is used for the complement, so the first interval started by
  212. /// openIntv will be 1.
  213. unsigned OpenIdx;
  214. /// The current spill mode, selected by reset().
  215. ComplementSpillMode SpillMode;
  216. typedef IntervalMap<SlotIndex, unsigned> RegAssignMap;
  217. /// Allocator for the interval map. This will eventually be shared with
  218. /// SlotIndexes and LiveIntervals.
  219. RegAssignMap::Allocator Allocator;
  220. /// RegAssign - Map of the assigned register indexes.
  221. /// Edit.get(RegAssign.lookup(Idx)) is the register that should be live at
  222. /// Idx.
  223. RegAssignMap RegAssign;
  224. typedef PointerIntPair<VNInfo*, 1> ValueForcePair;
  225. typedef DenseMap<std::pair<unsigned, unsigned>, ValueForcePair> ValueMap;
  226. /// Values - keep track of the mapping from parent values to values in the new
  227. /// intervals. Given a pair (RegIdx, ParentVNI->id), Values contains:
  228. ///
  229. /// 1. No entry - the value is not mapped to Edit.get(RegIdx).
  230. /// 2. (Null, false) - the value is mapped to multiple values in
  231. /// Edit.get(RegIdx). Each value is represented by a minimal live range at
  232. /// its def. The full live range can be inferred exactly from the range
  233. /// of RegIdx in RegAssign.
  234. /// 3. (Null, true). As above, but the ranges in RegAssign are too large, and
  235. /// the live range must be recomputed using LiveRangeCalc::extend().
  236. /// 4. (VNI, false) The value is mapped to a single new value.
  237. /// The new value has no live ranges anywhere.
  238. ValueMap Values;
  239. /// LRCalc - Cache for computing live ranges and SSA update. Each instance
  240. /// can only handle non-overlapping live ranges, so use a separate
  241. /// LiveRangeCalc instance for the complement interval when in spill mode.
  242. LiveRangeCalc LRCalc[2];
  243. /// getLRCalc - Return the LRCalc to use for RegIdx. In spill mode, the
  244. /// complement interval can overlap the other intervals, so it gets its own
  245. /// LRCalc instance. When not in spill mode, all intervals can share one.
  246. LiveRangeCalc &getLRCalc(unsigned RegIdx) {
  247. return LRCalc[SpillMode != SM_Partition && RegIdx != 0];
  248. }
  249. /// defValue - define a value in RegIdx from ParentVNI at Idx.
  250. /// Idx does not have to be ParentVNI->def, but it must be contained within
  251. /// ParentVNI's live range in ParentLI. The new value is added to the value
  252. /// map.
  253. /// Return the new LI value.
  254. VNInfo *defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx);
  255. /// forceRecompute - Force the live range of ParentVNI in RegIdx to be
  256. /// recomputed by LiveRangeCalc::extend regardless of the number of defs.
  257. /// This is used for values whose live range doesn't match RegAssign exactly.
  258. /// They could have rematerialized, or back-copies may have been moved.
  259. void forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI);
  260. /// defFromParent - Define Reg from ParentVNI at UseIdx using either
  261. /// rematerialization or a COPY from parent. Return the new value.
  262. VNInfo *defFromParent(unsigned RegIdx,
  263. VNInfo *ParentVNI,
  264. SlotIndex UseIdx,
  265. MachineBasicBlock &MBB,
  266. MachineBasicBlock::iterator I);
  267. /// removeBackCopies - Remove the copy instructions that defines the values
  268. /// in the vector in the complement interval.
  269. void removeBackCopies(SmallVectorImpl<VNInfo*> &Copies);
  270. /// getShallowDominator - Returns the least busy dominator of MBB that is
  271. /// also dominated by DefMBB. Busy is measured by loop depth.
  272. MachineBasicBlock *findShallowDominator(MachineBasicBlock *MBB,
  273. MachineBasicBlock *DefMBB);
  274. /// hoistCopiesForSize - Hoist back-copies to the complement interval in a
  275. /// way that minimizes code size. This implements the SM_Size spill mode.
  276. void hoistCopiesForSize();
  277. /// transferValues - Transfer values to the new ranges.
  278. /// Return true if any ranges were skipped.
  279. bool transferValues();
  280. /// extendPHIKillRanges - Extend the ranges of all values killed by original
  281. /// parent PHIDefs.
  282. void extendPHIKillRanges();
  283. /// rewriteAssigned - Rewrite all uses of Edit.getReg() to assigned registers.
  284. void rewriteAssigned(bool ExtendRanges);
  285. /// deleteRematVictims - Delete defs that are dead after rematerializing.
  286. void deleteRematVictims();
  287. public:
  288. /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
  289. /// Newly created intervals will be appended to newIntervals.
  290. SplitEditor(SplitAnalysis &SA, LiveIntervals&, VirtRegMap&,
  291. MachineDominatorTree&, MachineBlockFrequencyInfo &);
  292. /// reset - Prepare for a new split.
  293. void reset(LiveRangeEdit&, ComplementSpillMode = SM_Partition);
  294. /// Create a new virtual register and live interval.
  295. /// Return the interval index, starting from 1. Interval index 0 is the
  296. /// implicit complement interval.
  297. unsigned openIntv();
  298. /// currentIntv - Return the current interval index.
  299. unsigned currentIntv() const { return OpenIdx; }
  300. /// selectIntv - Select a previously opened interval index.
  301. void selectIntv(unsigned Idx);
  302. /// enterIntvBefore - Enter the open interval before the instruction at Idx.
  303. /// If the parent interval is not live before Idx, a COPY is not inserted.
  304. /// Return the beginning of the new live range.
  305. SlotIndex enterIntvBefore(SlotIndex Idx);
  306. /// enterIntvAfter - Enter the open interval after the instruction at Idx.
  307. /// Return the beginning of the new live range.
  308. SlotIndex enterIntvAfter(SlotIndex Idx);
  309. /// enterIntvAtEnd - Enter the open interval at the end of MBB.
  310. /// Use the open interval from the inserted copy to the MBB end.
  311. /// Return the beginning of the new live range.
  312. SlotIndex enterIntvAtEnd(MachineBasicBlock &MBB);
  313. /// useIntv - indicate that all instructions in MBB should use OpenLI.
  314. void useIntv(const MachineBasicBlock &MBB);
  315. /// useIntv - indicate that all instructions in range should use OpenLI.
  316. void useIntv(SlotIndex Start, SlotIndex End);
  317. /// leaveIntvAfter - Leave the open interval after the instruction at Idx.
  318. /// Return the end of the live range.
  319. SlotIndex leaveIntvAfter(SlotIndex Idx);
  320. /// leaveIntvBefore - Leave the open interval before the instruction at Idx.
  321. /// Return the end of the live range.
  322. SlotIndex leaveIntvBefore(SlotIndex Idx);
  323. /// leaveIntvAtTop - Leave the interval at the top of MBB.
  324. /// Add liveness from the MBB top to the copy.
  325. /// Return the end of the live range.
  326. SlotIndex leaveIntvAtTop(MachineBasicBlock &MBB);
  327. /// overlapIntv - Indicate that all instructions in range should use the open
  328. /// interval, but also let the complement interval be live.
  329. ///
  330. /// This doubles the register pressure, but is sometimes required to deal with
  331. /// register uses after the last valid split point.
  332. ///
  333. /// The Start index should be a return value from a leaveIntv* call, and End
  334. /// should be in the same basic block. The parent interval must have the same
  335. /// value across the range.
  336. ///
  337. void overlapIntv(SlotIndex Start, SlotIndex End);
  338. /// finish - after all the new live ranges have been created, compute the
  339. /// remaining live range, and rewrite instructions to use the new registers.
  340. /// @param LRMap When not null, this vector will map each live range in Edit
  341. /// back to the indices returned by openIntv.
  342. /// There may be extra indices created by dead code elimination.
  343. void finish(SmallVectorImpl<unsigned> *LRMap = nullptr);
  344. /// dump - print the current interval mapping to dbgs().
  345. void dump() const;
  346. // ===--- High level methods ---===
  347. /// splitSingleBlock - Split CurLI into a separate live interval around the
  348. /// uses in a single block. This is intended to be used as part of a larger
  349. /// split, and doesn't call finish().
  350. void splitSingleBlock(const SplitAnalysis::BlockInfo &BI);
  351. /// splitLiveThroughBlock - Split CurLI in the given block such that it
  352. /// enters the block in IntvIn and leaves it in IntvOut. There may be uses in
  353. /// the block, but they will be ignored when placing split points.
  354. ///
  355. /// @param MBBNum Block number.
  356. /// @param IntvIn Interval index entering the block.
  357. /// @param LeaveBefore When set, leave IntvIn before this point.
  358. /// @param IntvOut Interval index leaving the block.
  359. /// @param EnterAfter When set, enter IntvOut after this point.
  360. void splitLiveThroughBlock(unsigned MBBNum,
  361. unsigned IntvIn, SlotIndex LeaveBefore,
  362. unsigned IntvOut, SlotIndex EnterAfter);
  363. /// splitRegInBlock - Split CurLI in the given block such that it enters the
  364. /// block in IntvIn and leaves it on the stack (or not at all). Split points
  365. /// are placed in a way that avoids putting uses in the stack interval. This
  366. /// may require creating a local interval when there is interference.
  367. ///
  368. /// @param BI Block descriptor.
  369. /// @param IntvIn Interval index entering the block. Not 0.
  370. /// @param LeaveBefore When set, leave IntvIn before this point.
  371. void splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
  372. unsigned IntvIn, SlotIndex LeaveBefore);
  373. /// splitRegOutBlock - Split CurLI in the given block such that it enters the
  374. /// block on the stack (or isn't live-in at all) and leaves it in IntvOut.
  375. /// Split points are placed to avoid interference and such that the uses are
  376. /// not in the stack interval. This may require creating a local interval
  377. /// when there is interference.
  378. ///
  379. /// @param BI Block descriptor.
  380. /// @param IntvOut Interval index leaving the block.
  381. /// @param EnterAfter When set, enter IntvOut after this point.
  382. void splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
  383. unsigned IntvOut, SlotIndex EnterAfter);
  384. };
  385. }
  386. #endif