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