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