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