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