1 //===- LiveIntervals.h - Live Interval Analysis -----------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file This file implements the LiveInterval analysis pass. Given some 10 /// numbering of each the machine instructions (in this implemention depth-first 11 /// order) an interval [i, j) is said to be a live interval for register v if 12 /// there is no instruction with number j' > j such that v is live at j' and 13 /// there is no instruction with number i' < i such that v is live at i'. In 14 /// this implementation intervals can have holes, i.e. an interval might look 15 /// like [1,20), [50,65), [1000,1001). 16 // 17 //===----------------------------------------------------------------------===// 18 19 #ifndef LLVM_CODEGEN_LIVEINTERVALS_H 20 #define LLVM_CODEGEN_LIVEINTERVALS_H 21 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/IndexedMap.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/CodeGen/LiveInterval.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineFunctionPass.h" 28 #include "llvm/CodeGen/SlotIndexes.h" 29 #include "llvm/CodeGen/TargetRegisterInfo.h" 30 #include "llvm/MC/LaneBitmask.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Compiler.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include <cassert> 35 #include <cstdint> 36 #include <utility> 37 38 namespace llvm { 39 40 extern cl::opt<bool> UseSegmentSetForPhysRegs; 41 42 class BitVector; 43 class LiveIntervalCalc; 44 class MachineBlockFrequencyInfo; 45 class MachineDominatorTree; 46 class MachineFunction; 47 class MachineInstr; 48 class MachineRegisterInfo; 49 class raw_ostream; 50 class TargetInstrInfo; 51 class VirtRegMap; 52 53 class LiveIntervals : public MachineFunctionPass { 54 MachineFunction* MF; 55 MachineRegisterInfo* MRI; 56 const TargetRegisterInfo* TRI; 57 const TargetInstrInfo *TII; 58 SlotIndexes* Indexes; 59 MachineDominatorTree *DomTree = nullptr; 60 LiveIntervalCalc *LICalc = nullptr; 61 62 /// Special pool allocator for VNInfo's (LiveInterval val#). 63 VNInfo::Allocator VNInfoAllocator; 64 65 /// Live interval pointers for all the virtual registers. 66 IndexedMap<LiveInterval*, VirtReg2IndexFunctor> VirtRegIntervals; 67 68 /// Sorted list of instructions with register mask operands. Always use the 69 /// 'r' slot, RegMasks are normal clobbers, not early clobbers. 70 SmallVector<SlotIndex, 8> RegMaskSlots; 71 72 /// This vector is parallel to RegMaskSlots, it holds a pointer to the 73 /// corresponding register mask. This pointer can be recomputed as: 74 /// 75 /// MI = Indexes->getInstructionFromIndex(RegMaskSlot[N]); 76 /// unsigned OpNum = findRegMaskOperand(MI); 77 /// RegMaskBits[N] = MI->getOperand(OpNum).getRegMask(); 78 /// 79 /// This is kept in a separate vector partly because some standard 80 /// libraries don't support lower_bound() with mixed objects, partly to 81 /// improve locality when searching in RegMaskSlots. 82 /// Also see the comment in LiveInterval::find(). 83 SmallVector<const uint32_t*, 8> RegMaskBits; 84 85 /// For each basic block number, keep (begin, size) pairs indexing into the 86 /// RegMaskSlots and RegMaskBits arrays. 87 /// Note that basic block numbers may not be layout contiguous, that's why 88 /// we can't just keep track of the first register mask in each basic 89 /// block. 90 SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks; 91 92 /// Keeps a live range set for each register unit to track fixed physreg 93 /// interference. 94 SmallVector<LiveRange*, 0> RegUnitRanges; 95 96 public: 97 static char ID; 98 99 LiveIntervals(); 100 ~LiveIntervals() override; 101 102 /// Calculate the spill weight to assign to a single instruction. 103 static float getSpillWeight(bool isDef, bool isUse, 104 const MachineBlockFrequencyInfo *MBFI, 105 const MachineInstr &MI); 106 107 /// Calculate the spill weight to assign to a single instruction. 108 static float getSpillWeight(bool isDef, bool isUse, 109 const MachineBlockFrequencyInfo *MBFI, 110 const MachineBasicBlock *MBB); 111 getInterval(Register Reg)112 LiveInterval &getInterval(Register Reg) { 113 if (hasInterval(Reg)) 114 return *VirtRegIntervals[Reg.id()]; 115 116 return createAndComputeVirtRegInterval(Reg); 117 } 118 getInterval(Register Reg)119 const LiveInterval &getInterval(Register Reg) const { 120 return const_cast<LiveIntervals*>(this)->getInterval(Reg); 121 } 122 hasInterval(Register Reg)123 bool hasInterval(Register Reg) const { 124 return VirtRegIntervals.inBounds(Reg.id()) && 125 VirtRegIntervals[Reg.id()]; 126 } 127 128 /// Interval creation. createEmptyInterval(Register Reg)129 LiveInterval &createEmptyInterval(Register Reg) { 130 assert(!hasInterval(Reg) && "Interval already exists!"); 131 VirtRegIntervals.grow(Reg.id()); 132 VirtRegIntervals[Reg.id()] = createInterval(Reg); 133 return *VirtRegIntervals[Reg.id()]; 134 } 135 createAndComputeVirtRegInterval(Register Reg)136 LiveInterval &createAndComputeVirtRegInterval(Register Reg) { 137 LiveInterval &LI = createEmptyInterval(Reg); 138 computeVirtRegInterval(LI); 139 return LI; 140 } 141 142 /// Interval removal. removeInterval(Register Reg)143 void removeInterval(Register Reg) { 144 delete VirtRegIntervals[Reg]; 145 VirtRegIntervals[Reg] = nullptr; 146 } 147 148 /// Given a register and an instruction, adds a live segment from that 149 /// instruction to the end of its MBB. 150 LiveInterval::Segment addSegmentToEndOfBlock(Register Reg, 151 MachineInstr &startInst); 152 153 /// After removing some uses of a register, shrink its live range to just 154 /// the remaining uses. This method does not compute reaching defs for new 155 /// uses, and it doesn't remove dead defs. 156 /// Dead PHIDef values are marked as unused. New dead machine instructions 157 /// are added to the dead vector. Returns true if the interval may have been 158 /// separated into multiple connected components. 159 bool shrinkToUses(LiveInterval *li, 160 SmallVectorImpl<MachineInstr*> *dead = nullptr); 161 162 /// Specialized version of 163 /// shrinkToUses(LiveInterval *li, SmallVectorImpl<MachineInstr*> *dead) 164 /// that works on a subregister live range and only looks at uses matching 165 /// the lane mask of the subregister range. 166 /// This may leave the subrange empty which needs to be cleaned up with 167 /// LiveInterval::removeEmptySubranges() afterwards. 168 void shrinkToUses(LiveInterval::SubRange &SR, Register Reg); 169 170 /// Extend the live range \p LR to reach all points in \p Indices. The 171 /// points in the \p Indices array must be jointly dominated by the union 172 /// of the existing defs in \p LR and points in \p Undefs. 173 /// 174 /// PHI-defs are added as needed to maintain SSA form. 175 /// 176 /// If a SlotIndex in \p Indices is the end index of a basic block, \p LR 177 /// will be extended to be live out of the basic block. 178 /// If a SlotIndex in \p Indices is jointy dominated only by points in 179 /// \p Undefs, the live range will not be extended to that point. 180 /// 181 /// See also LiveRangeCalc::extend(). 182 void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices, 183 ArrayRef<SlotIndex> Undefs); 184 extendToIndices(LiveRange & LR,ArrayRef<SlotIndex> Indices)185 void extendToIndices(LiveRange &LR, ArrayRef<SlotIndex> Indices) { 186 extendToIndices(LR, Indices, /*Undefs=*/{}); 187 } 188 189 /// If \p LR has a live value at \p Kill, prune its live range by removing 190 /// any liveness reachable from Kill. Add live range end points to 191 /// EndPoints such that extendToIndices(LI, EndPoints) will reconstruct the 192 /// value's live range. 193 /// 194 /// Calling pruneValue() and extendToIndices() can be used to reconstruct 195 /// SSA form after adding defs to a virtual register. 196 void pruneValue(LiveRange &LR, SlotIndex Kill, 197 SmallVectorImpl<SlotIndex> *EndPoints); 198 199 /// This function should not be used. Its intent is to tell you that you are 200 /// doing something wrong if you call pruneValue directly on a 201 /// LiveInterval. Indeed, you are supposed to call pruneValue on the main 202 /// LiveRange and all the LiveRanges of the subranges if any. pruneValue(LiveInterval &,SlotIndex,SmallVectorImpl<SlotIndex> *)203 LLVM_ATTRIBUTE_UNUSED void pruneValue(LiveInterval &, SlotIndex, 204 SmallVectorImpl<SlotIndex> *) { 205 llvm_unreachable( 206 "Use pruneValue on the main LiveRange and on each subrange"); 207 } 208 getSlotIndexes()209 SlotIndexes *getSlotIndexes() const { 210 return Indexes; 211 } 212 213 /// Returns true if the specified machine instr has been removed or was 214 /// never entered in the map. isNotInMIMap(const MachineInstr & Instr)215 bool isNotInMIMap(const MachineInstr &Instr) const { 216 return !Indexes->hasIndex(Instr); 217 } 218 219 /// Returns the base index of the given instruction. getInstructionIndex(const MachineInstr & Instr)220 SlotIndex getInstructionIndex(const MachineInstr &Instr) const { 221 return Indexes->getInstructionIndex(Instr); 222 } 223 224 /// Returns the instruction associated with the given index. getInstructionFromIndex(SlotIndex index)225 MachineInstr* getInstructionFromIndex(SlotIndex index) const { 226 return Indexes->getInstructionFromIndex(index); 227 } 228 229 /// Return the first index in the given basic block. getMBBStartIdx(const MachineBasicBlock * mbb)230 SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const { 231 return Indexes->getMBBStartIdx(mbb); 232 } 233 234 /// Return the last index in the given basic block. getMBBEndIdx(const MachineBasicBlock * mbb)235 SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const { 236 return Indexes->getMBBEndIdx(mbb); 237 } 238 isLiveInToMBB(const LiveRange & LR,const MachineBasicBlock * mbb)239 bool isLiveInToMBB(const LiveRange &LR, 240 const MachineBasicBlock *mbb) const { 241 return LR.liveAt(getMBBStartIdx(mbb)); 242 } 243 isLiveOutOfMBB(const LiveRange & LR,const MachineBasicBlock * mbb)244 bool isLiveOutOfMBB(const LiveRange &LR, 245 const MachineBasicBlock *mbb) const { 246 return LR.liveAt(getMBBEndIdx(mbb).getPrevSlot()); 247 } 248 getMBBFromIndex(SlotIndex index)249 MachineBasicBlock* getMBBFromIndex(SlotIndex index) const { 250 return Indexes->getMBBFromIndex(index); 251 } 252 insertMBBInMaps(MachineBasicBlock * MBB)253 void insertMBBInMaps(MachineBasicBlock *MBB) { 254 Indexes->insertMBBInMaps(MBB); 255 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() && 256 "Blocks must be added in order."); 257 RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0)); 258 } 259 InsertMachineInstrInMaps(MachineInstr & MI)260 SlotIndex InsertMachineInstrInMaps(MachineInstr &MI) { 261 return Indexes->insertMachineInstrInMaps(MI); 262 } 263 InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B,MachineBasicBlock::iterator E)264 void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B, 265 MachineBasicBlock::iterator E) { 266 for (MachineBasicBlock::iterator I = B; I != E; ++I) 267 Indexes->insertMachineInstrInMaps(*I); 268 } 269 RemoveMachineInstrFromMaps(MachineInstr & MI)270 void RemoveMachineInstrFromMaps(MachineInstr &MI) { 271 Indexes->removeMachineInstrFromMaps(MI); 272 } 273 ReplaceMachineInstrInMaps(MachineInstr & MI,MachineInstr & NewMI)274 SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI) { 275 return Indexes->replaceMachineInstrInMaps(MI, NewMI); 276 } 277 getVNInfoAllocator()278 VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; } 279 280 void getAnalysisUsage(AnalysisUsage &AU) const override; 281 void releaseMemory() override; 282 283 /// Pass entry point; Calculates LiveIntervals. 284 bool runOnMachineFunction(MachineFunction&) override; 285 286 /// Implement the dump method. 287 void print(raw_ostream &O, const Module* = nullptr) const override; 288 289 /// If LI is confined to a single basic block, return a pointer to that 290 /// block. If LI is live in to or out of any block, return NULL. 291 MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const; 292 293 /// Returns true if VNI is killed by any PHI-def values in LI. 294 /// This may conservatively return true to avoid expensive computations. 295 bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const; 296 297 /// Add kill flags to any instruction that kills a virtual register. 298 void addKillFlags(const VirtRegMap*); 299 300 /// Call this method to notify LiveIntervals that instruction \p MI has been 301 /// moved within a basic block. This will update the live intervals for all 302 /// operands of \p MI. Moves between basic blocks are not supported. 303 /// 304 /// \param UpdateFlags Update live intervals for nonallocatable physregs. 305 void handleMove(MachineInstr &MI, bool UpdateFlags = false); 306 307 /// Update intervals of operands of all instructions in the newly 308 /// created bundle specified by \p BundleStart. 309 /// 310 /// \param UpdateFlags Update live intervals for nonallocatable physregs. 311 /// 312 /// Assumes existing liveness is accurate. 313 /// \pre BundleStart should be the first instruction in the Bundle. 314 /// \pre BundleStart should not have a have SlotIndex as one will be assigned. 315 void handleMoveIntoNewBundle(MachineInstr &BundleStart, 316 bool UpdateFlags = false); 317 318 /// Update live intervals for instructions in a range of iterators. It is 319 /// intended for use after target hooks that may insert or remove 320 /// instructions, and is only efficient for a small number of instructions. 321 /// 322 /// OrigRegs is a vector of registers that were originally used by the 323 /// instructions in the range between the two iterators. 324 /// 325 /// Currently, the only only changes that are supported are simple removal 326 /// and addition of uses. 327 void repairIntervalsInRange(MachineBasicBlock *MBB, 328 MachineBasicBlock::iterator Begin, 329 MachineBasicBlock::iterator End, 330 ArrayRef<Register> OrigRegs); 331 332 // Register mask functions. 333 // 334 // Machine instructions may use a register mask operand to indicate that a 335 // large number of registers are clobbered by the instruction. This is 336 // typically used for calls. 337 // 338 // For compile time performance reasons, these clobbers are not recorded in 339 // the live intervals for individual physical registers. Instead, 340 // LiveIntervalAnalysis maintains a sorted list of instructions with 341 // register mask operands. 342 343 /// Returns a sorted array of slot indices of all instructions with 344 /// register mask operands. getRegMaskSlots()345 ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; } 346 347 /// Returns a sorted array of slot indices of all instructions with register 348 /// mask operands in the basic block numbered \p MBBNum. getRegMaskSlotsInBlock(unsigned MBBNum)349 ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const { 350 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum]; 351 return getRegMaskSlots().slice(P.first, P.second); 352 } 353 354 /// Returns an array of register mask pointers corresponding to 355 /// getRegMaskSlots(). getRegMaskBits()356 ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits; } 357 358 /// Returns an array of mask pointers corresponding to 359 /// getRegMaskSlotsInBlock(MBBNum). getRegMaskBitsInBlock(unsigned MBBNum)360 ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const { 361 std::pair<unsigned, unsigned> P = RegMaskBlocks[MBBNum]; 362 return getRegMaskBits().slice(P.first, P.second); 363 } 364 365 /// Test if \p LI is live across any register mask instructions, and 366 /// compute a bit mask of physical registers that are not clobbered by any 367 /// of them. 368 /// 369 /// Returns false if \p LI doesn't cross any register mask instructions. In 370 /// that case, the bit vector is not filled in. 371 bool checkRegMaskInterference(const LiveInterval &LI, 372 BitVector &UsableRegs); 373 374 // Register unit functions. 375 // 376 // Fixed interference occurs when MachineInstrs use physregs directly 377 // instead of virtual registers. This typically happens when passing 378 // arguments to a function call, or when instructions require operands in 379 // fixed registers. 380 // 381 // Each physreg has one or more register units, see MCRegisterInfo. We 382 // track liveness per register unit to handle aliasing registers more 383 // efficiently. 384 385 /// Return the live range for register unit \p Unit. It will be computed if 386 /// it doesn't exist. getRegUnit(unsigned Unit)387 LiveRange &getRegUnit(unsigned Unit) { 388 LiveRange *LR = RegUnitRanges[Unit]; 389 if (!LR) { 390 // Compute missing ranges on demand. 391 // Use segment set to speed-up initial computation of the live range. 392 RegUnitRanges[Unit] = LR = new LiveRange(UseSegmentSetForPhysRegs); 393 computeRegUnitRange(*LR, Unit); 394 } 395 return *LR; 396 } 397 398 /// Return the live range for register unit \p Unit if it has already been 399 /// computed, or nullptr if it hasn't been computed yet. getCachedRegUnit(unsigned Unit)400 LiveRange *getCachedRegUnit(unsigned Unit) { 401 return RegUnitRanges[Unit]; 402 } 403 getCachedRegUnit(unsigned Unit)404 const LiveRange *getCachedRegUnit(unsigned Unit) const { 405 return RegUnitRanges[Unit]; 406 } 407 408 /// Remove computed live range for register unit \p Unit. Subsequent uses 409 /// should rely on on-demand recomputation. removeRegUnit(unsigned Unit)410 void removeRegUnit(unsigned Unit) { 411 delete RegUnitRanges[Unit]; 412 RegUnitRanges[Unit] = nullptr; 413 } 414 415 /// Remove associated live ranges for the register units associated with \p 416 /// Reg. Subsequent uses should rely on on-demand recomputation. \note This 417 /// method can result in inconsistent liveness tracking if multiple phyical 418 /// registers share a regunit, and should be used cautiously. removeAllRegUnitsForPhysReg(MCRegister Reg)419 void removeAllRegUnitsForPhysReg(MCRegister Reg) { 420 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 421 removeRegUnit(*Units); 422 } 423 424 /// Remove value numbers and related live segments starting at position 425 /// \p Pos that are part of any liverange of physical register \p Reg or one 426 /// of its subregisters. 427 void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos); 428 429 /// Remove value number and related live segments of \p LI and its subranges 430 /// that start at position \p Pos. 431 void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos); 432 433 /// Split separate components in LiveInterval \p LI into separate intervals. 434 void splitSeparateComponents(LiveInterval &LI, 435 SmallVectorImpl<LiveInterval*> &SplitLIs); 436 437 /// For live interval \p LI with correct SubRanges construct matching 438 /// information for the main live range. Expects the main live range to not 439 /// have any segments or value numbers. 440 void constructMainRangeFromSubranges(LiveInterval &LI); 441 442 private: 443 /// Compute live intervals for all virtual registers. 444 void computeVirtRegs(); 445 446 /// Compute RegMaskSlots and RegMaskBits. 447 void computeRegMasks(); 448 449 /// Walk the values in \p LI and check for dead values: 450 /// - Dead PHIDef values are marked as unused. 451 /// - Dead operands are marked as such. 452 /// - Completely dead machine instructions are added to the \p dead vector 453 /// if it is not nullptr. 454 /// Returns true if any PHI value numbers have been removed which may 455 /// have separated the interval into multiple connected components. 456 bool computeDeadValues(LiveInterval &LI, 457 SmallVectorImpl<MachineInstr*> *dead); 458 459 static LiveInterval *createInterval(Register Reg); 460 461 void printInstrs(raw_ostream &O) const; 462 void dumpInstrs() const; 463 464 void computeLiveInRegUnits(); 465 void computeRegUnitRange(LiveRange&, unsigned Unit); 466 bool computeVirtRegInterval(LiveInterval&); 467 468 using ShrinkToUsesWorkList = SmallVector<std::pair<SlotIndex, VNInfo*>, 16>; 469 void extendSegmentsToUses(LiveRange &Segments, 470 ShrinkToUsesWorkList &WorkList, Register Reg, 471 LaneBitmask LaneMask); 472 473 /// Helper function for repairIntervalsInRange(), walks backwards and 474 /// creates/modifies live segments in \p LR to match the operands found. 475 /// Only full operands or operands with subregisters matching \p LaneMask 476 /// are considered. 477 void repairOldRegInRange(MachineBasicBlock::iterator Begin, 478 MachineBasicBlock::iterator End, 479 const SlotIndex endIdx, LiveRange &LR, 480 Register Reg, 481 LaneBitmask LaneMask = LaneBitmask::getAll()); 482 483 class HMEditor; 484 }; 485 486 } // end namespace llvm 487 488 #endif 489