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

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of llvm/include/llvm/CodeGen/LiveIntervals.h