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