LLVM 24.0.0git
RegisterCoalescer.cpp
Go to the documentation of this file.
1//===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
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// This file implements the generic RegisterCoalescer interface which
10// is used as the common interface used by all clients and
11// implementations of register coalescing.
12//
13//===----------------------------------------------------------------------===//
14
15#include "RegisterCoalescer.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/Passes.h"
45#include "llvm/IR/DebugLoc.h"
47#include "llvm/MC/LaneBitmask.h"
48#include "llvm/MC/MCInstrDesc.h"
50#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
56#include <algorithm>
57#include <cassert>
58#include <iterator>
59#include <limits>
60#include <tuple>
61#include <utility>
62#include <vector>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "regalloc"
67
68STATISTIC(numJoins, "Number of interval joins performed");
69STATISTIC(numCrossRCs, "Number of cross class joins performed");
70STATISTIC(numCommutes, "Number of instruction commuting performed");
71STATISTIC(numExtends, "Number of copies extended");
72STATISTIC(NumReMats, "Number of instructions re-materialized");
73STATISTIC(NumInflated, "Number of register classes inflated");
74STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
75STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
76STATISTIC(NumShrinkToUses, "Number of shrinkToUses called");
77
78static cl::opt<bool> EnableJoining("join-liveintervals",
79 cl::desc("Coalesce copies (default=true)"),
80 cl::init(true), cl::Hidden);
81
82static cl::opt<bool> UseTerminalRule("terminal-rule",
83 cl::desc("Apply the terminal rule"),
84 cl::init(true), cl::Hidden);
85
86/// Temporary flag to test critical edge unsplitting.
88 "join-splitedges",
89 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
90
91/// Temporary flag to test global copy optimization.
93 "join-globalcopies",
94 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
96
98 "verify-coalescing",
99 cl::desc("Verify machine instrs before and after register coalescing"),
100 cl::Hidden);
101
103 "late-remat-update-threshold", cl::Hidden,
104 cl::desc("During rematerialization for a copy, if the def instruction has "
105 "many other copy uses to be rematerialized, delay the multiple "
106 "separate live interval update work and do them all at once after "
107 "all those rematerialization are done. It will save a lot of "
108 "repeated work. "),
109 cl::init(100));
110
112 "large-interval-size-threshold", cl::Hidden,
113 cl::desc("If the valnos size of an interval is larger than the threshold, "
114 "it is regarded as a large interval. "),
115 cl::init(100));
116
118 "large-interval-freq-threshold", cl::Hidden,
119 cl::desc("For a large interval, if it is coalesced with other live "
120 "intervals many times more than the threshold, stop its "
121 "coalescing to control the compile time. "),
122 cl::init(256));
123
124namespace {
125
126class JoinVals;
127
128class RegisterCoalescer : private LiveRangeEdit::Delegate {
129 MachineFunction *MF = nullptr;
130 MachineRegisterInfo *MRI = nullptr;
131 const TargetRegisterInfo *TRI = nullptr;
132 const TargetInstrInfo *TII = nullptr;
133 LiveIntervals *LIS = nullptr;
134 SlotIndexes *SI = nullptr;
135 const MachineLoopInfo *Loops = nullptr;
136 const RegisterClassInfo *RegClassInfo = nullptr;
137
138 /// Position and VReg of a PHI instruction during coalescing.
139 struct PHIValPos {
140 SlotIndex SI; ///< Slot where this PHI occurs.
141 Register Reg; ///< VReg the PHI occurs in.
142 unsigned SubReg; ///< Qualifying subregister for Reg.
143 };
144
145 /// Map from debug instruction number to PHI position during coalescing.
146 DenseMap<unsigned, PHIValPos> PHIValToPos;
147 /// Index of, for each VReg, which debug instruction numbers and
148 /// corresponding PHIs are sensitive to coalescing. Each VReg may have
149 /// multiple PHI defs, at different positions.
150 DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
151
152 /// Debug variable location tracking -- for each VReg, maintain an
153 /// ordered-by-slot-index set of DBG_VALUEs, to help quick
154 /// identification of whether coalescing may change location validity.
155 using DbgValueLoc = std::pair<SlotIndex, MachineInstr *>;
156 DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
157
158 /// A LaneMask to remember on which subregister live ranges we need to call
159 /// shrinkToUses() later.
160 LaneBitmask ShrinkMask;
161
162 /// PHI kills of pruned subrange values. The incoming value of a subrange PHI
163 /// may need to be re-extended from earlier defs after operands are rewritten.
165
166 /// True if the main range of the currently coalesced intervals should be
167 /// checked for smaller live intervals.
168 bool ShrinkMainRange = false;
169
170 /// True if the coalescer should aggressively coalesce global copies
171 /// in favor of keeping local copies.
172 bool JoinGlobalCopies = false;
173
174 /// True if the coalescer should aggressively coalesce fall-thru
175 /// blocks exclusively containing copies.
176 bool JoinSplitEdges = false;
177
178 /// Copy instructions yet to be coalesced.
179 SmallVector<MachineInstr *, 8> WorkList;
180 SmallVector<MachineInstr *, 8> LocalWorkList;
181
182 /// Set of instruction pointers that have been erased, and
183 /// that may be present in WorkList.
184 SmallPtrSet<MachineInstr *, 8> ErasedInstrs;
185
186 /// Dead instructions that are about to be deleted.
187 SmallVector<MachineInstr *, 8> DeadDefs;
188
189 /// Virtual registers to be considered for register class inflation.
190 SmallVector<Register, 8> InflateRegs;
191
192 /// The collection of live intervals which should have been updated
193 /// immediately after rematerialiation but delayed until
194 /// lateLiveIntervalUpdate is called.
195 DenseSet<Register> ToBeUpdated;
196
197 /// Record how many times the large live interval with many valnos
198 /// has been tried to join with other live interval.
199 DenseMap<Register, unsigned long> LargeLIVisitCounter;
200
201 /// Recursively eliminate dead defs in DeadDefs.
202 void eliminateDeadDefs(LiveRangeEdit *Edit = nullptr);
203
204 /// LiveRangeEdit callback for eliminateDeadDefs().
205 void LRE_WillEraseInstruction(MachineInstr *MI) override;
206
207 /// Coalesce the LocalWorkList.
208 void coalesceLocals();
209
210 /// Join compatible live intervals
211 void joinAllIntervals();
212
213 /// Coalesce copies in the specified MBB, putting
214 /// copies that cannot yet be coalesced into WorkList.
215 void copyCoalesceInMBB(MachineBasicBlock *MBB);
216
217 /// Tries to coalesce all copies in CurrList. Returns true if any progress
218 /// was made.
219 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr *> CurrList);
220
221 /// If one def has many copy like uses, and those copy uses are all
222 /// rematerialized, the live interval update needed for those
223 /// rematerializations will be delayed and done all at once instead
224 /// of being done multiple times. This is to save compile cost because
225 /// live interval update is costly.
226 void lateLiveIntervalUpdate();
227
228 /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
229 /// has no value defined in the predecessors. If the incoming value is the
230 /// same as defined by the copy itself, the value is considered undefined.
231 bool copyValueUndefInPredecessors(LiveRange &S, const MachineBasicBlock *MBB,
232 LiveQueryResult SLRQ);
233
234 /// Set necessary undef flags on subregister uses after pruning out undef
235 /// lane segments from the subrange.
236 void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
237 LaneBitmask PrunedLanes);
238
239 /// Result of attempting to coalesce a copy.
240 /// - Joined: the copy was removed or otherwise fully handled.
241 /// - Deferred: retry after other coalescing may make progress.
242 /// - Rejected: do not retry, either because the copy is not a coalescing
243 /// candidate or because the join was intentionally rejected.
244 enum class JoinResult { Joined, Deferred, Rejected };
245
246 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
247 /// src/dst of the copy instruction CopyMI.
248 JoinResult joinCopy(MachineInstr *CopyMI,
249 SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs);
250
251 /// Attempt to join these two intervals. On failure, the output "SrcInt"
252 /// will not have been modified, so we can use this information below to
253 /// update aliases. Returns Deferred when it may be possible to join later,
254 /// or Rejected when retrying should be avoided.
255 JoinResult joinIntervals(CoalescerPair &CP);
256
257 /// Attempt joining two virtual registers.
258 JoinResult joinVirtRegs(CoalescerPair &CP);
259
260 /// If a live interval has many valnos and is coalesced with other
261 /// live intervals many times, we regard such live interval as having
262 /// high compile time cost.
263 bool isHighCostLiveInterval(LiveInterval &LI);
264
265 /// Attempt joining with a reserved physreg.
266 bool joinReservedPhysReg(CoalescerPair &CP);
267
268 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
269 /// Subranges in @p LI which only partially interfere with the desired
270 /// LaneMask are split as necessary. @p LaneMask are the lanes that
271 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
272 /// lanemasks already adjusted to the coalesced register.
273 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
274 LaneBitmask LaneMask, CoalescerPair &CP,
275 unsigned DstIdx);
276
277 /// Join the liveranges of two subregisters. Joins @p RRange into
278 /// @p LRange, @p RRange may be invalid afterwards.
279 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
280 LaneBitmask LaneMask, const CoalescerPair &CP);
281
282 /// We found a non-trivially-coalescable copy. If the source value number is
283 /// defined by a copy from the destination reg see if we can merge these two
284 /// destination reg valno# into a single value number, eliminating a copy.
285 /// This returns true if an interval was modified.
286 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
287
288 /// Return true if there are definitions of IntB
289 /// other than BValNo val# that can reach uses of AValno val# of IntA.
290 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
291 VNInfo *AValNo, VNInfo *BValNo);
292
293 /// We found a non-trivially-coalescable copy.
294 /// If the source value number is defined by a commutable instruction and
295 /// its other operand is coalesced to the copy dest register, see if we
296 /// can transform the copy into a noop by commuting the definition.
297 /// This returns a pair of two flags:
298 /// - the first element is true if an interval was modified,
299 /// - the second element is true if the destination interval needs
300 /// to be shrunk after deleting the copy.
301 std::pair<bool, bool> removeCopyByCommutingDef(const CoalescerPair &CP,
302 MachineInstr *CopyMI);
303
304 /// We found a copy which can be moved to its less frequent predecessor.
305 bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
306
307 /// If the source of a copy is defined by a CheapAsAMove computation,
308 /// replace the copy by rematerialize the definition.
309 bool reMaterializeDef(const CoalescerPair &CP, MachineInstr *CopyMI,
310 bool &IsDefCopy);
311
312 /// Return true if a copy involving a physreg should be joined.
313 bool canJoinPhys(const CoalescerPair &CP);
314
315 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
316 /// number if it is not zero. If DstReg is a physical register and the
317 /// existing subregister number of the def / use being updated is not zero,
318 /// make sure to set it to the correct physical subregister.
319 void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
320
321 /// Fix up the subranges of \p LI after values were pruned by the join:
322 /// re-extend the pruned PHI inputs in PHIKills to their remaining defs, and
323 /// shrink the subranges in ShrinkMask.
324 void updatePrunedSubRanges(LiveInterval &LI);
325
326 /// If the given machine operand reads only undefined lanes add an undef
327 /// flag.
328 /// This can happen when undef uses were previously concealed by a copy
329 /// which we coalesced. Example:
330 /// %0:sub0<def,read-undef> = ...
331 /// %1 = COPY %0 <-- Coalescing COPY reveals undef
332 /// = use %1:sub1 <-- hidden undef use
333 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
334 MachineOperand &MO, unsigned SubRegIdx);
335
336 /// Handle copies of undef values. If the undef value is an incoming
337 /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
338 /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
339 /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
340 MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
341
342 /// Check whether or not we should apply the terminal rule on the
343 /// destination (Dst) of \p Copy.
344 /// When the terminal rule applies, Copy is not profitable to
345 /// coalesce.
346 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
347 /// at least one interference (Dst, Dst2). If Dst is terminal, the
348 /// terminal rule consists in checking that at least one of
349 /// interfering node, say Dst2, has an affinity of equal or greater
350 /// weight with Src.
351 /// In that case, Dst2 and Dst will not be able to be both coalesced
352 /// with Src. Since Dst2 exposes more coalescing opportunities than
353 /// Dst, we can drop \p Copy.
354 bool applyTerminalRule(const MachineInstr &Copy) const;
355
356 /// Wrapper method for \see LiveIntervals::shrinkToUses.
357 /// This method does the proper fixing of the live-ranges when the afore
358 /// mentioned method returns true.
359 void shrinkToUses(LiveInterval *LI,
360 SmallVectorImpl<MachineInstr *> *Dead = nullptr) {
361 NumShrinkToUses++;
362 if (LIS->shrinkToUses(LI, Dead)) {
363 /// Check whether or not \p LI is composed by multiple connected
364 /// components and if that is the case, fix that.
366 LIS->splitSeparateComponents(*LI, SplitLIs);
367 }
368 }
369
370 /// Wrapper Method to do all the necessary work when an Instruction is
371 /// deleted.
372 /// Optimizations should use this to make sure that deleted instructions
373 /// are always accounted for.
374 void deleteInstr(MachineInstr *MI) {
375 ErasedInstrs.insert(MI);
376 LIS->RemoveMachineInstrFromMaps(*MI);
377 MI->eraseFromParent();
378 }
379
380 /// Walk over function and initialize the DbgVRegToValues map.
382
383 /// Test whether, after merging, any DBG_VALUEs would refer to a
384 /// different value number than before merging, and whether this can
385 /// be resolved. If not, mark the DBG_VALUE as being undef.
386 void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
387 JoinVals &LHSVals, LiveRange &RHS,
388 JoinVals &RHSVals);
389
390 void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
391 LiveRange &RegRange, JoinVals &Vals2);
392
393public:
394 // For legacy pass only.
395 RegisterCoalescer() = default;
396 RegisterCoalescer &operator=(RegisterCoalescer &&Other) = default;
397
398 RegisterCoalescer(LiveIntervals *LIS, SlotIndexes *SI,
399 const MachineLoopInfo *Loops,
400 const RegisterClassInfo *RegClassInfo)
401 : LIS(LIS), SI(SI), Loops(Loops), RegClassInfo(RegClassInfo) {}
402
403 bool run(MachineFunction &MF);
404};
405
406class RegisterCoalescerLegacy : public MachineFunctionPass {
407public:
408 static char ID; ///< Class identification, replacement for typeinfo
409
410 RegisterCoalescerLegacy() : MachineFunctionPass(ID) {}
411
412 void getAnalysisUsage(AnalysisUsage &AU) const override;
413
414 MachineFunctionProperties getClearedProperties() const override {
415 return MachineFunctionProperties().setIsSSA();
416 }
417
418 /// This is the pass entry point.
419 bool runOnMachineFunction(MachineFunction &) override;
420};
421
422} // end anonymous namespace
423
424char RegisterCoalescerLegacy::ID = 0;
425
426char &llvm::RegisterCoalescerID = RegisterCoalescerLegacy::ID;
427
428INITIALIZE_PASS_BEGIN(RegisterCoalescerLegacy, "register-coalescer",
429 "Register Coalescer", false, false)
434INITIALIZE_PASS_END(RegisterCoalescerLegacy, "register-coalescer",
435 "Register Coalescer", false, false)
436
437[[nodiscard]] static bool isMoveInstr(const TargetRegisterInfo &tri,
439 Register &Dst, unsigned &SrcSub,
440 unsigned &DstSub) {
441 if (MI->isCopy()) {
442 Dst = MI->getOperand(0).getReg();
443 DstSub = MI->getOperand(0).getSubReg();
444 Src = MI->getOperand(1).getReg();
445 SrcSub = MI->getOperand(1).getSubReg();
446 } else if (MI->isSubregToReg()) {
447 Dst = MI->getOperand(0).getReg();
448 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
449 MI->getOperand(2).getImm());
450 Src = MI->getOperand(1).getReg();
451 SrcSub = MI->getOperand(1).getSubReg();
452 } else
453 return false;
454 return true;
455}
456
457/// Return true if this block should be vacated by the coalescer to eliminate
458/// branches. The important cases to handle in the coalescer are critical edges
459/// split during phi elimination which contain only copies. Simple blocks that
460/// contain non-branches should also be vacated, but this can be handled by an
461/// earlier pass similar to early if-conversion.
462static bool isSplitEdge(const MachineBasicBlock *MBB) {
463 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
464 return false;
465
466 for (const auto &MI : *MBB) {
467 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
468 return false;
469 }
470 return true;
471}
472
474 SrcReg = DstReg = Register();
475 SrcIdx = DstIdx = 0;
476 NewRC = nullptr;
477 Flipped = CrossClass = false;
478
479 Register Src, Dst;
480 unsigned SrcSub = 0, DstSub = 0;
481 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
482 return false;
483 Partial = SrcSub || DstSub;
484
485 // If one register is a physreg, it must be Dst.
486 if (Src.isPhysical()) {
487 if (Dst.isPhysical())
488 return false;
489 std::swap(Src, Dst);
490 std::swap(SrcSub, DstSub);
491 Flipped = true;
492 }
493
494 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
495 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
496
497 if (Dst.isPhysical()) {
498 // Eliminate DstSub on a physreg.
499 if (DstSub) {
500 Dst = TRI.getSubReg(Dst, DstSub);
501 if (!Dst)
502 return false;
503 DstSub = 0;
504 }
505
506 // Eliminate SrcSub by picking a corresponding Dst superregister.
507 if (SrcSub) {
508 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, SrcRC);
509 if (!Dst)
510 return false;
511 } else if (!SrcRC->contains(Dst)) {
512 return false;
513 }
514 } else {
515 // Both registers are virtual.
516 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
517
518 // Both registers have subreg indices.
519 if (SrcSub && DstSub) {
520 // Copies between different sub-registers are never coalescable.
521 if (Src == Dst && SrcSub != DstSub)
522 return false;
523
524 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, SrcIdx,
525 DstIdx);
526 if (!NewRC)
527 return false;
528 } else if (DstSub) {
529 // SrcReg will be merged with a sub-register of DstReg.
530 SrcIdx = DstSub;
531 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
532 } else if (SrcSub) {
533 // DstReg will be merged with a sub-register of SrcReg.
534 DstIdx = SrcSub;
535 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
536 } else {
537 // This is a straight copy without sub-registers.
538 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
539 }
540
541 // The combined constraint may be impossible to satisfy.
542 if (!NewRC)
543 return false;
544
545 // Prefer SrcReg to be a sub-register of DstReg.
546 // FIXME: Coalescer should support subregs symmetrically.
547 if (DstIdx && !SrcIdx) {
548 std::swap(Src, Dst);
549 std::swap(SrcIdx, DstIdx);
550 Flipped = !Flipped;
551 }
552
553 CrossClass = NewRC != DstRC || NewRC != SrcRC;
554 }
555 // Check our invariants
556 assert(Src.isVirtual() && "Src must be virtual");
557 assert(!(Dst.isPhysical() && DstSub) && "Cannot have a physical SubIdx");
558 SrcReg = Src;
559 DstReg = Dst;
560 return true;
561}
562
564 if (DstReg.isPhysical())
565 return false;
566 std::swap(SrcReg, DstReg);
567 std::swap(SrcIdx, DstIdx);
568 Flipped = !Flipped;
569 return true;
570}
571
573 if (!MI)
574 return false;
575 Register Src, Dst;
576 unsigned SrcSub = 0, DstSub = 0;
577 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
578 return false;
579
580 // Find the virtual register that is SrcReg.
581 if (Dst == SrcReg) {
582 std::swap(Src, Dst);
583 std::swap(SrcSub, DstSub);
584 } else if (Src != SrcReg) {
585 return false;
586 }
587
588 // Now check that Dst matches DstReg.
589 if (DstReg.isPhysical()) {
590 if (!Dst.isPhysical())
591 return false;
592 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
593 // DstSub could be set for a physreg from INSERT_SUBREG.
594 if (DstSub)
595 Dst = TRI.getSubReg(Dst, DstSub);
596 // Full copy of Src.
597 if (!SrcSub)
598 return DstReg == Dst;
599 // This is a partial register copy. Check that the parts match.
600 return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
601 }
602
603 // DstReg is virtual.
604 if (DstReg != Dst)
605 return false;
606 // Registers match, do the subregisters line up?
607 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
608 TRI.composeSubRegIndices(DstIdx, DstSub);
609}
610
611void RegisterCoalescerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
612 AU.setPreservesCFG();
620}
621
622void RegisterCoalescer::eliminateDeadDefs(LiveRangeEdit *Edit) {
623 if (Edit) {
624 Edit->eliminateDeadDefs(DeadDefs);
625 return;
626 }
628 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, nullptr, this)
629 .eliminateDeadDefs(DeadDefs);
630}
631
632void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
633 // MI may be in WorkList. Make sure we don't visit it.
634 ErasedInstrs.insert(MI);
635}
636
637bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
638 MachineInstr *CopyMI) {
639 assert(!CP.isPartial() && "This doesn't work for partial copies.");
640 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
641
642 LiveInterval &IntA =
643 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
644 LiveInterval &IntB =
645 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
646 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
647
648 // We have a non-trivially-coalescable copy with IntA being the source and
649 // IntB being the dest, thus this defines a value number in IntB. If the
650 // source value number (in IntA) is defined by a copy from B, see if we can
651 // merge these two pieces of B into a single value number, eliminating a copy.
652 // For example:
653 //
654 // A3 = B0
655 // ...
656 // B1 = A3 <- this copy
657 //
658 // In this case, B0 can be extended to where the B1 copy lives, allowing the
659 // B1 value number to be replaced with B0 (which simplifies the B
660 // liveinterval).
661
662 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
663 // the example above.
665 if (BS == IntB.end())
666 return false;
667 VNInfo *BValNo = BS->valno;
668
669 // Get the location that B is defined at. Two options: either this value has
670 // an unknown definition point or it is defined at CopyIdx. If unknown, we
671 // can't process it.
672 if (BValNo->def != CopyIdx)
673 return false;
674
675 // AValNo is the value number in A that defines the copy, A3 in the example.
676 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
677 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
678 // The live segment might not exist after fun with physreg coalescing.
679 if (AS == IntA.end())
680 return false;
681 VNInfo *AValNo = AS->valno;
682
683 // If AValNo is defined as a copy from IntB, we can potentially process this.
684 // Get the instruction that defines this value number.
685 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
686 // Don't allow any partial copies, even if isCoalescable() allows them.
687 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
688 return false;
689
690 // Get the Segment in IntB that this value number starts with.
692 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
693 if (ValS == IntB.end())
694 return false;
695
696 // Make sure that the end of the live segment is inside the same block as
697 // CopyMI.
698 MachineInstr *ValSEndInst =
699 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
700 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
701 return false;
702
703 // Okay, we now know that ValS ends in the same block that the CopyMI
704 // live-range starts. If there are no intervening live segments between them
705 // in IntB, we can merge them.
706 if (ValS + 1 != BS)
707 return false;
708
709 LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI));
710
711 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
712 // We are about to delete CopyMI, so need to remove it as the 'instruction
713 // that defines this value #'. Update the valnum with the new defining
714 // instruction #.
715 BValNo->def = FillerStart;
716
717 // Okay, we can merge them. We need to insert a new liverange:
718 // [ValS.end, BS.begin) of either value number, then we merge the
719 // two value numbers.
720 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
721
722 // Okay, merge "B1" into the same value number as "B0".
723 if (BValNo != ValS->valno)
724 IntB.MergeValueNumberInto(BValNo, ValS->valno);
725
726 // Do the same for the subregister segments.
727 for (LiveInterval::SubRange &S : IntB.subranges()) {
728 // Check for SubRange Segments of the form [1234r,1234d:0) which can be
729 // removed to prevent creating bogus SubRange Segments.
730 LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
731 if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
732 S.removeSegment(*SS, true);
733 continue;
734 }
735 // The subrange may have ended before FillerStart. If so, extend it.
736 if (!S.getVNInfoAt(FillerStart)) {
737 SlotIndex BBStart =
738 LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
739 S.extendInBlock(BBStart, FillerStart);
740 }
741 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
742 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
743 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
744 if (SubBValNo != SubValSNo)
745 S.MergeValueNumberInto(SubBValNo, SubValSNo);
746 }
747
748 LLVM_DEBUG(dbgs() << " result = " << IntB << '\n');
749
750 // If the source instruction was killing the source register before the
751 // merge, unset the isKill marker given the live range has been extended.
752 int UIdx =
753 ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), /*TRI=*/nullptr, true);
754 if (UIdx != -1) {
755 ValSEndInst->getOperand(UIdx).setIsKill(false);
756 }
757
758 // Rewrite the copy.
759 CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
760 // If the copy instruction was killing the destination register or any
761 // subrange before the merge trim the live range.
762 bool RecomputeLiveRange = AS->end == CopyIdx;
763 if (!RecomputeLiveRange) {
764 for (LiveInterval::SubRange &S : IntA.subranges()) {
765 LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
766 if (SS != S.end() && SS->end == CopyIdx) {
767 RecomputeLiveRange = true;
768 break;
769 }
770 }
771 }
772 if (RecomputeLiveRange)
773 shrinkToUses(&IntA);
774
775 ++numExtends;
776 return true;
777}
778
779bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
780 LiveInterval &IntB, VNInfo *AValNo,
781 VNInfo *BValNo) {
782 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
783 // the PHI values.
784 if (LIS->hasPHIKill(IntA, AValNo))
785 return true;
786
787 for (LiveRange::Segment &ASeg : IntA.segments) {
788 if (ASeg.valno != AValNo)
789 continue;
791 if (BI != IntB.begin())
792 --BI;
793 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
794 if (BI->valno == BValNo)
795 continue;
796 if (BI->start <= ASeg.start && BI->end > ASeg.start)
797 return true;
798 if (BI->start > ASeg.start && BI->start < ASeg.end)
799 return true;
800 }
801 }
802 return false;
803}
804
805/// Copy segments with value number @p SrcValNo from liverange @p Src to live
806/// range @Dst and use value number @p DstValNo there.
807static std::pair<bool, bool> addSegmentsWithValNo(LiveRange &Dst,
808 VNInfo *DstValNo,
809 const LiveRange &Src,
810 const VNInfo *SrcValNo) {
811 bool Changed = false;
812 bool MergedWithDead = false;
813 for (const LiveRange::Segment &S : Src.segments) {
814 if (S.valno != SrcValNo)
815 continue;
816 // This is adding a segment from Src that ends in a copy that is about
817 // to be removed. This segment is going to be merged with a pre-existing
818 // segment in Dst. This works, except in cases when the corresponding
819 // segment in Dst is dead. For example: adding [192r,208r:1) from Src
820 // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
821 // Recognized such cases, so that the segments can be shrunk.
822 LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
823 LiveRange::Segment &Merged = *Dst.addSegment(Added);
824 if (Merged.end.isDead())
825 MergedWithDead = true;
826 Changed = true;
827 }
828 return std::make_pair(Changed, MergedWithDead);
829}
830
831std::pair<bool, bool>
832RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
833 MachineInstr *CopyMI) {
834 assert(!CP.isPhys());
835
836 LiveInterval &IntA =
837 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
838 LiveInterval &IntB =
839 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
840
841 // We found a non-trivially-coalescable copy with IntA being the source and
842 // IntB being the dest, thus this defines a value number in IntB. If the
843 // source value number (in IntA) is defined by a commutable instruction and
844 // its other operand is coalesced to the copy dest register, see if we can
845 // transform the copy into a noop by commuting the definition. For example,
846 //
847 // A3 = op A2 killed B0
848 // ...
849 // B1 = A3 <- this copy
850 // ...
851 // = op A3 <- more uses
852 //
853 // ==>
854 //
855 // B2 = op B0 killed A2
856 // ...
857 // B1 = B2 <- now an identity copy
858 // ...
859 // = op B2 <- more uses
860
861 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
862 // the example above.
863 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
864 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
865 assert(BValNo != nullptr && BValNo->def == CopyIdx);
866
867 // AValNo is the value number in A that defines the copy, A3 in the example.
868 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
869 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
870 if (AValNo->isPHIDef())
871 return {false, false};
873 if (!DefMI)
874 return {false, false};
875 if (!DefMI->isCommutable())
876 return {false, false};
877 // If DefMI is a two-address instruction then commuting it will change the
878 // destination register.
879 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg(), /*TRI=*/nullptr);
880 assert(DefIdx != -1);
881 unsigned UseOpIdx;
882 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
883 return {false, false};
884
885 // If DefMI only defines the register partially, we can't replace uses of the
886 // full register with the new destination register after commuting it.
887 if (IntA.reg().isVirtual() &&
888 none_of(DefMI->all_defs(), [&](const MachineOperand &DefMO) {
889 return DefMO.getReg() == IntA.reg() && !DefMO.getSubReg();
890 }))
891 return {false, false};
892
893 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
894 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
895 // passed to the method. That _other_ operand is chosen by
896 // the findCommutedOpIndices() method.
897 //
898 // That is obviously an area for improvement in case of instructions having
899 // more than 2 operands. For example, if some instruction has 3 commutable
900 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
901 // op#2<->op#3) of commute transformation should be considered/tried here.
902 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
903 if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
904 return {false, false};
905
906 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
907 Register NewReg = NewDstMO.getReg();
908 if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
909 return {false, false};
910
911 // Make sure there are no other definitions of IntB that would reach the
912 // uses which the new definition can reach.
913 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
914 return {false, false};
915
916 // Make sure all reads of AValNo can be rewritten to the new register.
917 for (MachineOperand &MO : MRI->reg_nodbg_operands(IntA.reg())) {
918 if (!MO.readsReg())
919 continue;
920 MachineInstr *UseMI = MO.getParent();
921 unsigned OpNo = &MO - &UseMI->getOperand(0);
922 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
924 if (US == IntA.end() || US->valno != AValNo)
925 continue;
926 // Partial defs and tied uses can't be rewritten independently.
927 if (MO.isDef() || UseMI->isRegTiedToDefOperand(OpNo))
928 return {false, false};
929 }
930
931 LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
932 << *DefMI);
933
934 // At this point we have decided that it is legal to do this
935 // transformation. Start by commuting the instruction.
937 MachineInstr *NewMI =
938 TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
939 if (!NewMI)
940 return {false, false};
941 if (IntA.reg().isVirtual() && IntB.reg().isVirtual() &&
942 !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
943 return {false, false};
944 if (NewMI != DefMI) {
945 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
947 MBB->insert(Pos, NewMI);
948 MBB->erase(DefMI);
949 }
950
951 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
952 // A = or A, B
953 // ...
954 // B = A
955 // ...
956 // C = killed A
957 // ...
958 // = B
959
960 // Update uses of IntA of the specific Val# with IntB.
961 for (MachineOperand &UseMO :
963 if (UseMO.isUndef())
964 continue;
965 MachineInstr *UseMI = UseMO.getParent();
966 if (UseMI->isDebugInstr()) {
967 // FIXME These don't have an instruction index. Not clear we have enough
968 // info to decide whether to do this replacement or not. For now do it.
969 UseMO.setReg(NewReg);
970 continue;
971 }
972 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
974 assert(US != IntA.end() && "Use must be live");
975 if (US->valno != AValNo)
976 continue;
977 // Kill flags are no longer accurate. They are recomputed after RA.
978 UseMO.setIsKill(false);
979 if (NewReg.isPhysical())
980 UseMO.substPhysReg(NewReg, *TRI);
981 else
982 UseMO.setReg(NewReg);
983 if (UseMI == CopyMI)
984 continue;
985 if (!UseMI->isCopy())
986 continue;
987 if (UseMI->getOperand(0).getReg() != IntB.reg() ||
989 continue;
990
991 // This copy will become a noop. If it's defining a new val#, merge it into
992 // BValNo.
993 SlotIndex DefIdx = UseIdx.getRegSlot();
994 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
995 if (!DVNI)
996 continue;
997 LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
998 assert(DVNI->def == DefIdx);
999 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
1000 for (LiveInterval::SubRange &S : IntB.subranges()) {
1001 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
1002 if (!SubDVNI)
1003 continue;
1004 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
1005 assert(SubBValNo->def == CopyIdx);
1006 S.MergeValueNumberInto(SubDVNI, SubBValNo);
1007 }
1008
1009 deleteInstr(UseMI);
1010 }
1011
1012 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
1013 // is updated.
1014 bool ShrinkB = false;
1016 if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
1017 if (!IntA.hasSubRanges()) {
1019 IntA.createSubRangeFrom(Allocator, Mask, IntA);
1020 } else if (!IntB.hasSubRanges()) {
1022 IntB.createSubRangeFrom(Allocator, Mask, IntB);
1023 }
1024 SlotIndex AIdx = CopyIdx.getRegSlot(true);
1025 LaneBitmask MaskA;
1026 const SlotIndexes &Indexes = *LIS->getSlotIndexes();
1027 for (LiveInterval::SubRange &SA : IntA.subranges()) {
1028 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
1029 // Even if we are dealing with a full copy, some lanes can
1030 // still be undefined.
1031 // E.g.,
1032 // undef A.subLow = ...
1033 // B = COPY A <== A.subHigh is undefined here and does
1034 // not have a value number.
1035 if (!ASubValNo)
1036 continue;
1037 MaskA |= SA.LaneMask;
1038
1039 IntB.refineSubRanges(
1040 Allocator, SA.LaneMask,
1041 [&Allocator, &SA, CopyIdx, ASubValNo,
1042 &ShrinkB](LiveInterval::SubRange &SR) {
1043 VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
1044 : SR.getVNInfoAt(CopyIdx);
1045 assert(BSubValNo != nullptr);
1046 auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
1047 ShrinkB |= P.second;
1048 if (P.first)
1049 BSubValNo->def = ASubValNo->def;
1050 },
1051 Indexes, *TRI);
1052 }
1053 // Go over all subranges of IntB that have not been covered by IntA,
1054 // and delete the segments starting at CopyIdx. This can happen if
1055 // IntA has undef lanes that are defined in IntB.
1056 for (LiveInterval::SubRange &SB : IntB.subranges()) {
1057 if ((SB.LaneMask & MaskA).any())
1058 continue;
1059 if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
1060 if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
1061 SB.removeSegment(*S, true);
1062 }
1063 }
1064
1065 BValNo->def = AValNo->def;
1066 auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
1067 ShrinkB |= P.second;
1068 LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
1069
1070 LIS->removeVRegDefAt(IntA, AValNo->def);
1071
1072 LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
1073 ++numCommutes;
1074 return {true, ShrinkB};
1075}
1076
1077/// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
1078/// predecessor of BB2, and if B is not redefined on the way from A = B
1079/// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
1080/// execution goes through the path from BB0 to BB2. We may move B = A
1081/// to the predecessor without such reversed copy.
1082/// So we will transform the program from:
1083/// BB0:
1084/// A = B; BB1:
1085/// ... ...
1086/// / \ /
1087/// BB2:
1088/// ...
1089/// B = A;
1090///
1091/// to:
1092///
1093/// BB0: BB1:
1094/// A = B; ...
1095/// ... B = A;
1096/// / \ /
1097/// BB2:
1098/// ...
1099///
1100/// A special case is when BB0 and BB2 are the same BB which is the only
1101/// BB in a loop:
1102/// BB1:
1103/// ...
1104/// BB0/BB2: ----
1105/// B = A; |
1106/// ... |
1107/// A = B; |
1108/// |-------
1109/// |
1110/// We may hoist B = A from BB0/BB2 to BB1.
1111///
1112/// The major preconditions for correctness to remove such partial
1113/// redundancy include:
1114/// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
1115/// the PHI is defined by the reversed copy A = B in BB0.
1116/// 2. No B is referenced from the start of BB2 to B = A.
1117/// 3. No B is defined from A = B to the end of BB0.
1118/// 4. BB1 has only one successor.
1119///
1120/// 2 and 4 implicitly ensure B is not live at the end of BB1.
1121/// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
1122/// colder place, which not only prevent endless loop, but also make sure
1123/// the movement of copy is beneficial.
1124bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
1125 MachineInstr &CopyMI) {
1126 assert(!CP.isPhys());
1127 if (!CopyMI.isFullCopy())
1128 return false;
1129
1130 MachineBasicBlock &MBB = *CopyMI.getParent();
1131 // If this block is the target of an invoke/inlineasm_br, moving the copy into
1132 // the predecessor is tricker, and we don't handle it.
1134 return false;
1135
1136 if (MBB.pred_size() != 2)
1137 return false;
1138
1139 LiveInterval &IntA =
1140 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
1141 LiveInterval &IntB =
1142 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
1143
1144 // A is defined by PHI at the entry of MBB.
1145 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
1146 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
1147 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
1148 if (!AValNo->isPHIDef())
1149 return false;
1150
1151 // No B is referenced before CopyMI in MBB.
1152 if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
1153 return false;
1154
1155 // MBB has two predecessors: one contains A = B so no copy will be inserted
1156 // for it. The other one will have a copy moved from MBB.
1157 bool FoundReverseCopy = false;
1158 MachineBasicBlock *CopyLeftBB = nullptr;
1160 VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
1162 if (!DefMI || !DefMI->isFullCopy()) {
1163 CopyLeftBB = Pred;
1164 continue;
1165 }
1166 // Check DefMI is a reverse copy and it is in BB Pred.
1167 if (DefMI->getOperand(0).getReg() != IntA.reg() ||
1168 DefMI->getOperand(1).getReg() != IntB.reg() ||
1169 DefMI->getParent() != Pred) {
1170 CopyLeftBB = Pred;
1171 continue;
1172 }
1173 // If there is any other def of B after DefMI and before the end of Pred,
1174 // we need to keep the copy of B = A at the end of Pred if we remove
1175 // B = A from MBB.
1176 bool ValB_Changed = false;
1177 for (auto *VNI : IntB.valnos) {
1178 if (VNI->isUnused())
1179 continue;
1180 if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
1181 ValB_Changed = true;
1182 break;
1183 }
1184 }
1185 if (ValB_Changed) {
1186 CopyLeftBB = Pred;
1187 continue;
1188 }
1189 FoundReverseCopy = true;
1190 }
1191
1192 // If no reverse copy is found in predecessors, nothing to do.
1193 if (!FoundReverseCopy)
1194 return false;
1195
1196 // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
1197 // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
1198 // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
1199 // update IntA/IntB.
1200 //
1201 // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
1202 // MBB is hotter than CopyLeftBB.
1203 if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
1204 return false;
1205
1206 // Now (almost sure it's) ok to move copy.
1207 if (CopyLeftBB) {
1208 // Position in CopyLeftBB where we should insert new copy.
1209 auto InsPos = CopyLeftBB->getFirstTerminator();
1210
1211 // Make sure that B isn't referenced in the terminators (if any) at the end
1212 // of the predecessor since we're about to insert a new definition of B
1213 // before them.
1214 if (InsPos != CopyLeftBB->end()) {
1215 SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
1216 if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
1217 return false;
1218 }
1219
1220 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
1221 << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
1222
1223 // Insert new copy to CopyLeftBB.
1224 MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1225 TII->get(TargetOpcode::COPY), IntB.reg())
1226 .addReg(IntA.reg());
1227 SlotIndex NewCopyIdx =
1228 LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1229 IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1230 for (LiveInterval::SubRange &SR : IntB.subranges())
1231 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1232
1233 // If the newly created Instruction has an address of an instruction that
1234 // was deleted before (object recycled by the allocator) it needs to be
1235 // removed from the deleted list.
1236 ErasedInstrs.erase(NewCopyMI);
1237 } else {
1238 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
1239 << printMBBReference(MBB) << '\t' << CopyMI);
1240 }
1241
1242 const bool IsUndefCopy = CopyMI.getOperand(1).isUndef();
1243
1244 // Remove CopyMI.
1245 // Note: This is fine to remove the copy before updating the live-ranges.
1246 // While updating the live-ranges, we only look at slot indices and
1247 // never go back to the instruction.
1248 // Mark instructions as deleted.
1249 deleteInstr(&CopyMI);
1250
1251 // Update the liveness.
1252 SmallVector<SlotIndex, 8> EndPoints;
1253 VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
1254 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
1255 &EndPoints);
1256 BValNo->markUnused();
1257
1258 if (IsUndefCopy) {
1259 // We're introducing an undef phi def, and need to set undef on any users of
1260 // the previously local def to avoid artifically extending the lifetime
1261 // through the block.
1262 for (MachineOperand &MO : MRI->use_nodbg_operands(IntB.reg())) {
1263 const MachineInstr &MI = *MO.getParent();
1264 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1265 if (!IntB.liveAt(UseIdx))
1266 MO.setIsUndef(true);
1267 }
1268 }
1269
1270 // Extend IntB to the EndPoints of its original live interval.
1271 LIS->extendToIndices(IntB, EndPoints);
1272
1273 // Now, do the same for its subranges.
1274 for (LiveInterval::SubRange &SR : IntB.subranges()) {
1275 EndPoints.clear();
1276 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1277 assert(BValNo && "All sublanes should be live");
1278 LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
1279 BValNo->markUnused();
1280 // We can have a situation where the result of the original copy is live,
1281 // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
1282 // the copy appear as an endpoint from pruneValue(), but we don't want it
1283 // to because the copy has been removed. We can go ahead and remove that
1284 // endpoint; there is no other situation here that there could be a use at
1285 // the same place as we know that the copy is a full copy.
1286 for (unsigned I = 0; I != EndPoints.size();) {
1287 if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
1288 EndPoints[I] = EndPoints.back();
1289 EndPoints.pop_back();
1290 continue;
1291 }
1292 ++I;
1293 }
1295 IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
1296 *LIS->getSlotIndexes());
1297 LIS->extendToIndices(SR, EndPoints, Undefs);
1298 }
1299 // If any dead defs were extended, truncate them.
1300 shrinkToUses(&IntB);
1301
1302 // Finally, update the live-range of IntA.
1303 shrinkToUses(&IntA);
1304 return true;
1305}
1306
1307bool RegisterCoalescer::reMaterializeDef(const CoalescerPair &CP,
1308 MachineInstr *CopyMI,
1309 bool &IsDefCopy) {
1310 IsDefCopy = false;
1311 Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1312 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1313 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1314 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1315 if (SrcReg.isPhysical())
1316 return false;
1317
1318 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1319 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1320 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1321 if (!ValNo)
1322 return false;
1323 if (ValNo->isPHIDef())
1324 return false;
1326 assert(DefMI && "Defining instruction disappeared!");
1327 if (DefMI->isCopyLike()) {
1328 IsDefCopy = true;
1329 return false;
1330 }
1331 if (!TII->isAsCheapAsAMove(*DefMI))
1332 return false;
1333
1334 if (!TII->isReMaterializable(*DefMI))
1335 return false;
1336
1337 bool SawStore = false;
1338 if (!DefMI->isSafeToMove(SawStore))
1339 return false;
1340 const MCInstrDesc &MCID = DefMI->getDesc();
1341 if (MCID.getNumDefs() != 1)
1342 return false;
1343
1344 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1345 // the register substantially (beyond both source and dest size). This is bad
1346 // for performance since it can cascade through a function, introducing many
1347 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1348 // around after a few subreg copies).
1349 if (SrcIdx && DstIdx)
1350 return false;
1351
1352 // Only support subregister destinations when the def is read-undef.
1353 MachineOperand &DstOperand = CopyMI->getOperand(0);
1354 Register CopyDstReg = DstOperand.getReg();
1355 if (DstOperand.getSubReg() && !DstOperand.isUndef())
1356 return false;
1357
1358 // In the physical register case, checking that the def is read-undef is not
1359 // enough. We're widening the def and need to avoid clobbering other live
1360 // values in the unused register pieces.
1361 //
1362 // TODO: Targets may support rewriting the rematerialized instruction to only
1363 // touch relevant lanes, in which case we don't need any liveness check.
1364 if (CopyDstReg.isPhysical() && CP.isPartial()) {
1365 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
1366 // Ignore the register units we are writing anyway.
1367 if (is_contained(TRI->regunits(CopyDstReg), Unit))
1368 continue;
1369
1370 // Check if the other lanes we are defining are live at the
1371 // rematerialization point.
1372 LiveRange &LR = LIS->getRegUnit(Unit);
1373 if (LR.liveAt(CopyIdx))
1374 return false;
1375 }
1376 }
1377
1378 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0);
1379
1380 if (!VirtRegAuxInfo::allUsesAvailableAt(DefMI, CopyIdx, *LIS, *MRI, *TII))
1381 return false;
1382
1383 DebugLoc DL = CopyMI->getDebugLoc();
1384 MachineBasicBlock *MBB = CopyMI->getParent();
1386 std::next(MachineBasicBlock::iterator(CopyMI));
1387 LiveRangeEdit::Remat RM(ValNo);
1388 RM.OrigMI = DefMI;
1390 LiveRangeEdit Edit(&SrcInt, NewRegs, *MF, *LIS, nullptr, this);
1391 Edit.rematerializeAt(*MBB, MII, DstReg, RM, *TRI, false, SrcIdx, CopyMI);
1392 MachineInstr &NewMI = *std::prev(MII);
1393 assert(LIS->getInstructionIndex(NewMI) == CopyIdx);
1394 NewMI.setDebugLoc(DL);
1395
1396 // In a situation like the following:
1397 // %0:subreg = instr ; DefMI, subreg = DstIdx
1398 // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
1399 // instead of widening %1 to the register class of %0 simply do:
1400 // %1 = instr
1401 const TargetRegisterClass *NewRC = CP.getNewRC();
1402 if (DstIdx != 0) {
1403 MachineOperand &DefMO = NewMI.getOperand(0);
1404 if (DefMO.getSubReg() == DstIdx) {
1405 assert(SrcIdx == 0 && CP.isFlipped() &&
1406 "Shouldn't have SrcIdx+DstIdx at this point");
1407 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1408 const TargetRegisterClass *CommonRC =
1409 TRI->getCommonSubClass(DefRC, DstRC);
1410 if (CommonRC != nullptr) {
1411 NewRC = CommonRC;
1412
1413 // Instruction might contain "undef %0:subreg" as use operand:
1414 // %0:subreg = instr op_1, ..., op_N, undef %0:subreg, op_N+2, ...
1415 //
1416 // Need to check all operands.
1417 for (MachineOperand &MO : NewMI.operands()) {
1418 if (MO.isReg() && MO.getReg() == DstReg && MO.getSubReg() == DstIdx) {
1419 MO.setSubReg(0);
1420 }
1421 }
1422
1423 DstIdx = 0;
1424 }
1425 }
1426 }
1427
1428 // CopyMI may have implicit operands, save them so that we can transfer them
1429 // over to the newly materialized instruction after CopyMI is removed.
1431 ImplicitOps.reserve(CopyMI->getNumOperands() -
1432 CopyMI->getDesc().getNumOperands());
1433 for (unsigned I = CopyMI->getDesc().getNumOperands(),
1434 E = CopyMI->getNumOperands();
1435 I != E; ++I) {
1436 MachineOperand &MO = CopyMI->getOperand(I);
1437 if (MO.isReg()) {
1438 assert(MO.isImplicit() &&
1439 "No explicit operands after implicit operands.");
1440 assert((MO.getReg().isPhysical() ||
1441 (MO.getSubReg() == 0 && MO.getReg() == DstOperand.getReg())) &&
1442 "unexpected implicit virtual register def");
1443 ImplicitOps.push_back(MO);
1444 }
1445 }
1446
1447 CopyMI->eraseFromParent();
1448 ErasedInstrs.insert(CopyMI);
1449
1450 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1451 // We need to remember these so we can add intervals once we insert
1452 // NewMI into SlotIndexes.
1453 //
1454 // We also expect to have tied implicit-defs of super registers originating
1455 // from SUBREG_TO_REG, such as:
1456 // $edi = MOV32r0 implicit-def dead $eflags, implicit-def $rdi
1457 // undef %0.sub_32bit = MOV32r0 implicit-def dead $eflags, implicit-def %0
1458 //
1459 // The implicit-def of the super register may have been reduced to
1460 // subregisters depending on the uses.
1462 for (unsigned i = NewMI.getDesc().getNumOperands(),
1463 e = NewMI.getNumOperands();
1464 i != e; ++i) {
1465 MachineOperand &MO = NewMI.getOperand(i);
1466 if (MO.isReg() && MO.isDef()) {
1467 assert(MO.isImplicit());
1468 if (MO.getReg().isPhysical()) {
1469 assert(
1470 MO.isDead() ||
1471 (DefMI->getOperand(0).getSubReg() &&
1472 ((TRI->getSubReg(MO.getReg(), DefMI->getOperand(0).getSubReg()) ==
1473 MCRegister((unsigned)NewMI.getOperand(0).getReg())) ||
1474 TRI->isSubRegisterEq(NewMI.getOperand(0).getReg(),
1475 MO.getReg()))));
1476 NewMIImplDefs.push_back({i, MO.getReg()});
1477 } else {
1478 assert(MO.getReg() == NewMI.getOperand(0).getReg());
1479
1480 // We're only expecting another def of the main output, so the range
1481 // should get updated with the regular output range.
1482 //
1483 // FIXME: The range updating below probably needs updating to look at
1484 // the super register if subranges are tracked.
1486 "subrange update for implicit-def of super register may not be "
1487 "properly handled");
1488 }
1489 }
1490 }
1491
1492 if (DstReg.isVirtual()) {
1493 unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1494
1495 assert(
1496 (!DefRC ||
1497 NewRC == (NewIdx ? TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx)
1498 : TRI->getCommonSubClass(NewRC, DefRC))) &&
1499 "Subreg chosen for remat incompatible with instruction!");
1500
1501 LiveInterval &DstInt = LIS->getInterval(DstReg);
1502 MRI->setRegClass(DstReg, NewRC);
1503 if (DstIdx) {
1504 // Remap subranges to new lanemask.
1505 for (LiveInterval::SubRange &SR : DstInt.subranges())
1506 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1507
1508 // Update machine operands and add flags.
1509 updateRegDefsUses(DstReg, DstReg, DstIdx);
1510 NewMI.getOperand(0).setSubReg(NewIdx);
1511 }
1512 // updateRegDefUses can add an "undef" flag to the definition, since
1513 // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
1514 // sure that "undef" is not set.
1515 if (NewIdx == 0)
1516 NewMI.getOperand(0).setIsUndef(false);
1517 NewMI.setRegisterDefReadUndef(DstReg);
1518
1519 // In a situation like the following:
1520 //
1521 // undef %2.subreg:reg = INST %1:reg ; DefMI (rematerializable),
1522 // ; Defines only some of lanes,
1523 // ; so NewIdx = subreg
1524 // %3:reg = COPY %2 ; Copy full reg
1525 // .... = SOMEINSTR %3:reg ; Use full reg
1526 //
1527 // there are no subranges for %3 so after rematerialization we need
1528 // to explicitly create them. Undefined subranges are removed later on.
1529 if (NewIdx && !DstInt.hasSubRanges() &&
1530 MRI->shouldTrackSubRegLiveness(DstReg)) {
1531 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstReg);
1532 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(NewIdx);
1533 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1535 DstInt.createSubRangeFrom(Alloc, UsedLanes, DstInt);
1536 DstInt.createSubRangeFrom(Alloc, UnusedLanes, DstInt);
1537 }
1538
1539 // Update the subranges to match the lanes defined by NewMI. NewMI may
1540 // define more of the register than the copy it replaces, in which case the
1541 // extra lanes need at least a dead def. For example:
1542 // %1 = LOAD_CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1543 // ; Copying only part of the register here, but the rest is undef.
1544 // undef %2.sub_16bit = COPY %1.sub_16bit
1545 // ==>
1546 // ; Materialize all the constants but only using one
1547 // %2 = LOAD_CONSTANTS 5, 8
1548 //
1549 // Conversely, if NewMI only defines a subregister then the copied value in
1550 // the other lanes is now undef and must be removed. For example:
1551 // undef %1.sub1 = LOAD_CONSTANT 1
1552 // %2 = COPY %1
1553 // ==>
1554 // undef %2.sub1 = LOAD_CONSTANT 1
1555 // ; Correct but need to remove the subrange for %2:sub0 as it is now
1556 // ; undef.
1557 if (DstInt.hasSubRanges()) {
1558 LaneBitmask DstMask = NewIdx ? TRI->getSubRegIndexLaneMask(NewIdx)
1559 : MRI->getMaxLaneMaskForVReg(DstReg);
1560 SlotIndex DefIndex =
1561 CopyIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1563
1564 // Refine the subranges that are now defined by the remat.
1565 // This will split existing subranges if necessary.
1566 DstInt.refineSubRanges(
1567 Alloc, DstMask,
1568 [&DefIndex, &Alloc](LiveInterval::SubRange &SR) {
1569 // We know that this lane is defined by this instruction,
1570 // but at this point it might not be live because it was not defined
1571 // by the original instruction. This happens when the
1572 // rematerialization widens the defined register. Assign that lane a
1573 // dead def so that the interferences are properly modeled.
1574 if (!SR.liveAt(DefIndex))
1575 SR.createDeadDef(DefIndex, Alloc);
1576 },
1577 *LIS->getSlotIndexes(), *TRI);
1578
1579 // The subregister segments that are not defined by the remat can be
1580 // removed.
1581 bool UpdatedSubRanges = false;
1582 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1583 if ((SR.LaneMask & DstMask).none()) {
1585 << "Removing undefined SubRange "
1586 << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
1587
1588 if (VNInfo *RmValNo = SR.getVNInfoAt(CopyIdx.getRegSlot())) {
1589 // VNI is in ValNo - remove any segments in this SubRange that have
1590 // this ValNo
1591 SR.removeValNo(RmValNo);
1592 }
1593
1594 // We may not have a defined value at this point, but still need to
1595 // clear out any empty subranges tentatively created by
1596 // updateRegDefUses. The original subrange def may have only undefed
1597 // some lanes.
1598 UpdatedSubRanges = true;
1599 }
1600 }
1601 if (UpdatedSubRanges)
1602 DstInt.removeEmptySubRanges();
1603 }
1604 } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1605 // The New instruction may be defining a sub-register of what's actually
1606 // been asked for. If so it must implicitly define the whole thing.
1607
1608 // CopyDstReg is added as an implicit-def below. If the remat defines a
1609 // sub-register of CopyDstReg, the def is part of that live value and must
1610 // stay live. Otherwise only the part covered by CopyDstReg is used, so the
1611 // def is dead.
1612 if (!TRI->isSuperRegister(NewMI.getOperand(0).getReg(), CopyDstReg))
1613 NewMI.getOperand(0).setIsDead(true);
1614
1615 bool HasDefMatchingCopy = false;
1616 for (auto [OpIndex, Reg] : NewMIImplDefs) {
1617 if (Reg != DstReg)
1618 continue;
1619 // Also, if CopyDstReg is a sub-register of DstReg (and it is defined), we
1620 // must mark DstReg as dead since it is not going to used as a result of
1621 // this remat.
1622 if (DstReg != CopyDstReg)
1623 NewMI.getOperand(OpIndex).setIsDead(true);
1624 else
1625 HasDefMatchingCopy = true;
1626 }
1627
1628 // If NewMI does not already have an implicit-def CopyDstReg add one now.
1629 if (!HasDefMatchingCopy)
1631 CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1632
1633 // Record small dead def live-ranges for all the subregisters
1634 // of the destination register.
1635 // Otherwise, variables that live through may miss some
1636 // interferences, thus creating invalid allocation.
1637 // E.g., i386 code:
1638 // %1 = somedef ; %1 GR8
1639 // %2 = remat ; %2 GR32
1640 // CL = COPY %2.sub_8bit
1641 // = somedef %1 ; %1 GR8
1642 // =>
1643 // %1 = somedef ; %1 GR8
1644 // dead ECX = remat ; implicit-def CL
1645 // = somedef %1 ; %1 GR8
1646 // %1 will see the interferences with CL but not with CH since
1647 // no live-ranges would have been created for ECX.
1648 // Fix that!
1649 for (MCRegUnit Unit : TRI->regunits(NewMI.getOperand(0).getReg()))
1650 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1651 LR->createDeadDef(CopyIdx.getRegSlot(), LIS->getVNInfoAllocator());
1652 }
1653
1654 // Transfer over implicit operands to the rematerialized instruction.
1655 for (MachineOperand &MO : ImplicitOps)
1656 NewMI.addOperand(MO);
1657
1658 for (Register Reg : make_second_range(NewMIImplDefs)) {
1659 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
1660 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1661 LR->createDeadDef(CopyIdx.getRegSlot(), LIS->getVNInfoAllocator());
1662 }
1663
1664 LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
1665 ++NumReMats;
1666
1667 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1668 // to describe DstReg instead.
1669 if (MRI->use_nodbg_empty(SrcReg)) {
1670 for (MachineOperand &UseMO :
1672 MachineInstr *UseMI = UseMO.getParent();
1674 if (DstReg.isPhysical())
1675 UseMO.substPhysReg(DstReg, *TRI);
1676 else
1677 UseMO.setReg(DstReg);
1678 // Move the debug value directly after the def of the rematerialized
1679 // value in DstReg.
1680 MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
1681 LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1682 }
1683 }
1684
1685 if (ToBeUpdated.count(SrcReg))
1686 return true;
1687
1688 unsigned NumCopyUses = 0;
1689 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
1690 if (UseMO.getParent()->isCopyLike())
1691 NumCopyUses++;
1692 }
1693 if (NumCopyUses < LateRematUpdateThreshold) {
1694 // The source interval can become smaller because we removed a use.
1695 shrinkToUses(&SrcInt, &DeadDefs);
1696 if (!DeadDefs.empty())
1697 eliminateDeadDefs(&Edit);
1698 } else {
1699 ToBeUpdated.insert(SrcReg);
1700 }
1701 return true;
1702}
1703
1704MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1705 // ProcessImplicitDefs may leave some copies of <undef> values, it only
1706 // removes local variables. When we have a copy like:
1707 //
1708 // %1 = COPY undef %2
1709 //
1710 // We delete the copy and remove the corresponding value number from %1.
1711 // Any uses of that value number are marked as <undef>.
1712
1713 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1714 // CoalescerPair may have a new register class with adjusted subreg indices
1715 // at this point.
1716 Register SrcReg, DstReg;
1717 unsigned SrcSubIdx = 0, DstSubIdx = 0;
1718 if (!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1719 return nullptr;
1720
1721 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1722 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1723 // CopyMI is undef iff SrcReg is not live before the instruction.
1724 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1725 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1726 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1727 if ((SR.LaneMask & SrcMask).none())
1728 continue;
1729 if (SR.liveAt(Idx))
1730 return nullptr;
1731 }
1732 } else if (SrcLI.liveAt(Idx))
1733 return nullptr;
1734
1735 // If the undef copy defines a live-out value (i.e. an input to a PHI def),
1736 // then replace it with an IMPLICIT_DEF.
1737 LiveInterval &DstLI = LIS->getInterval(DstReg);
1738 SlotIndex RegIndex = Idx.getRegSlot();
1739 LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
1740 assert(Seg != nullptr && "No segment for defining instruction");
1741 VNInfo *V = DstLI.getVNInfoAt(Seg->end);
1742
1743 // The source interval may also have been on an undef use, in which case the
1744 // copy introduced a live value.
1745 if (((V && V->isPHIDef()) || (!V && !DstLI.liveAt(Idx)))) {
1746 for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
1747 MachineOperand &MO = CopyMI->getOperand(i - 1);
1748 if (MO.isReg()) {
1749 if (MO.isUse())
1750 CopyMI->removeOperand(i - 1);
1751 } else {
1752 assert(MO.isImm() &&
1753 CopyMI->getOpcode() == TargetOpcode::SUBREG_TO_REG);
1754 CopyMI->removeOperand(i - 1);
1755 }
1756 }
1757
1758 CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1759 LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
1760 "implicit def\n");
1761 return CopyMI;
1762 }
1763
1764 // Remove any DstReg segments starting at the instruction.
1765 LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1766
1767 // Remove value or merge with previous one in case of a subregister def.
1768 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1769 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1770 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1771
1772 // The affected subregister segments can be removed.
1773 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1774 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1775 if ((SR.LaneMask & DstMask).none())
1776 continue;
1777
1778 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1779 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1780 SR.removeValNo(SVNI);
1781 }
1782 DstLI.removeEmptySubRanges();
1783 } else
1784 LIS->removeVRegDefAt(DstLI, RegIndex);
1785
1786 // Mark uses as undef.
1787 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1788 if (MO.isDef() && !MO.getSubReg())
1789 continue;
1790 const MachineInstr &MI = *MO.getParent();
1791 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1792 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1793 if (MO.isDef())
1794 UseMask = ~UseMask;
1795 bool isLive;
1796 if (!UseMask.all() && DstLI.hasSubRanges()) {
1797 isLive = false;
1798 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1799 if ((SR.LaneMask & UseMask).none())
1800 continue;
1801 if (SR.liveAt(UseIdx)) {
1802 isLive = true;
1803 break;
1804 }
1805 }
1806 } else
1807 isLive = DstLI.liveAt(UseIdx);
1808 if (isLive)
1809 continue;
1810 MO.setIsUndef(true);
1811 LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1812 }
1813
1814 // A def of a subregister may be a use of the other subregisters, so
1815 // deleting a def of a subregister may also remove uses. Since CopyMI
1816 // is still part of the function (but about to be erased), mark all
1817 // defs of DstReg in it as <undef>, so that shrinkToUses would
1818 // ignore them.
1819 for (MachineOperand &MO : CopyMI->all_defs())
1820 if (MO.getReg() == DstReg)
1821 MO.setIsUndef(true);
1822 LIS->shrinkToUses(&DstLI);
1823
1824 return CopyMI;
1825}
1826
1827void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1828 MachineOperand &MO, unsigned SubRegIdx) {
1829 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1830 if (MO.isDef())
1831 Mask = ~Mask;
1832 bool IsUndef = true;
1833 for (const LiveInterval::SubRange &S : Int.subranges()) {
1834 if ((S.LaneMask & Mask).none())
1835 continue;
1836 if (S.liveAt(UseIdx)) {
1837 IsUndef = false;
1838 break;
1839 }
1840 }
1841 if (IsUndef) {
1842 MO.setIsUndef(true);
1843 // We found out some subregister use is actually reading an undefined
1844 // value. In some cases the whole vreg has become undefined at this
1845 // point so we have to potentially shrink the main range if the
1846 // use was ending a live segment there.
1847 LiveQueryResult Q = Int.Query(UseIdx);
1848 if (Q.valueOut() == nullptr)
1849 ShrinkMainRange = true;
1850 }
1851}
1852
1853void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
1854 unsigned SubIdx) {
1855 bool DstIsPhys = DstReg.isPhysical();
1856 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1857
1858 if (DstInt && DstReg != SrcReg) {
1859 bool HasSubRanges = DstInt->hasSubRanges();
1860 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1861 if (MO.isUndef())
1862 continue;
1863 unsigned SubReg = MO.getSubReg();
1864 if (SubReg == 0 && MO.isDef())
1865 continue;
1866
1867 SlotIndex UseIdx =
1868 LIS->getInstructionIndex(*MO.getParent()).getRegSlot(true);
1869 if (HasSubRanges) {
1870 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1871 } else if (MO.isUse() && SubReg == 0 && !DstInt->liveAt(UseIdx)) {
1872 // A full-register use already referencing DstReg (not renamed from
1873 // SrcReg) may have no reaching def after the join if its feeding COPY
1874 // and erasable IMPLICIT_DEF were removed. Mark such uses undef; the
1875 // SrcReg rename loop below only visits SrcReg operands and will miss
1876 // these.
1877 MO.setIsUndef(true);
1878 }
1879 }
1880 }
1881
1884 E = MRI->reg_instr_end();
1885 I != E;) {
1886 MachineInstr *UseMI = &*(I++);
1887
1888 // Each instruction can only be rewritten once because sub-register
1889 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1890 // the UseMI operands removes them from the SrcReg use-def chain, but when
1891 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1892 // operands mentioning the virtual register.
1893 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1894 continue;
1895
1897 bool Reads, Writes;
1898 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1899
1900 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1901 // because SrcReg is a sub-register.
1902 if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
1903 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1904
1905 // Replace SrcReg with DstReg in all UseMI operands.
1906 for (unsigned Op : Ops) {
1908
1909 // Adjust <undef> flags in case of sub-register joins. We don't want to
1910 // turn a full def into a read-modify-write sub-register def and vice
1911 // versa.
1912 if (SubIdx && MO.isDef())
1913 MO.setIsUndef(!Reads);
1914
1915 // A subreg use of a partially undef (super) register may be a complete
1916 // undef use now and then has to be marked that way.
1917 if (MO.isUse() && !MO.isUndef() && !DstIsPhys) {
1918 unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
1919 if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
1920 if (!DstInt->hasSubRanges()) {
1922 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
1923 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1924 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1925 DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1926 // The unused lanes are just empty live-ranges at this point.
1927 // It is the caller responsibility to set the proper
1928 // dead segments if there is an actual dead def of the
1929 // unused lanes. This may happen with rematerialization.
1930 DstInt->createSubRange(Allocator, UnusedLanes);
1931 }
1932 SlotIndex MIIdx = UseMI->isDebugInstr()
1934 : LIS->getInstructionIndex(*UseMI);
1935 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1936 addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
1937 }
1938 }
1939
1940 if (DstIsPhys)
1941 MO.substPhysReg(DstReg, *TRI);
1942 else
1943 MO.substVirtReg(DstReg, SubIdx, *TRI);
1944 }
1945
1946 LLVM_DEBUG({
1947 dbgs() << "\t\tupdated: ";
1948 if (!UseMI->isDebugInstr())
1949 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
1950 dbgs() << *UseMI;
1951 });
1952 }
1953}
1954
1955bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1956 // Always join simple intervals that are defined by a single copy from a
1957 // reserved register. This doesn't increase register pressure, so it is
1958 // always beneficial.
1959 if (!MRI->isReserved(CP.getDstReg())) {
1960 LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1961 return false;
1962 }
1963
1964 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1965 if (JoinVInt.containsOneValue())
1966 return true;
1967
1968 LLVM_DEBUG(
1969 dbgs() << "\tCannot join complex intervals into reserved register.\n");
1970 return false;
1971}
1972
1973bool RegisterCoalescer::copyValueUndefInPredecessors(
1975 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
1976 SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
1977 if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
1978 // If this is a self loop, we may be reading the same value.
1979 if (V->id != SLRQ.valueOutOrDead()->id)
1980 return false;
1981 }
1982 }
1983
1984 return true;
1985}
1986
1987void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
1988 Register Reg,
1989 LaneBitmask PrunedLanes) {
1990 // If we had other instructions in the segment reading the undef sublane
1991 // value, we need to mark them with undef.
1993 unsigned SubRegIdx = MO.getSubReg();
1994 if (SubRegIdx == 0 || MO.isUndef())
1995 continue;
1996
1997 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1998 SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
1999 for (LiveInterval::SubRange &S : LI.subranges()) {
2000 if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
2001 MO.setIsUndef();
2002 break;
2003 }
2004 }
2005 }
2006
2008
2009 // A def of a subregister may be a use of other register lanes. Replacing
2010 // such a def with a def of a different register will eliminate the use,
2011 // and may cause the recorded live range to be larger than the actual
2012 // liveness in the program IR.
2013 LIS->shrinkToUses(&LI);
2014}
2015
2016void RegisterCoalescer::updatePrunedSubRanges(LiveInterval &LI) {
2017 for (LiveInterval::SubRange &S : LI.subranges()) {
2018 SmallVector<SlotIndex, 8> EndPoints;
2019 for (auto [Mask, Idx] : PHIKills) {
2020 if ((Mask & S.LaneMask).any() && LI.liveAt(Idx.getPrevSlot()))
2021 EndPoints.push_back(Idx);
2022 }
2023
2024 if (!EndPoints.empty()) {
2026 LI.computeSubRangeUndefs(Undefs, S.LaneMask, *MRI,
2027 *LIS->getSlotIndexes());
2028 LIS->extendToIndices(S, EndPoints, Undefs);
2029 }
2030
2031 if ((S.LaneMask & ShrinkMask).none())
2032 continue;
2033
2034 LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
2035 << ")\n");
2036 LIS->shrinkToUses(S, LI.reg());
2037 ShrinkMainRange = true;
2038 }
2039
2041}
2042
2043RegisterCoalescer::JoinResult RegisterCoalescer::joinCopy(
2044 MachineInstr *CopyMI,
2045 SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs) {
2046 LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
2047
2048 CoalescerPair CP(*TRI);
2049 if (!CP.setRegisters(CopyMI)) {
2050 LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
2051 return JoinResult::Rejected;
2052 }
2053
2054 if (CP.getNewRC()) {
2055 if (RegClassInfo->getNumAllocatableRegs(CP.getNewRC()) == 0) {
2056 LLVM_DEBUG(dbgs() << "\tNo " << TRI->getRegClassName(CP.getNewRC())
2057 << "are available for allocation\n");
2058 return JoinResult::Rejected;
2059 }
2060
2061 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
2062 auto DstRC = MRI->getRegClass(CP.getDstReg());
2063 unsigned SrcIdx = CP.getSrcIdx();
2064 unsigned DstIdx = CP.getDstIdx();
2065 if (CP.isFlipped()) {
2066 std::swap(SrcIdx, DstIdx);
2067 std::swap(SrcRC, DstRC);
2068 }
2069 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
2070 CP.getNewRC(), *LIS)) {
2071 LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
2072 return JoinResult::Rejected;
2073 }
2074 }
2075
2076 // Dead code elimination. This really should be handled by MachineDCE, but
2077 // sometimes dead copies slip through, and we can't generate invalid live
2078 // ranges.
2079 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
2080 LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
2081 DeadDefs.push_back(CopyMI);
2082 eliminateDeadDefs();
2083 return JoinResult::Joined;
2084 }
2085
2086 // Eliminate undefs.
2087 if (!CP.isPhys()) {
2088 // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
2089 if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
2090 if (UndefMI->isImplicitDef())
2091 return JoinResult::Rejected;
2092 deleteInstr(CopyMI);
2093 return JoinResult::Rejected; // Not coalescable.
2094 }
2095 }
2096
2097 // Coalesced copies are normally removed immediately, but transformations
2098 // like removeCopyByCommutingDef() can inadvertently create identity copies.
2099 // When that happens, just join the values and remove the copy.
2100 if (CP.getSrcReg() == CP.getDstReg()) {
2101 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
2102 LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
2103 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
2104 LiveQueryResult LRQ = LI.Query(CopyIdx);
2105 if (VNInfo *DefVNI = LRQ.valueDefined()) {
2106 VNInfo *ReadVNI = LRQ.valueIn();
2107 assert(ReadVNI && "No value before copy and no <undef> flag.");
2108 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
2109
2110 // Track incoming undef lanes we need to eliminate from the subrange.
2111 LaneBitmask PrunedLanes;
2112 MachineBasicBlock *MBB = CopyMI->getParent();
2113
2114 // Process subregister liveranges.
2115 for (LiveInterval::SubRange &S : LI.subranges()) {
2116 LiveQueryResult SLRQ = S.Query(CopyIdx);
2117 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
2118 if (VNInfo *SReadVNI = SLRQ.valueIn())
2119 SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
2120
2121 // If this copy introduced an undef subrange from an incoming value,
2122 // we need to eliminate the undef live in values from the subrange.
2123 if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
2124 LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n");
2125 PrunedLanes |= S.LaneMask;
2126 S.removeValNo(SDefVNI);
2127 }
2128 }
2129 }
2130
2131 LI.MergeValueNumberInto(DefVNI, ReadVNI);
2132 if (PrunedLanes.any()) {
2133 LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: " << PrunedLanes
2134 << '\n');
2135 setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
2136 }
2137
2138 LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
2139 }
2140 deleteInstr(CopyMI);
2141 return JoinResult::Joined;
2142 }
2143
2144 // Enforce policies.
2145 if (CP.isPhys()) {
2146 LLVM_DEBUG(dbgs() << "\tConsidering merging "
2147 << printReg(CP.getSrcReg(), TRI) << " with "
2148 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
2149 if (!canJoinPhys(CP)) {
2150 // Before giving up coalescing, try rematerializing the source of
2151 // the copy instead if it is cheap.
2152 bool IsDefCopy = false;
2153 if (reMaterializeDef(CP, CopyMI, IsDefCopy))
2154 return JoinResult::Joined;
2155 if (IsDefCopy)
2156 return JoinResult::Deferred; // May be possible to coalesce later.
2157 return JoinResult::Rejected;
2158 }
2159 } else {
2160 // When possible, let DstReg be the larger interval.
2161 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
2162 LIS->getInterval(CP.getDstReg()).size())
2163 CP.flip();
2164
2165 LLVM_DEBUG({
2166 dbgs() << "\tConsidering merging to "
2167 << TRI->getRegClassName(CP.getNewRC()) << " with ";
2168 if (CP.getDstIdx() && CP.getSrcIdx())
2169 dbgs() << printReg(CP.getDstReg()) << " in "
2170 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
2171 << printReg(CP.getSrcReg()) << " in "
2172 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
2173 else
2174 dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
2175 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
2176 });
2177 }
2178
2179 ShrinkMask = LaneBitmask::getNone();
2180 ShrinkMainRange = false;
2181 PHIKills.clear();
2182
2183 // Okay, attempt to join these two intervals. If one of the intervals being
2184 // joined is a physreg and the join succeeds, this method always canonicalizes
2185 // DstInt to be it. The output "SrcInt" will not have been modified, so we
2186 // can use this information below to update aliases.
2187 JoinResult Result = joinIntervals(CP);
2188 if (Result != JoinResult::Joined) {
2189 // Coalescing failed.
2190
2191 // Try rematerializing the definition of the source if it is cheap.
2192 bool IsDefCopy = false;
2193 if (reMaterializeDef(CP, CopyMI, IsDefCopy))
2194 return JoinResult::Joined;
2195
2196 // If we can eliminate the copy without merging the live segments, do so
2197 // now.
2198 if (!CP.isPartial() && !CP.isPhys()) {
2199 bool Changed = adjustCopiesBackFrom(CP, CopyMI);
2200 bool Shrink = false;
2201 if (!Changed)
2202 std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
2203 if (Changed) {
2204 deleteInstr(CopyMI);
2205 if (Shrink) {
2206 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
2207 LiveInterval &DstLI = LIS->getInterval(DstReg);
2208 shrinkToUses(&DstLI);
2209 LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n');
2210 }
2211 LLVM_DEBUG(dbgs() << "\tTrivial!\n");
2212 return JoinResult::Joined;
2213 }
2214 }
2215
2216 // Try and see if we can partially eliminate the copy by moving the copy to
2217 // its predecessor.
2218 if (!CP.isPartial() && !CP.isPhys())
2219 if (removePartialRedundancy(CP, *CopyMI))
2220 return JoinResult::Joined;
2221
2222 // Otherwise, we are unable to join the intervals.
2223 LLVM_DEBUG(dbgs() << "\tInterference!\n");
2224 // A high-cost interval is already too expensive to retry. Keeping the copy
2225 // in WorkList would make every subsequent successful join rescan it again,
2226 // which can dominate compile time.
2227 if (Result == JoinResult::Deferred)
2228 LLVM_DEBUG(dbgs() << "\tWill retry later.\n");
2229 return Result;
2230 }
2231
2232 // Coalescing to a virtual register that is of a sub-register class of the
2233 // other. Make sure the resulting register is set to the right register class.
2234 if (CP.isCrossClass()) {
2235 ++numCrossRCs;
2236 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
2237 }
2238
2239 // Removing sub-register copies can ease the register class constraints.
2240 // Make sure we attempt to inflate the register class of DstReg.
2241 if (!CP.isPhys() && RegClassInfo->isProperSubClass(CP.getNewRC()))
2242 InflateRegs.push_back(CP.getDstReg());
2243
2244 // CopyMI has been erased by joinIntervals at this point. Remove it from
2245 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
2246 // to the work list. This keeps ErasedInstrs from growing needlessly.
2247 if (ErasedInstrs.erase(CopyMI))
2248 // But we may encounter the instruction again in this iteration.
2249 CurrentErasedInstrs.insert(CopyMI);
2250
2251 // Rewrite all SrcReg operands to DstReg.
2252 // Also update DstReg operands to include DstIdx if it is set.
2253 if (CP.getDstIdx())
2254 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
2255 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
2256
2257 if (ShrinkMask.any() || !PHIKills.empty())
2258 updatePrunedSubRanges(LIS->getInterval(CP.getDstReg()));
2259
2260 // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
2261 // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
2262 // is not up-to-date, need to update the merged live interval here.
2263 if (ShrinkMainRange || ToBeUpdated.count(CP.getSrcReg()))
2264 shrinkToUses(&LIS->getInterval(CP.getDstReg()));
2265
2266 // SrcReg is guaranteed to be the register whose live interval that is
2267 // being merged.
2268 LIS->removeInterval(CP.getSrcReg());
2269
2270 // Update regalloc hint.
2271 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
2272
2273 LLVM_DEBUG({
2274 dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
2275 << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
2276 dbgs() << "\tResult = ";
2277 if (CP.isPhys())
2278 dbgs() << printReg(CP.getDstReg(), TRI);
2279 else
2280 dbgs() << LIS->getInterval(CP.getDstReg());
2281 dbgs() << '\n';
2282 });
2283
2284 ++numJoins;
2285 return JoinResult::Joined;
2286}
2287
2288bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2289 Register DstReg = CP.getDstReg();
2290 Register SrcReg = CP.getSrcReg();
2291 assert(CP.isPhys() && "Must be a physreg copy");
2292 assert(MRI->isReserved(DstReg) && "Not a reserved register");
2293 LiveInterval &RHS = LIS->getInterval(SrcReg);
2294 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
2295
2296 assert(RHS.containsOneValue() && "Invalid join with reserved register");
2297
2298 // Optimization for reserved registers like ESP. We can only merge with a
2299 // reserved physreg if RHS has a single value that is a copy of DstReg.
2300 // The live range of the reserved register will look like a set of dead defs
2301 // - we don't properly track the live range of reserved registers.
2302
2303 // Deny any overlapping intervals. This depends on all the reserved
2304 // register live ranges to look like dead defs.
2305 if (!MRI->isConstantPhysReg(DstReg)) {
2306 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2307 // Abort if not all the regunits are reserved.
2308 for (MCRegUnitRootIterator RI(Unit, TRI); RI.isValid(); ++RI) {
2309 if (!MRI->isReserved(*RI))
2310 return false;
2311 }
2312 if (RHS.overlaps(LIS->getRegUnit(Unit))) {
2313 LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(Unit, TRI)
2314 << '\n');
2315 return false;
2316 }
2317 }
2318
2319 // We must also check for overlaps with regmask clobbers.
2320 BitVector RegMaskUsable;
2321 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
2322 !RegMaskUsable.test(DstReg.id())) {
2323 LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
2324 return false;
2325 }
2326 }
2327
2328 // Skip any value computations, we are not adding new values to the
2329 // reserved register. Also skip merging the live ranges, the reserved
2330 // register live range doesn't need to be accurate as long as all the
2331 // defs are there.
2332
2333 // Delete the identity copy.
2334 MachineInstr *CopyMI;
2335 if (CP.isFlipped()) {
2336 // Physreg is copied into vreg
2337 // %y = COPY %physreg_x
2338 // ... //< no other def of %physreg_x here
2339 // use %y
2340 // =>
2341 // ...
2342 // use %physreg_x
2343 CopyMI = MRI->getVRegDef(SrcReg);
2344 deleteInstr(CopyMI);
2345 } else {
2346 // VReg is copied into physreg:
2347 // %y = def
2348 // ... //< no other def or use of %physreg_x here
2349 // %physreg_x = COPY %y
2350 // =>
2351 // %physreg_x = def
2352 // ...
2353 if (!MRI->hasOneNonDBGUse(SrcReg)) {
2354 LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
2355 return false;
2356 }
2357
2358 if (!LIS->intervalIsInOneMBB(RHS)) {
2359 LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
2360 return false;
2361 }
2362
2363 MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
2364 CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
2365 SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
2366 bool IsEarlyClobber =
2367 DestMI.findRegisterDefOperand(SrcReg, TRI)->isEarlyClobber();
2368 SlotIndex DestRegIdx =
2369 LIS->getInstructionIndex(DestMI).getRegSlot(IsEarlyClobber);
2370
2371 if (!MRI->isConstantPhysReg(DstReg)) {
2372 // We checked above that there are no interfering defs of the physical
2373 // register. However, for this case, where we intend to move up the def of
2374 // the physical register, we also need to check for interfering uses.
2375 for (MachineInstr &MI :
2376 make_range(std::next(DestMI.getIterator()), CopyMI->getIterator())) {
2377 if (MI.isDebugInstr())
2378 continue;
2379 if (MI.readsRegister(DstReg, TRI)) {
2380 LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << MI);
2381 return false;
2382 }
2383 }
2384 }
2385
2386 // We're going to remove the copy which defines a physical reserved
2387 // register, so remove its valno, etc.
2388 LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
2389 << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
2390
2391 LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
2392 deleteInstr(CopyMI);
2393
2394 // Create a new dead def at the new def location.
2395 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2396 LiveRange &LR = LIS->getRegUnit(Unit);
2397 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
2398 }
2399 }
2400
2401 return true;
2402}
2403
2404//===----------------------------------------------------------------------===//
2405// Interference checking and interval joining
2406//===----------------------------------------------------------------------===//
2407//
2408// In the easiest case, the two live ranges being joined are disjoint, and
2409// there is no interference to consider. It is quite common, though, to have
2410// overlapping live ranges, and we need to check if the interference can be
2411// resolved.
2412//
2413// The live range of a single SSA value forms a sub-tree of the dominator tree.
2414// This means that two SSA values overlap if and only if the def of one value
2415// is contained in the live range of the other value. As a special case, the
2416// overlapping values can be defined at the same index.
2417//
2418// The interference from an overlapping def can be resolved in these cases:
2419//
2420// 1. Coalescable copies. The value is defined by a copy that would become an
2421// identity copy after joining SrcReg and DstReg. The copy instruction will
2422// be removed, and the value will be merged with the source value.
2423//
2424// There can be several copies back and forth, causing many values to be
2425// merged into one. We compute a list of ultimate values in the joined live
2426// range as well as a mappings from the old value numbers.
2427//
2428// 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
2429// predecessors have a live out value. It doesn't cause real interference,
2430// and can be merged into the value it overlaps. Like a coalescable copy, it
2431// can be erased after joining.
2432//
2433// 3. Copy of external value. The overlapping def may be a copy of a value that
2434// is already in the other register. This is like a coalescable copy, but
2435// the live range of the source register must be trimmed after erasing the
2436// copy instruction:
2437//
2438// %src = COPY %ext
2439// %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
2440//
2441// 4. Clobbering undefined lanes. Vector registers are sometimes built by
2442// defining one lane at a time:
2443//
2444// %dst:ssub0<def,read-undef> = FOO
2445// %src = BAR
2446// %dst:ssub1 = COPY %src
2447//
2448// The live range of %src overlaps the %dst value defined by FOO, but
2449// merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
2450// which was undef anyway.
2451//
2452// The value mapping is more complicated in this case. The final live range
2453// will have different value numbers for both FOO and BAR, but there is no
2454// simple mapping from old to new values. It may even be necessary to add
2455// new PHI values.
2456//
2457// 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
2458// is live, but never read. This can happen because we don't compute
2459// individual live ranges per lane.
2460//
2461// %dst = FOO
2462// %src = BAR
2463// %dst:ssub1 = COPY %src
2464//
2465// This kind of interference is only resolved locally. If the clobbered
2466// lane value escapes the block, the join is aborted.
2467
2468namespace {
2469
2470/// Track information about values in a single virtual register about to be
2471/// joined. Objects of this class are always created in pairs - one for each
2472/// side of the CoalescerPair (or one for each lane of a side of the coalescer
2473/// pair)
2474class JoinVals {
2475 /// Live range we work on.
2476 LiveRange &LR;
2477
2478 /// (Main) register we work on.
2479 const Register Reg;
2480
2481 /// Reg (and therefore the values in this liverange) will end up as
2482 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
2483 /// CP.SrcIdx.
2484 const unsigned SubIdx;
2485
2486 /// The LaneMask that this liverange will occupy the coalesced register. May
2487 /// be smaller than the lanemask produced by SubIdx when merging subranges.
2488 const LaneBitmask LaneMask;
2489
2490 /// This is true when joining sub register ranges, false when joining main
2491 /// ranges.
2492 const bool SubRangeJoin;
2493
2494 /// Whether the current LiveInterval tracks subregister liveness.
2495 const bool TrackSubRegLiveness;
2496
2497 /// Values that will be present in the final live range.
2498 SmallVectorImpl<VNInfo *> &NewVNInfo;
2499
2500 const CoalescerPair &CP;
2501 LiveIntervals *LIS;
2502 SlotIndexes *Indexes;
2503 const TargetRegisterInfo *TRI;
2504
2505 /// Value number assignments. Maps value numbers in LI to entries in
2506 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
2507 SmallVector<int, 8> Assignments;
2508
2509public:
2510 /// Conflict resolution for overlapping values.
2511 enum ConflictResolution {
2512 /// No overlap, simply keep this value.
2513 CR_Keep,
2514
2515 /// Merge this value into OtherVNI and erase the defining instruction.
2516 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
2517 /// values.
2518 CR_Erase,
2519
2520 /// Merge this value into OtherVNI but keep the defining instruction.
2521 /// This is for the special case where OtherVNI is defined by the same
2522 /// instruction.
2523 CR_Merge,
2524
2525 /// Keep this value, and have it replace OtherVNI where possible. This
2526 /// complicates value mapping since OtherVNI maps to two different values
2527 /// before and after this def.
2528 /// Used when clobbering undefined or dead lanes.
2529 CR_Replace,
2530
2531 /// Unresolved conflict. Visit later when all values have been mapped.
2532 CR_Unresolved,
2533
2534 /// Unresolvable conflict. Abort the join.
2535 CR_Impossible
2536 };
2537
2538private:
2539 /// Per-value info for LI. The lane bit masks are all relative to the final
2540 /// joined register, so they can be compared directly between SrcReg and
2541 /// DstReg.
2542 struct Val {
2543 ConflictResolution Resolution = CR_Keep;
2544
2545 /// Lanes written by this def, 0 for unanalyzed values.
2546 LaneBitmask WriteLanes;
2547
2548 /// Lanes with defined values in this register. Other lanes are undef and
2549 /// safe to clobber.
2550 LaneBitmask ValidLanes;
2551
2552 /// Value in LI being redefined by this def.
2553 VNInfo *RedefVNI = nullptr;
2554
2555 /// Value in the other live range that overlaps this def, if any.
2556 VNInfo *OtherVNI = nullptr;
2557
2558 /// Is this value an IMPLICIT_DEF that can be erased?
2559 ///
2560 /// IMPLICIT_DEF values should only exist at the end of a basic block that
2561 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
2562 /// safely erased if they are overlapping a live value in the other live
2563 /// interval.
2564 ///
2565 /// Weird control flow graphs and incomplete PHI handling in
2566 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
2567 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
2568 /// normal values.
2569 bool ErasableImplicitDef = false;
2570
2571 /// True when the live range of this value will be pruned because of an
2572 /// overlapping CR_Replace value in the other live range.
2573 bool Pruned = false;
2574
2575 /// True once Pruned above has been computed.
2576 bool PrunedComputed = false;
2577
2578 /// True if this value is determined to be identical to OtherVNI
2579 /// (in valuesIdentical). This is used with CR_Erase where the erased
2580 /// copy is redundant, i.e. the source value is already the same as
2581 /// the destination. In such cases the subranges need to be updated
2582 /// properly. See comment at pruneSubRegValues for more info.
2583 bool Identical = false;
2584
2585 Val() = default;
2586
2587 bool isAnalyzed() const { return WriteLanes.any(); }
2588
2589 /// Mark this value as an IMPLICIT_DEF which must be kept as if it were an
2590 /// ordinary value.
2591 void mustKeepImplicitDef(const TargetRegisterInfo &TRI,
2592 const MachineInstr &ImpDef) {
2593 assert(ImpDef.isImplicitDef());
2594 ErasableImplicitDef = false;
2595 ValidLanes |=
2596 TRI.getSubRegIndexLaneMask(ImpDef.getOperand(0).getSubReg());
2597 }
2598 };
2599
2600 /// One entry per value number in LI.
2602
2603 /// Compute the bitmask of lanes actually written by DefMI.
2604 /// Set Redef if there are any partial register definitions that depend on the
2605 /// previous value of the register.
2606 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2607
2608 /// Find the ultimate value that VNI was copied from.
2609 std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
2610
2611 bool valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2612 const JoinVals &Other) const;
2613
2614 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2615 /// Return a conflict resolution when possible, but leave the hard cases as
2616 /// CR_Unresolved.
2617 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2618 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2619 /// The recursion always goes upwards in the dominator tree, making loops
2620 /// impossible.
2621 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2622
2623 /// Compute the value assignment for ValNo in RI.
2624 /// This may be called recursively by analyzeValue(), but never for a ValNo on
2625 /// the stack.
2626 void computeAssignment(unsigned ValNo, JoinVals &Other);
2627
2628 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2629 /// the extent of the tainted lanes in the block.
2630 ///
2631 /// Multiple values in Other.LR can be affected since partial redefinitions
2632 /// can preserve previously tainted lanes.
2633 ///
2634 /// 1 %dst = VLOAD <-- Define all lanes in %dst
2635 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
2636 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
2637 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2638 ///
2639 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2640 /// entry to TaintedVals.
2641 ///
2642 /// Returns false if the tainted lanes extend beyond the basic block.
2643 bool
2644 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2645 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
2646
2647 /// Return true if MI uses any of the given Lanes from Reg.
2648 /// This does not include partial redefinitions of Reg.
2649 bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
2650
2651 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2652 /// be pruned:
2653 ///
2654 /// %dst = COPY %src
2655 /// %src = COPY %dst <-- This value to be pruned.
2656 /// %dst = COPY %src <-- This value is a copy of a pruned value.
2657 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2658
2659public:
2660 JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
2661 SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
2662 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2663 bool TrackSubRegLiveness)
2664 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2665 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2666 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2667 TRI(TRI), Assignments(LR.getNumValNums(), -1),
2668 Vals(LR.getNumValNums()) {}
2669
2670 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2671 /// Returns false if any conflicts were impossible to resolve.
2672 bool mapValues(JoinVals &Other);
2673
2674 /// Try to resolve conflicts that require all values to be mapped.
2675 /// Returns false if any conflicts were impossible to resolve.
2676 bool resolveConflicts(JoinVals &Other);
2677
2678 /// Prune the live range of values in Other.LR where they would conflict with
2679 /// CR_Replace values in LR. Collect end points for restoring the live range
2680 /// after joining.
2681 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2682 bool changeInstrs);
2683
2684 /// Removes subranges starting at copies that get removed. This sometimes
2685 /// happens when undefined subranges are copied around. These ranges contain
2686 /// no useful information and can be removed.
2687 void pruneSubRegValues(
2688 LiveInterval &LI, LaneBitmask &ShrinkMask,
2689 SmallVectorImpl<std::pair<LaneBitmask, SlotIndex>> &PHIKills);
2690
2691 /// Pruning values in subranges can lead to removing segments in these
2692 /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2693 /// the main range also need to be removed. This function will mark
2694 /// the corresponding values in the main range as pruned, so that
2695 /// eraseInstrs can do the final cleanup.
2696 /// The parameter @p LI must be the interval whose main range is the
2697 /// live range LR.
2698 void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2699
2700 /// Erase any machine instructions that have been coalesced away.
2701 /// Add erased instructions to ErasedInstrs.
2702 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2703 /// the erased instrs.
2704 void eraseInstrs(SmallPtrSetImpl<MachineInstr *> &ErasedInstrs,
2705 SmallVectorImpl<Register> &ShrinkRegs,
2706 LiveInterval *LI = nullptr);
2707
2708 /// Remove liverange defs at places where implicit defs will be removed.
2709 void removeImplicitDefs();
2710
2711 /// Get the value assignments suitable for passing to LiveInterval::join.
2712 const int *getAssignments() const { return Assignments.data(); }
2713
2714 /// Get the conflict resolution for a value number.
2715 ConflictResolution getResolution(unsigned Num) const {
2716 return Vals[Num].Resolution;
2717 }
2718};
2719
2720} // end anonymous namespace
2721
2722LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI,
2723 bool &Redef) const {
2724 LaneBitmask L;
2725 for (const MachineOperand &MO : DefMI->all_defs()) {
2726 if (MO.getReg() != Reg)
2727 continue;
2728 L |= TRI->getSubRegIndexLaneMask(
2729 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2730 if (MO.readsReg())
2731 Redef = true;
2732 }
2733 return L;
2734}
2735
2736std::pair<const VNInfo *, Register>
2737JoinVals::followCopyChain(const VNInfo *VNI) const {
2738 Register TrackReg = Reg;
2739
2740 while (!VNI->isPHIDef()) {
2741 SlotIndex Def = VNI->def;
2742 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2743 assert(MI && "No defining instruction");
2744 if (!MI->isFullCopy())
2745 return std::make_pair(VNI, TrackReg);
2746 Register SrcReg = MI->getOperand(1).getReg();
2747 if (!SrcReg.isVirtual())
2748 return std::make_pair(VNI, TrackReg);
2749
2750 const LiveInterval &LI = LIS->getInterval(SrcReg);
2751 const VNInfo *ValueIn;
2752 // No subrange involved.
2753 if (!SubRangeJoin || !LI.hasSubRanges()) {
2754 LiveQueryResult LRQ = LI.Query(Def);
2755 ValueIn = LRQ.valueIn();
2756 } else {
2757 // Query subranges. Ensure that all matching ones take us to the same def
2758 // (allowing some of them to be undef).
2759 ValueIn = nullptr;
2760 for (const LiveInterval::SubRange &S : LI.subranges()) {
2761 // Transform lanemask to a mask in the joined live interval.
2762 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2763 if ((SMask & LaneMask).none())
2764 continue;
2765 LiveQueryResult LRQ = S.Query(Def);
2766 if (!ValueIn) {
2767 ValueIn = LRQ.valueIn();
2768 continue;
2769 }
2770 if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
2771 return std::make_pair(VNI, TrackReg);
2772 }
2773 }
2774 if (ValueIn == nullptr) {
2775 // Reaching an undefined value is legitimate, for example:
2776 //
2777 // 1 undef %0.sub1 = ... ;; %0.sub0 == undef
2778 // 2 %1 = COPY %0 ;; %1 is defined here.
2779 // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
2780 // ;; but it's equivalent to "undef".
2781 return std::make_pair(nullptr, SrcReg);
2782 }
2783 VNI = ValueIn;
2784 TrackReg = SrcReg;
2785 }
2786 return std::make_pair(VNI, TrackReg);
2787}
2788
2789bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2790 const JoinVals &Other) const {
2791 const VNInfo *Orig0;
2792 Register Reg0;
2793 std::tie(Orig0, Reg0) = followCopyChain(Value0);
2794 if (Orig0 == Value1 && Reg0 == Other.Reg)
2795 return true;
2796
2797 const VNInfo *Orig1;
2798 Register Reg1;
2799 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2800 // If both values are undefined, and the source registers are the same
2801 // register, the values are identical. Filter out cases where only one
2802 // value is defined.
2803 if (Orig0 == nullptr || Orig1 == nullptr)
2804 return Orig0 == Orig1 && Reg0 == Reg1;
2805
2806 // The values are equal if they are defined at the same place and use the
2807 // same register. Note that we cannot compare VNInfos directly as some of
2808 // them might be from a copy created in mergeSubRangeInto() while the other
2809 // is from the original LiveInterval.
2810 return Orig0->def == Orig1->def && Reg0 == Reg1;
2811}
2812
2813JoinVals::ConflictResolution JoinVals::analyzeValue(unsigned ValNo,
2814 JoinVals &Other) {
2815 Val &V = Vals[ValNo];
2816 assert(!V.isAnalyzed() && "Value has already been analyzed!");
2817 VNInfo *VNI = LR.getValNumInfo(ValNo);
2818 if (VNI->isUnused()) {
2819 V.WriteLanes = LaneBitmask::getAll();
2820 return CR_Keep;
2821 }
2822
2823 // Get the instruction defining this value, compute the lanes written.
2824 const MachineInstr *DefMI = nullptr;
2825 if (VNI->isPHIDef()) {
2826 // Conservatively assume that all lanes in a PHI are valid.
2827 LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
2828 : TRI->getSubRegIndexLaneMask(SubIdx);
2829 V.ValidLanes = V.WriteLanes = Lanes;
2830 } else {
2831 DefMI = Indexes->getInstructionFromIndex(VNI->def);
2832 assert(DefMI != nullptr);
2833 if (SubRangeJoin) {
2834 // We don't care about the lanes when joining subregister ranges.
2835 V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
2836 if (DefMI->isImplicitDef()) {
2837 V.ValidLanes = LaneBitmask::getNone();
2838 V.ErasableImplicitDef = true;
2839 }
2840 } else {
2841 bool Redef = false;
2842 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2843
2844 // If this is a read-modify-write instruction, there may be more valid
2845 // lanes than the ones written by this instruction.
2846 // This only covers partial redef operands. DefMI may have normal use
2847 // operands reading the register. They don't contribute valid lanes.
2848 //
2849 // This adds ssub1 to the set of valid lanes in %src:
2850 //
2851 // %src:ssub1 = FOO
2852 //
2853 // This leaves only ssub1 valid, making any other lanes undef:
2854 //
2855 // %src:ssub1<def,read-undef> = FOO %src:ssub2
2856 //
2857 // The <read-undef> flag on the def operand means that old lane values are
2858 // not important.
2859 if (Redef) {
2860 V.RedefVNI = LR.Query(VNI->def).valueIn();
2861 assert((TrackSubRegLiveness || V.RedefVNI) &&
2862 "Instruction is reading nonexistent value");
2863 if (V.RedefVNI != nullptr) {
2864 computeAssignment(V.RedefVNI->id, Other);
2865 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2866 }
2867 }
2868
2869 // An IMPLICIT_DEF writes undef values.
2870 if (DefMI->isImplicitDef()) {
2871 // We normally expect IMPLICIT_DEF values to be live only until the end
2872 // of their block. If the value is really live longer and gets pruned in
2873 // another block, this flag is cleared again.
2874 //
2875 // Clearing the valid lanes is deferred until it is sure this can be
2876 // erased.
2877 V.ErasableImplicitDef = true;
2878 }
2879 }
2880 }
2881
2882 // Find the value in Other that overlaps VNI->def, if any.
2883 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2884
2885 // It is possible that both values are defined by the same instruction, or
2886 // the values are PHIs defined in the same block. When that happens, the two
2887 // values should be merged into one, but not into any preceding value.
2888 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2889 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2890 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
2891
2892 // One value stays, the other is merged. Keep the earlier one, or the first
2893 // one we see.
2894 if (OtherVNI->def < VNI->def)
2895 Other.computeAssignment(OtherVNI->id, *this);
2896 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2897 // This is an early-clobber def overlapping a live-in value in the other
2898 // register. Not mergeable.
2899 V.OtherVNI = OtherLRQ.valueIn();
2900 return CR_Impossible;
2901 }
2902 V.OtherVNI = OtherVNI;
2903 Val &OtherV = Other.Vals[OtherVNI->id];
2904 // Keep this value, check for conflicts when analyzing OtherVNI. Avoid
2905 // revisiting OtherVNI->id in JoinVals::computeAssignment() below before it
2906 // is assigned.
2907 if (!OtherV.isAnalyzed() || Other.Assignments[OtherVNI->id] == -1)
2908 return CR_Keep;
2909 // Both sides have been analyzed now.
2910 // Allow overlapping PHI values. Any real interference would show up in a
2911 // predecessor, the PHI itself can't introduce any conflicts.
2912 if (VNI->isPHIDef())
2913 return CR_Merge;
2914 if ((V.ValidLanes & OtherV.ValidLanes).any())
2915 // Overlapping lanes can't be resolved.
2916 return CR_Impossible;
2917 return CR_Merge;
2918 }
2919
2920 // No simultaneous def. Is Other live at the def?
2921 V.OtherVNI = OtherLRQ.valueIn();
2922 if (!V.OtherVNI)
2923 // No overlap, no conflict.
2924 return CR_Keep;
2925
2926 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2927
2928 // We have overlapping values, or possibly a kill of Other.
2929 // Recursively compute assignments up the dominator tree.
2930 Other.computeAssignment(V.OtherVNI->id, *this);
2931 Val &OtherV = Other.Vals[V.OtherVNI->id];
2932
2933 if (OtherV.ErasableImplicitDef) {
2934 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2935 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2936 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2937 // technically.
2938 //
2939 // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2940 // to erase the IMPLICIT_DEF instruction.
2941 //
2942 // Additionally we must keep an IMPLICIT_DEF if we're redefining an incoming
2943 // value.
2944
2945 MachineInstr *OtherImpDef =
2946 Indexes->getInstructionFromIndex(V.OtherVNI->def);
2947 MachineBasicBlock *OtherMBB = OtherImpDef->getParent();
2948 if (DefMI &&
2949 (DefMI->getParent() != OtherMBB || LIS->isLiveInToMBB(LR, OtherMBB))) {
2950 LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2951 << " extends into "
2953 << ", keeping it.\n");
2954 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2955 } else if (OtherMBB->hasEHPadSuccessor()) {
2956 // If OtherV is defined in a basic block that has EH pad successors then
2957 // we get the same problem not just if OtherV is live beyond its basic
2958 // block, but beyond the last call instruction in its basic block. Handle
2959 // this case conservatively.
2960 LLVM_DEBUG(
2961 dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2962 << " may be live into EH pad successors, keeping it.\n");
2963 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2964 } else {
2965 // We deferred clearing these lanes in case we needed to save them
2966 OtherV.ValidLanes &= ~OtherV.WriteLanes;
2967 }
2968 }
2969
2970 // Allow overlapping PHI values. Any real interference would show up in a
2971 // predecessor, the PHI itself can't introduce any conflicts.
2972 if (VNI->isPHIDef())
2973 return CR_Replace;
2974
2975 // Check for simple erasable conflicts.
2976 if (DefMI->isImplicitDef())
2977 return CR_Erase;
2978
2979 // Include the non-conflict where DefMI is a coalescable copy that kills
2980 // OtherVNI. We still want the copy erased and value numbers merged.
2981 if (CP.isCoalescable(DefMI)) {
2982 // Some of the lanes copied from OtherVNI may be undef, making them undef
2983 // here too.
2984 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2985 return CR_Erase;
2986 }
2987
2988 // This may not be a real conflict if DefMI simply kills Other and defines
2989 // VNI.
2990 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2991 return CR_Keep;
2992
2993 // Handle the case where VNI and OtherVNI can be proven to be identical:
2994 //
2995 // %other = COPY %ext
2996 // %this = COPY %ext <-- Erase this copy
2997 //
2998 if (DefMI->isFullCopy() && !CP.isPartial() &&
2999 valuesIdentical(VNI, V.OtherVNI, Other)) {
3000 V.Identical = true;
3001 return CR_Erase;
3002 }
3003
3004 // The remaining checks apply to the lanes, which aren't tracked here. This
3005 // was already decided to be OK via the following CR_Replace condition.
3006 // CR_Replace.
3007 if (SubRangeJoin)
3008 return CR_Replace;
3009
3010 // If the lanes written by this instruction were all undef in OtherVNI, it is
3011 // still safe to join the live ranges. This can't be done with a simple value
3012 // mapping, though - OtherVNI will map to multiple values:
3013 //
3014 // 1 %dst:ssub0 = FOO <-- OtherVNI
3015 // 2 %src = BAR <-- VNI
3016 // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
3017 // 4 BAZ killed %dst
3018 // 5 QUUX killed %src
3019 //
3020 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
3021 // handles this complex value mapping.
3022 if ((V.WriteLanes & OtherV.ValidLanes).none())
3023 return CR_Replace;
3024
3025 // If the other live range is killed by DefMI and the live ranges are still
3026 // overlapping, it must be because we're looking at an early clobber def:
3027 //
3028 // %dst<def,early-clobber> = ASM killed %src
3029 //
3030 // In this case, it is illegal to merge the two live ranges since the early
3031 // clobber def would clobber %src before it was read.
3032 if (OtherLRQ.isKill()) {
3033 // This case where the def doesn't overlap the kill is handled above.
3034 assert(VNI->def.isEarlyClobber() &&
3035 "Only early clobber defs can overlap a kill");
3036 return CR_Impossible;
3037 }
3038
3039 // VNI is clobbering live lanes in OtherVNI, but there is still the
3040 // possibility that no instructions actually read the clobbered lanes.
3041 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
3042 // Otherwise Other.RI wouldn't be live here.
3043 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
3044 return CR_Impossible;
3045
3046 if (TrackSubRegLiveness) {
3047 auto &OtherLI = LIS->getInterval(Other.Reg);
3048 // If OtherVNI does not have subranges, it means all the lanes of OtherVNI
3049 // share the same live range, so we just need to check whether they have
3050 // any conflict bit in their LaneMask.
3051 if (!OtherLI.hasSubRanges()) {
3052 LaneBitmask OtherMask = TRI->getSubRegIndexLaneMask(Other.SubIdx);
3053 return (OtherMask & V.WriteLanes).none() ? CR_Replace : CR_Impossible;
3054 }
3055
3056 // If we are clobbering some active lanes of OtherVNI at VNI->def, it is
3057 // impossible to resolve the conflict. Otherwise, we can just replace
3058 // OtherVNI because of no real conflict.
3059 for (LiveInterval::SubRange &OtherSR : OtherLI.subranges()) {
3060 LaneBitmask OtherMask =
3061 TRI->composeSubRegIndexLaneMask(Other.SubIdx, OtherSR.LaneMask);
3062 if ((OtherMask & V.WriteLanes).none())
3063 continue;
3064
3065 auto OtherSRQ = OtherSR.Query(VNI->def);
3066 if (OtherSRQ.valueIn() && OtherSRQ.endPoint() > VNI->def) {
3067 // VNI is clobbering some lanes of OtherVNI, they have real conflict.
3068 return CR_Impossible;
3069 }
3070 }
3071
3072 // VNI is NOT clobbering any lane of OtherVNI, just replace OtherVNI.
3073 return CR_Replace;
3074 }
3075
3076 // We need to verify that no instructions are reading the clobbered lanes.
3077 // To save compile time, we'll only check that locally. Don't allow the
3078 // tainted value to escape the basic block.
3079 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3080 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
3081 return CR_Impossible;
3082
3083 // There are still some things that could go wrong besides clobbered lanes
3084 // being read, for example OtherVNI may be only partially redefined in MBB,
3085 // and some clobbered lanes could escape the block. Save this analysis for
3086 // resolveConflicts() when all values have been mapped. We need to know
3087 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
3088 // that now - the recursive analyzeValue() calls must go upwards in the
3089 // dominator tree.
3090 return CR_Unresolved;
3091}
3092
3093void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
3094 Val &V = Vals[ValNo];
3095 if (V.isAnalyzed()) {
3096 // Recursion should always move up the dominator tree, so ValNo is not
3097 // supposed to reappear before it has been assigned.
3098 assert(Assignments[ValNo] != -1 && "Bad recursion?");
3099 return;
3100 }
3101 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
3102 case CR_Erase:
3103 case CR_Merge:
3104 // Merge this ValNo into OtherVNI.
3105 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
3106 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
3107 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
3108 LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
3109 << LR.getValNumInfo(ValNo)->def << " into "
3110 << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
3111 << V.OtherVNI->def << " --> @"
3112 << NewVNInfo[Assignments[ValNo]]->def << '\n');
3113 break;
3114 case CR_Replace:
3115 case CR_Unresolved: {
3116 // The other value is going to be pruned if this join is successful.
3117 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
3118 Val &OtherV = Other.Vals[V.OtherVNI->id];
3119 OtherV.Pruned = true;
3120 [[fallthrough]];
3121 }
3122 default:
3123 // This value number needs to go in the final joined live range.
3124 Assignments[ValNo] = NewVNInfo.size();
3125 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
3126 break;
3127 }
3128}
3129
3130bool JoinVals::mapValues(JoinVals &Other) {
3131 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3132 computeAssignment(i, Other);
3133 if (Vals[i].Resolution == CR_Impossible) {
3134 LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
3135 << '@' << LR.getValNumInfo(i)->def << '\n');
3136 return false;
3137 }
3138 }
3139 return true;
3140}
3141
3142bool JoinVals::taintExtent(
3143 unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
3144 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
3145 VNInfo *VNI = LR.getValNumInfo(ValNo);
3146 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3147 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
3148
3149 // Scan Other.LR from VNI.def to MBBEnd.
3150 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
3151 assert(OtherI != Other.LR.end() && "No conflict?");
3152 do {
3153 // OtherI is pointing to a tainted value. Abort the join if the tainted
3154 // lanes escape the block.
3155 SlotIndex End = OtherI->end;
3156 if (End >= MBBEnd) {
3157 LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
3158 << OtherI->valno->id << '@' << OtherI->start << '\n');
3159 return false;
3160 }
3161 LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
3162 << OtherI->valno->id << '@' << OtherI->start << " to "
3163 << End << '\n');
3164 // A dead def is not a problem.
3165 if (End.isDead())
3166 break;
3167 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
3168
3169 // Check for another def in the MBB.
3170 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
3171 break;
3172
3173 // Lanes written by the new def are no longer tainted.
3174 const Val &OV = Other.Vals[OtherI->valno->id];
3175 TaintedLanes &= ~OV.WriteLanes;
3176 if (!OV.RedefVNI)
3177 break;
3178 } while (TaintedLanes.any());
3179 return true;
3180}
3181
3182bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
3183 LaneBitmask Lanes) const {
3184 if (MI.isDebugOrPseudoInstr())
3185 return false;
3186 for (const MachineOperand &MO : MI.all_uses()) {
3187 if (MO.getReg() != Reg)
3188 continue;
3189 if (!MO.readsReg())
3190 continue;
3191 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
3192 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
3193 return true;
3194 }
3195 return false;
3196}
3197
3198bool JoinVals::resolveConflicts(JoinVals &Other) {
3199 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3200 Val &V = Vals[i];
3201 assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
3202 if (V.Resolution != CR_Unresolved)
3203 continue;
3204 LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
3205 << LR.getValNumInfo(i)->def << ' '
3206 << PrintLaneMask(LaneMask) << '\n');
3207 if (SubRangeJoin)
3208 return false;
3209
3210 ++NumLaneConflicts;
3211 assert(V.OtherVNI && "Inconsistent conflict resolution.");
3212 VNInfo *VNI = LR.getValNumInfo(i);
3213 const Val &OtherV = Other.Vals[V.OtherVNI->id];
3214
3215 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
3216 // join, those lanes will be tainted with a wrong value. Get the extent of
3217 // the tainted lanes.
3218 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
3220 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
3221 // Tainted lanes would extend beyond the basic block.
3222 return false;
3223
3224 assert(!TaintExtent.empty() && "There should be at least one conflict.");
3225
3226 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
3227 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3229 if (!VNI->isPHIDef()) {
3230 MI = Indexes->getInstructionFromIndex(VNI->def);
3231 if (!VNI->def.isEarlyClobber()) {
3232 // No need to check the instruction defining VNI for reads.
3233 ++MI;
3234 }
3235 }
3236 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
3237 "Interference ends on VNI->def. Should have been handled earlier");
3238 MachineInstr *LastMI =
3239 Indexes->getInstructionFromIndex(TaintExtent.front().first);
3240 assert(LastMI && "Range must end at a proper instruction");
3241 unsigned TaintNum = 0;
3242 while (true) {
3243 assert(MI != MBB->end() && "Bad LastMI");
3244 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
3245 LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
3246 return false;
3247 }
3248 // LastMI is the last instruction to use the current value.
3249 if (&*MI == LastMI) {
3250 if (++TaintNum == TaintExtent.size())
3251 break;
3252 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
3253 assert(LastMI && "Range must end at a proper instruction");
3254 TaintedLanes = TaintExtent[TaintNum].second;
3255 }
3256 ++MI;
3257 }
3258
3259 // The tainted lanes are unused.
3260 V.Resolution = CR_Replace;
3261 ++NumLaneResolves;
3262 }
3263 return true;
3264}
3265
3266bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
3267 Val &V = Vals[ValNo];
3268 if (V.Pruned || V.PrunedComputed)
3269 return V.Pruned;
3270
3271 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
3272 return V.Pruned;
3273
3274 // Follow copies up the dominator tree and check if any intermediate value
3275 // has been pruned.
3276 V.PrunedComputed = true;
3277 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
3278 return V.Pruned;
3279}
3280
3281void JoinVals::pruneValues(JoinVals &Other,
3282 SmallVectorImpl<SlotIndex> &EndPoints,
3283 bool changeInstrs) {
3284 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3285 SlotIndex Def = LR.getValNumInfo(i)->def;
3286 switch (Vals[i].Resolution) {
3287 case CR_Keep:
3288 break;
3289 case CR_Replace: {
3290 // This value takes precedence over the value in Other.LR.
3291 LIS->pruneValue(Other.LR, Def, &EndPoints);
3292 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
3293 // instructions are only inserted to provide a live-out value for PHI
3294 // predecessors, so the instruction should simply go away once its value
3295 // has been replaced. If it still carries defined lanes, this def must
3296 // preserve them.
3297 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3298 bool EraseImpDef = OtherV.ErasableImplicitDef &&
3299 OtherV.Resolution == CR_Keep &&
3300 OtherV.ValidLanes.none();
3301 if (!Def.isBlock()) {
3302 if (changeInstrs) {
3303 // Remove <def,read-undef> flags. This def is now a partial redef.
3304 // Also remove dead flags since the joined live range will
3305 // continue past this instruction.
3306 for (MachineOperand &MO :
3307 mi_bundle_ops(*Indexes->getInstructionFromIndex(Def))) {
3308 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
3309 if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
3310 MO.setIsUndef(false);
3311 MO.setIsDead(false);
3312 }
3313 }
3314 }
3315 // This value will reach instructions below, but we need to make sure
3316 // the live range also reaches the instruction at Def.
3317 if (!EraseImpDef)
3318 EndPoints.push_back(Def);
3319 }
3320 LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
3321 << ": " << Other.LR << '\n');
3322 break;
3323 }
3324 case CR_Erase:
3325 case CR_Merge:
3326 if (isPrunedValue(i, Other)) {
3327 // This value is ultimately a copy of a pruned value in LR or Other.LR.
3328 // We can no longer trust the value mapping computed by
3329 // computeAssignment(), the value that was originally copied could have
3330 // been replaced.
3331 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3332 // If the source is an erasable IMPLICIT_DEF without any defined lanes,
3333 // the pruned endpoints only read undefined values, so discard them. A
3334 // partial IMPLICIT_DEF without <read-undef> still carries the lanes of
3335 // the value it redefines (its ValidLanes). Without lane information we
3336 // cannot tell which endpoints read those lanes, so keep all of them and
3337 // restore the live range.
3338 bool EraseImpDef = OtherV.ErasableImplicitDef &&
3339 OtherV.Resolution == CR_Keep &&
3340 OtherV.ValidLanes.none();
3341 LIS->pruneValue(LR, Def, EraseImpDef ? nullptr : &EndPoints);
3342 LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
3343 << Def << ": " << LR << '\n');
3344 }
3345 break;
3346 case CR_Unresolved:
3347 case CR_Impossible:
3348 llvm_unreachable("Unresolved conflicts");
3349 }
3350 }
3351}
3352
3353/// Collect the ends of the predecessors where \p VNI is live-out into a PHI
3354/// value of \p LR. Mirrors LiveIntervals::hasPHIKill.
3355static void collectPHIKills(const LiveRange &LR, const VNInfo *VNI,
3356 const SlotIndexes &Indexes,
3357 SmallVectorImpl<SlotIndex> &PHIKills) {
3358 for (const VNInfo *PHI : LR.valnos) {
3359 if (PHI->isUnused() || !PHI->isPHIDef())
3360 continue;
3361 const MachineBasicBlock *PHIMBB = Indexes.getMBBFromIndex(PHI->def);
3362 for (const MachineBasicBlock *Pred : PHIMBB->predecessors()) {
3363 SlotIndex End = Indexes.getMBBEndIdx(Pred);
3364 if (LR.getVNInfoBefore(End) == VNI)
3365 PHIKills.push_back(End);
3366 }
3367 }
3368}
3369
3370// Check if the segment consists of a copied live-through value (i.e. the copy
3371// in the block only extended the liveness, of an undef value which we may need
3372// to handle).
3373static bool isLiveThrough(const LiveQueryResult Q) {
3374 return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
3375}
3376
3377/// Consider the following situation when coalescing the copy between
3378/// %31 and %45 at 800. (The vertical lines represent live range segments.)
3379///
3380/// Main range Subrange 0004 (sub2)
3381/// %31 %45 %31 %45
3382/// 544 %45 = COPY %28 + +
3383/// | v1 | v1
3384/// 560B bb.1: + +
3385/// 624 = %45.sub2 | v2 | v2
3386/// 800 %31 = COPY %45 + + + +
3387/// | v0 | v0
3388/// 816 %31.sub1 = ... + |
3389/// 880 %30 = COPY %31 | v1 +
3390/// 928 %45 = COPY %30 | + +
3391/// | | v0 | v0 <--+
3392/// 992B ; backedge -> bb.1 | + + |
3393/// 1040 = %31.sub0 + |
3394/// This value must remain
3395/// live-out!
3396///
3397/// Assuming that %31 is coalesced into %45, the copy at 928 becomes
3398/// redundant, since it copies the value from %45 back into it. The
3399/// conflict resolution for the main range determines that %45.v0 is
3400/// to be erased, which is ok since %31.v1 is identical to it.
3401/// The problem happens with the subrange for sub2: it has to be live
3402/// on exit from the block, but since 928 was actually a point of
3403/// definition of %45.sub2, %45.sub2 was not live immediately prior
3404/// to that definition. As a result, when 928 was erased, the value v0
3405/// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
3406/// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
3407/// providing an incorrect value to the use at 624.
3408///
3409/// Since the main-range values %31.v1 and %45.v0 were proved to be
3410/// identical, the corresponding values in subranges must also be the
3411/// same. A redundant copy is removed because it's not needed, and not
3412/// because it copied an undefined value, so any liveness that originated
3413/// from that copy cannot disappear. When pruning a value that started
3414/// at the removed copy, the corresponding identical value must be
3415/// extended to replace it.
3416void JoinVals::pruneSubRegValues(
3417 LiveInterval &LI, LaneBitmask &ShrinkMask,
3418 SmallVectorImpl<std::pair<LaneBitmask, SlotIndex>> &PHIKills) {
3419 // Look for values being erased.
3420 bool DidPrune = false;
3421 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3422 Val &V = Vals[i];
3423 // We should trigger in all cases in which eraseInstrs() does something.
3424 // match what eraseInstrs() is doing, print a message so
3425 if (V.Resolution != CR_Erase &&
3426 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
3427 continue;
3428
3429 // Check subranges at the point where the copy will be removed.
3430 SlotIndex Def = LR.getValNumInfo(i)->def;
3431 SlotIndex OtherDef;
3432 if (V.Identical)
3433 OtherDef = V.OtherVNI->def;
3434
3435 // Print message so mismatches with eraseInstrs() can be diagnosed.
3436 LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
3437 << '\n');
3438 for (LiveInterval::SubRange &S : LI.subranges()) {
3439 LiveQueryResult Q = S.Query(Def);
3440
3441 // If a subrange starts at the copy then an undefined value has been
3442 // copied and we must remove that subrange value as well.
3443 VNInfo *ValueOut = Q.valueOutOrDead();
3444 if (ValueOut != nullptr &&
3445 (Q.valueIn() == nullptr ||
3446 (V.Identical && V.Resolution == CR_Erase && ValueOut->def == Def))) {
3447 LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
3448 << " at " << Def << "\n");
3449 SmallVector<SlotIndex, 8> ValuePHIKills;
3450 collectPHIKills(S, ValueOut, *Indexes, ValuePHIKills);
3451 SmallVector<SlotIndex, 8> EndPoints;
3452 LIS->pruneValue(S, Def, &EndPoints);
3453 DidPrune = true;
3454 // Mark value number as unused.
3455 if (ValueOut->def == Def)
3456 ValueOut->markUnused();
3457
3458 if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
3459 // If V is identical to V.OtherVNI (and S was live at OtherDef),
3460 // then we can't simply prune V from S. V needs to be replaced
3461 // with V.OtherVNI.
3462 LIS->extendToIndices(S, EndPoints);
3463 } else {
3464 for (SlotIndex Kill : ValuePHIKills)
3465 PHIKills.emplace_back(S.LaneMask, Kill);
3466 }
3467
3468 // We may need to eliminate the subrange if the copy introduced a live
3469 // out undef value.
3470 if (ValueOut->isPHIDef())
3471 ShrinkMask |= S.LaneMask;
3472 continue;
3473 }
3474
3475 // If a subrange ends at the copy, then a value was copied but only
3476 // partially used later. Shrink the subregister range appropriately.
3477 //
3478 // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
3479 // conservatively correct.
3480 if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
3481 (V.Resolution == CR_Erase && isLiveThrough(Q))) {
3482 LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
3483 << PrintLaneMask(S.LaneMask) << " at " << Def
3484 << "\n");
3485 ShrinkMask |= S.LaneMask;
3486 }
3487 }
3488 }
3489 if (DidPrune)
3491}
3492
3493/// Check if any of the subranges of @p LI contain a definition at @p Def.
3495 for (LiveInterval::SubRange &SR : LI.subranges()) {
3496 if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
3497 if (VNI->def == Def)
3498 return true;
3499 }
3500 return false;
3501}
3502
3503void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
3504 assert(&static_cast<LiveRange &>(LI) == &LR);
3505
3506 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3507 if (Vals[i].Resolution != CR_Keep)
3508 continue;
3509 VNInfo *VNI = LR.getValNumInfo(i);
3510 if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
3511 continue;
3512 Vals[i].Pruned = true;
3513 ShrinkMainRange = true;
3514 }
3515}
3516
3517void JoinVals::removeImplicitDefs() {
3518 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3519 Val &V = Vals[i];
3520 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
3521 continue;
3522
3523 VNInfo *VNI = LR.getValNumInfo(i);
3524 VNI->markUnused();
3525 LR.removeValNo(VNI);
3526 }
3527}
3528
3529void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr *> &ErasedInstrs,
3530 SmallVectorImpl<Register> &ShrinkRegs,
3531 LiveInterval *LI) {
3532 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3533 // Get the def location before markUnused() below invalidates it.
3534 VNInfo *VNI = LR.getValNumInfo(i);
3535 SlotIndex Def = VNI->def;
3536 switch (Vals[i].Resolution) {
3537 case CR_Keep: {
3538 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
3539 // longer. The IMPLICIT_DEF instructions are only inserted by
3540 // PHIElimination to guarantee that all PHI predecessors have a value.
3541 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
3542 break;
3543 // Remove value number i from LR.
3544 // For intervals with subranges, removing a segment from the main range
3545 // may require extending the previous segment: for each definition of
3546 // a subregister, there will be a corresponding def in the main range.
3547 // That def may fall in the middle of a segment from another subrange.
3548 // In such cases, removing this def from the main range must be
3549 // complemented by extending the main range to account for the liveness
3550 // of the other subrange.
3551 // The new end point of the main range segment to be extended.
3552 SlotIndex NewEnd;
3553 if (LI != nullptr) {
3555 assert(I != LR.end());
3556 // Do not extend beyond the end of the segment being removed.
3557 // The segment may have been pruned in preparation for joining
3558 // live ranges.
3559 NewEnd = I->end;
3560 }
3561
3562 LR.removeValNo(VNI);
3563 // Note that this VNInfo is reused and still referenced in NewVNInfo,
3564 // make it appear like an unused value number.
3565 VNI->markUnused();
3566
3567 if (LI != nullptr && LI->hasSubRanges()) {
3568 assert(static_cast<LiveRange *>(LI) == &LR);
3569 // Determine the end point based on the subrange information:
3570 // minimum of (earliest def of next segment,
3571 // latest end point of containing segment)
3572 SlotIndex ED, LE;
3573 for (LiveInterval::SubRange &SR : LI->subranges()) {
3574 LiveRange::iterator I = SR.find(Def);
3575 if (I == SR.end())
3576 continue;
3577 if (I->start > Def)
3578 ED = ED.isValid() ? std::min(ED, I->start) : I->start;
3579 else
3580 LE = LE.isValid() ? std::max(LE, I->end) : I->end;
3581 }
3582 if (LE.isValid())
3583 NewEnd = std::min(NewEnd, LE);
3584 if (ED.isValid())
3585 NewEnd = std::min(NewEnd, ED);
3586
3587 // We only want to do the extension if there was a subrange that
3588 // was live across Def.
3589 if (LE.isValid()) {
3590 LiveRange::iterator S = LR.find(Def);
3591 if (S != LR.begin())
3592 std::prev(S)->end = NewEnd;
3593 }
3594 }
3595 LLVM_DEBUG({
3596 dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
3597 if (LI != nullptr)
3598 dbgs() << "\t\t LHS = " << *LI << '\n';
3599 });
3600 [[fallthrough]];
3601 }
3602
3603 case CR_Erase: {
3604 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3605 assert(MI && "No instruction to erase");
3606 if (MI->isCopy()) {
3607 Register Reg = MI->getOperand(1).getReg();
3608 if (Reg.isVirtual() && Reg != CP.getSrcReg() && Reg != CP.getDstReg())
3609 ShrinkRegs.push_back(Reg);
3610 }
3611 ErasedInstrs.insert(MI);
3612 LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
3614 MI->eraseFromParent();
3615 break;
3616 }
3617 default:
3618 break;
3619 }
3620 }
3621}
3622
3623void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
3624 LaneBitmask LaneMask,
3625 const CoalescerPair &CP) {
3626 SmallVector<VNInfo *, 16> NewVNInfo;
3627 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask, NewVNInfo,
3628 CP, LIS, TRI, true, true);
3629 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask, NewVNInfo,
3630 CP, LIS, TRI, true, true);
3631
3632 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
3633 // We should be able to resolve all conflicts here as we could successfully do
3634 // it on the mainrange already. There is however a problem when multiple
3635 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
3636 // interferences.
3637 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3638 // We already determined that it is legal to merge the intervals, so this
3639 // should never fail.
3640 llvm_unreachable("*** Couldn't join subrange!\n");
3641 }
3642 if (!LHSVals.resolveConflicts(RHSVals) ||
3643 !RHSVals.resolveConflicts(LHSVals)) {
3644 // We already determined that it is legal to merge the intervals, so this
3645 // should never fail.
3646 llvm_unreachable("*** Couldn't join subrange!\n");
3647 }
3648
3649 // The merging algorithm in LiveInterval::join() can't handle conflicting
3650 // value mappings, so we need to remove any live ranges that overlap a
3651 // CR_Replace resolution. Collect a set of end points that can be used to
3652 // restore the live range after joining.
3653 SmallVector<SlotIndex, 8> EndPoints;
3654 LHSVals.pruneValues(RHSVals, EndPoints, false);
3655 RHSVals.pruneValues(LHSVals, EndPoints, false);
3656
3657 LHSVals.removeImplicitDefs();
3658 RHSVals.removeImplicitDefs();
3659
3660 assert(LRange.verify() && RRange.verify());
3661
3662 // Join RRange into LHS.
3663 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3664 NewVNInfo);
3665
3666 LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask) << ' '
3667 << LRange << "\n");
3668 if (EndPoints.empty())
3669 return;
3670
3671 // Recompute the parts of the live range we had to remove because of
3672 // CR_Replace conflicts.
3673 LLVM_DEBUG({
3674 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3675 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3676 dbgs() << EndPoints[i];
3677 if (i != n - 1)
3678 dbgs() << ',';
3679 }
3680 dbgs() << ": " << LRange << '\n';
3681 });
3682 LIS->extendToIndices(LRange, EndPoints);
3683}
3684
3685void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
3686 const LiveRange &ToMerge,
3687 LaneBitmask LaneMask,
3688 CoalescerPair &CP,
3689 unsigned ComposeSubRegIdx) {
3691 LI.refineSubRanges(
3692 Allocator, LaneMask,
3693 [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
3694 if (SR.empty()) {
3695 SR.assign(ToMerge, Allocator);
3696 } else {
3697 // joinSubRegRange() destroys the merged range, so we need a copy.
3698 LiveRange RangeCopy(ToMerge, Allocator);
3699 joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
3700 }
3701 },
3702 *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
3703
3704 // Merging may leave subranges empty; drop them so the interval is left in a
3705 // valid state.
3707}
3708
3709bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
3711 return false;
3712 auto &Counter = LargeLIVisitCounter[LI.reg()];
3713 if (Counter < LargeIntervalFreqThreshold) {
3714 Counter++;
3715 return false;
3716 }
3717 return true;
3718}
3719
3720RegisterCoalescer::JoinResult
3721RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
3722 SmallVector<VNInfo *, 16> NewVNInfo;
3723 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
3724 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
3725 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
3726 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
3727 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3728 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
3729 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3730
3731 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
3732
3733 if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS)) {
3734 LLVM_DEBUG(dbgs() << "\t\tHigh-cost live interval: RHS valnos="
3735 << RHS.valnos.size() << ", segments=" << RHS.size()
3736 << "; LHS valnos=" << LHS.valnos.size()
3737 << ", segments=" << LHS.size() << '\n');
3738 return JoinResult::Rejected;
3739 }
3740
3741 // First compute NewVNInfo and the simple value mappings. Conflicts found
3742 // here only reject this attempt; subsequent coalescing may still make the
3743 // same copy joinable, so keep it deferred.
3744 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3745 return JoinResult::Deferred;
3746
3747 // Some conflicts can only be resolved after all values have been mapped.
3748 // As above, unresolved conflicts are retryable interference.
3749 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3750 return JoinResult::Deferred;
3751
3752 // All clear, the live ranges can be merged.
3753 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
3755
3756 // Transform lanemasks from the LHS to masks in the coalesced register and
3757 // create initial subranges if necessary.
3758 unsigned DstIdx = CP.getDstIdx();
3759 if (!LHS.hasSubRanges()) {
3760 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
3761 : TRI->getSubRegIndexLaneMask(DstIdx);
3762 // LHS must support subregs or we wouldn't be in this codepath.
3763 assert(Mask.any());
3764 LHS.createSubRangeFrom(Allocator, Mask, LHS);
3765 } else if (DstIdx != 0) {
3766 // Transform LHS lanemasks to new register class if necessary.
3767 for (LiveInterval::SubRange &R : LHS.subranges()) {
3768 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3769 R.LaneMask = Mask;
3770 }
3771 }
3772 LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
3773 << '\n');
3774
3775 // Determine lanemasks of RHS in the coalesced register and merge subranges.
3776 unsigned SrcIdx = CP.getSrcIdx();
3777 if (!RHS.hasSubRanges()) {
3778 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3779 : TRI->getSubRegIndexLaneMask(SrcIdx);
3780 mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
3781 } else {
3782 // Pair up subranges and merge.
3783 for (LiveInterval::SubRange &R : RHS.subranges()) {
3784 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3785 mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
3786 }
3787 }
3788 LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
3789
3790 // Pruning implicit defs from subranges may result in the main range
3791 // having stale segments.
3792 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3793
3794 LHSVals.pruneSubRegValues(LHS, ShrinkMask, PHIKills);
3795 RHSVals.pruneSubRegValues(LHS, ShrinkMask, PHIKills);
3796 } else if (TrackSubRegLiveness && !CP.getDstIdx() && CP.getSrcIdx()) {
3797 LHS.createSubRangeFrom(LIS->getVNInfoAllocator(),
3798 CP.getNewRC()->getLaneMask(), LHS);
3799 mergeSubRangeInto(LHS, RHS, TRI->getSubRegIndexLaneMask(CP.getSrcIdx()), CP,
3800 CP.getDstIdx());
3801 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3802 LHSVals.pruneSubRegValues(LHS, ShrinkMask, PHIKills);
3803 }
3804
3805 // The merging algorithm in LiveInterval::join() can't handle conflicting
3806 // value mappings, so we need to remove any live ranges that overlap a
3807 // CR_Replace resolution. Collect a set of end points that can be used to
3808 // restore the live range after joining.
3809 SmallVector<SlotIndex, 8> EndPoints;
3810 LHSVals.pruneValues(RHSVals, EndPoints, true);
3811 RHSVals.pruneValues(LHSVals, EndPoints, true);
3812
3813 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3814 // registers to require trimming.
3815 SmallVector<Register, 8> ShrinkRegs;
3816 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3817 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3818 while (!ShrinkRegs.empty())
3819 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3820
3821 // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3822 checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3823
3824 // If the RHS covers any PHI locations that were tracked for debug-info, we
3825 // must update tracking information to reflect the join.
3826 auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
3827 if (RegIt != RegToPHIIdx.end()) {
3828 // Iterate over all the debug instruction numbers assigned this register.
3829 for (unsigned InstID : RegIt->second) {
3830 auto PHIIt = PHIValToPos.find(InstID);
3831 assert(PHIIt != PHIValToPos.end());
3832 const SlotIndex &SI = PHIIt->second.SI;
3833
3834 // Does the RHS cover the position of this PHI?
3835 auto LII = RHS.find(SI);
3836 if (LII == RHS.end() || LII->start > SI)
3837 continue;
3838
3839 // Accept two kinds of subregister movement:
3840 // * When we merge from one register class into a larger register:
3841 // %1:gr16 = some-inst
3842 // ->
3843 // %2:gr32.sub_16bit = some-inst
3844 // * When the PHI is already in a subregister, and the larger class
3845 // is coalesced:
3846 // %2:gr32.sub_16bit = some-inst
3847 // %3:gr32 = COPY %2
3848 // ->
3849 // %3:gr32.sub_16bit = some-inst
3850 // Test for subregister move:
3851 if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
3852 // If we're moving between different subregisters, ignore this join.
3853 // The PHI will not get a location, dropping variable locations.
3854 if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
3855 continue;
3856
3857 // Update our tracking of where the PHI is.
3858 PHIIt->second.Reg = CP.getDstReg();
3859
3860 // If we merge into a sub-register of a larger class (test above),
3861 // update SubReg.
3862 if (CP.getSrcIdx() != 0)
3863 PHIIt->second.SubReg = CP.getSrcIdx();
3864 }
3865
3866 // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
3867 // different VRegs now. Copy old collection of debug instruction numbers and
3868 // erase the old one:
3869 auto InstrNums = RegIt->second;
3870 RegToPHIIdx.erase(RegIt);
3871
3872 // There might already be PHIs being tracked in the destination VReg. Insert
3873 // into an existing tracking collection, or insert a new one.
3874 RegIt = RegToPHIIdx.find(CP.getDstReg());
3875 if (RegIt != RegToPHIIdx.end())
3876 llvm::append_range(RegIt->second, InstrNums);
3877 else
3878 RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
3879 }
3880
3881 // Join RHS into LHS.
3882 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3883
3884 if (!EndPoints.empty()) {
3885 // Recompute the parts of the live range we had to remove because of
3886 // CR_Replace conflicts.
3887 LLVM_DEBUG({
3888 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3889 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3890 dbgs() << EndPoints[i];
3891 if (i != n - 1)
3892 dbgs() << ',';
3893 }
3894 dbgs() << ": " << LHS << '\n';
3895 });
3896 LIS->extendToIndices((LiveRange &)LHS, EndPoints);
3897 }
3898
3899 return JoinResult::Joined;
3900}
3901
3902RegisterCoalescer::JoinResult
3903RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3904 if (CP.isPhys())
3905 return joinReservedPhysReg(CP) ? JoinResult::Joined : JoinResult::Deferred;
3906 return joinVirtRegs(CP);
3907}
3908
3909void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF) {
3910 const SlotIndexes &Slots = *LIS->getSlotIndexes();
3912
3913 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3914 // vreg => DbgValueLoc map.
3915 auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3916 for (auto *X : ToInsert) {
3917 for (const auto &Op : X->debug_operands()) {
3918 if (Op.isReg() && Op.getReg().isVirtual())
3919 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
3920 }
3921 }
3922
3923 ToInsert.clear();
3924 };
3925
3926 // Iterate over all instructions, collecting them into the ToInsert vector.
3927 // Once a non-debug instruction is found, record the slot index of the
3928 // collected DBG_VALUEs.
3929 for (auto &MBB : MF) {
3930 SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3931
3932 for (auto &MI : MBB) {
3933 if (MI.isDebugValue()) {
3934 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
3935 return MO.isReg() && MO.getReg().isVirtual();
3936 }))
3937 ToInsert.push_back(&MI);
3938 } else if (!MI.isDebugOrPseudoInstr()) {
3939 CurrentSlot = Slots.getInstructionIndex(MI);
3940 CloseNewDVRange(CurrentSlot);
3941 }
3942 }
3943
3944 // Close range of DBG_VALUEs at the end of blocks.
3945 CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3946 }
3947
3948 // Sort all DBG_VALUEs we've seen by slot number.
3949 for (auto &Pair : DbgVRegToValues)
3950 llvm::sort(Pair.second);
3951}
3952
3953void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3954 LiveRange &LHS,
3955 JoinVals &LHSVals,
3956 LiveRange &RHS,
3957 JoinVals &RHSVals) {
3958 auto ScanForDstReg = [&](Register Reg) {
3959 checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3960 };
3961
3962 auto ScanForSrcReg = [&](Register Reg) {
3963 checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3964 };
3965
3966 // Scan for unsound updates of both the source and destination register.
3967 ScanForSrcReg(CP.getSrcReg());
3968 ScanForDstReg(CP.getDstReg());
3969}
3970
3971void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
3972 LiveRange &OtherLR,
3973 LiveRange &RegLR,
3974 JoinVals &RegVals) {
3975 // Are there any DBG_VALUEs to examine?
3976 auto VRegMapIt = DbgVRegToValues.find(Reg);
3977 if (VRegMapIt == DbgVRegToValues.end())
3978 return;
3979
3980 auto &DbgValueSet = VRegMapIt->second;
3981 auto DbgValueSetIt = DbgValueSet.begin();
3982 auto SegmentIt = OtherLR.begin();
3983
3984 bool LastUndefResult = false;
3985 SlotIndex LastUndefIdx;
3986
3987 // If the "Other" register is live at a slot Idx, test whether Reg can
3988 // safely be merged with it, or should be marked undef.
3989 auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3990 &LastUndefIdx](SlotIndex Idx) -> bool {
3991 // Our worst-case performance typically happens with asan, causing very
3992 // many DBG_VALUEs of the same location. Cache a copy of the most recent
3993 // result for this edge-case.
3994 if (LastUndefIdx == Idx)
3995 return LastUndefResult;
3996
3997 // If the other range was live, and Reg's was not, the register coalescer
3998 // will not have tried to resolve any conflicts. We don't know whether
3999 // the DBG_VALUE will refer to the same value number, so it must be made
4000 // undef.
4001 auto OtherIt = RegLR.find(Idx);
4002 if (OtherIt == RegLR.end())
4003 return true;
4004
4005 // Both the registers were live: examine the conflict resolution record for
4006 // the value number Reg refers to. CR_Keep meant that this value number
4007 // "won" and the merged register definitely refers to that value. CR_Erase
4008 // means the value number was a redundant copy of the other value, which
4009 // was coalesced and Reg deleted. It's safe to refer to the other register
4010 // (which will be the source of the copy).
4011 auto Resolution = RegVals.getResolution(OtherIt->valno->id);
4012 LastUndefResult =
4013 Resolution != JoinVals::CR_Keep && Resolution != JoinVals::CR_Erase;
4014 LastUndefIdx = Idx;
4015 return LastUndefResult;
4016 };
4017
4018 // Iterate over both the live-range of the "Other" register, and the set of
4019 // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
4020 // slot index. This relies on the DbgValueSet being ordered.
4021 while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
4022 if (DbgValueSetIt->first < SegmentIt->end) {
4023 // "Other" is live and there is a DBG_VALUE of Reg: test if we should
4024 // set it undef.
4025 if (DbgValueSetIt->first >= SegmentIt->start) {
4026 bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
4027 bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
4028 if (HasReg && ShouldUndefReg) {
4029 // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
4030 DbgValueSetIt->second->setDebugValueUndef();
4031 continue;
4032 }
4033 }
4034 ++DbgValueSetIt;
4035 } else {
4036 ++SegmentIt;
4037 }
4038 }
4039}
4040
4041namespace {
4042
4043/// Information concerning MBB coalescing priority.
4044struct MBBPriorityInfo {
4045 MachineBasicBlock *MBB;
4046 unsigned Depth;
4047 bool IsSplit;
4048
4049 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
4050 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
4051};
4052
4053} // end anonymous namespace
4054
4055/// C-style comparator that sorts first based on the loop depth of the basic
4056/// block (the unsigned), and then on the MBB number.
4057///
4058/// EnableGlobalCopies assumes that the primary sort key is loop depth.
4059static int compareMBBPriority(const MBBPriorityInfo *LHS,
4060 const MBBPriorityInfo *RHS) {
4061 // Deeper loops first
4062 if (LHS->Depth != RHS->Depth)
4063 return LHS->Depth > RHS->Depth ? -1 : 1;
4064
4065 // Try to unsplit critical edges next.
4066 if (LHS->IsSplit != RHS->IsSplit)
4067 return LHS->IsSplit ? -1 : 1;
4068
4069 // Prefer blocks that are more connected in the CFG. This takes care of
4070 // the most difficult copies first while intervals are short.
4071 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
4072 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
4073 if (cl != cr)
4074 return cl > cr ? -1 : 1;
4075
4076 // As a last resort, sort by block number.
4077 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
4078}
4079
4080/// \returns true if the given copy uses or defines a local live range.
4081static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
4082 if (!Copy->isCopy())
4083 return false;
4084
4085 if (Copy->getOperand(1).isUndef())
4086 return false;
4087
4088 Register SrcReg = Copy->getOperand(1).getReg();
4089 Register DstReg = Copy->getOperand(0).getReg();
4090 if (SrcReg.isPhysical() || DstReg.isPhysical())
4091 return false;
4092
4093 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) ||
4094 LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
4095}
4096
4097void RegisterCoalescer::lateLiveIntervalUpdate() {
4098 for (Register reg : ToBeUpdated) {
4099 if (!LIS->hasInterval(reg))
4100 continue;
4101 LiveInterval &LI = LIS->getInterval(reg);
4102 shrinkToUses(&LI, &DeadDefs);
4103 if (!DeadDefs.empty())
4104 eliminateDeadDefs();
4105 }
4106 ToBeUpdated.clear();
4107}
4108
4109bool RegisterCoalescer::copyCoalesceWorkList(
4111 bool Progress = false;
4112 SmallPtrSet<MachineInstr *, 4> CurrentErasedInstrs;
4113 for (MachineInstr *&MI : CurrList) {
4114 if (!MI)
4115 continue;
4116 // Skip instruction pointers that have already been erased, for example by
4117 // dead code elimination.
4118 if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
4119 MI = nullptr;
4120 continue;
4121 }
4122 JoinResult Result = joinCopy(MI, CurrentErasedInstrs);
4123 Progress |= Result == JoinResult::Joined;
4124 if (Result != JoinResult::Deferred)
4125 MI = nullptr;
4126 }
4127 // Clear instructions not recorded in `ErasedInstrs` but erased.
4128 if (!CurrentErasedInstrs.empty()) {
4129 for (MachineInstr *&MI : CurrList) {
4130 if (MI && CurrentErasedInstrs.count(MI))
4131 MI = nullptr;
4132 }
4133 for (MachineInstr *&MI : WorkList) {
4134 if (MI && CurrentErasedInstrs.count(MI))
4135 MI = nullptr;
4136 }
4137 }
4138 return Progress;
4139}
4140
4141/// Check if DstReg is a terminal node.
4142/// I.e., it does not have any affinity other than \p Copy.
4143static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
4144 const MachineRegisterInfo *MRI) {
4145 assert(Copy.isCopyLike());
4146 // Check if the destination of this copy as any other affinity.
4147 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
4148 if (&MI != &Copy && MI.isCopyLike())
4149 return false;
4150 return true;
4151}
4152
4153bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
4154 assert(Copy.isCopyLike());
4155 if (!UseTerminalRule)
4156 return false;
4157 Register SrcReg, DstReg;
4158 unsigned SrcSubReg = 0, DstSubReg = 0;
4159 if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
4160 return false;
4161 // Check if the destination of this copy has any other affinity.
4162 if (DstReg.isPhysical() ||
4163 // If SrcReg is a physical register, the copy won't be coalesced.
4164 // Ignoring it may have other side effect (like missing
4165 // rematerialization). So keep it.
4166 SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
4167 return false;
4168
4169 // DstReg is a terminal node. Check if it interferes with any other
4170 // copy involving SrcReg.
4171 const MachineBasicBlock *OrigBB = Copy.getParent();
4172 const LiveInterval &DstLI = LIS->getInterval(DstReg);
4173 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
4174 // Technically we should check if the weight of the new copy is
4175 // interesting compared to the other one and update the weight
4176 // of the copies accordingly. However, this would only work if
4177 // we would gather all the copies first then coalesce, whereas
4178 // right now we interleave both actions.
4179 // For now, just consider the copies that are in the same block.
4180 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
4181 continue;
4182 Register OtherSrcReg, OtherReg;
4183 unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
4184 if (!isMoveInstr(*TRI, &MI, OtherSrcReg, OtherReg, OtherSrcSubReg,
4185 OtherSubReg))
4186 return false;
4187 if (OtherReg == SrcReg)
4188 OtherReg = OtherSrcReg;
4189 // Check if OtherReg is a non-terminal.
4190 if (OtherReg.isPhysical() || isTerminalReg(OtherReg, MI, MRI))
4191 continue;
4192 // Check that OtherReg interfere with DstReg.
4193 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
4194 LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
4195 << '\n');
4196 return true;
4197 }
4198 }
4199 return false;
4200}
4201
4202void RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
4203 LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
4204
4205 // Collect all copy-like instructions in MBB. Don't start coalescing anything
4206 // yet, it might invalidate the iterator.
4207 const unsigned PrevSize = WorkList.size();
4208 if (JoinGlobalCopies) {
4209 SmallVector<MachineInstr *, 2> LocalTerminals;
4210 SmallVector<MachineInstr *, 2> GlobalTerminals;
4211 // Coalesce copies top-down to propagate coalescing and rematerialization
4212 // forward.
4213 for (MachineInstr &MI : *MBB) {
4214 if (!MI.isCopyLike())
4215 continue;
4216 bool ApplyTerminalRule = applyTerminalRule(MI);
4217 if (isLocalCopy(&MI, LIS)) {
4218 if (ApplyTerminalRule)
4219 LocalTerminals.push_back(&MI);
4220 else
4221 LocalWorkList.push_back(&MI);
4222 } else {
4223 if (ApplyTerminalRule)
4224 GlobalTerminals.push_back(&MI);
4225 else
4226 WorkList.push_back(&MI);
4227 }
4228 }
4229 // Append the copies evicted by the terminal rule at the end of the list.
4230 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
4231 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
4232 } else {
4234 // Coalesce copies top-down to propagate coalescing and rematerialization
4235 // forward.
4236 for (MachineInstr &MII : *MBB)
4237 if (MII.isCopyLike()) {
4238 if (applyTerminalRule(MII))
4239 Terminals.push_back(&MII);
4240 else
4241 WorkList.push_back(&MII);
4242 }
4243 // Append the copies evicted by the terminal rule at the end of the list.
4244 WorkList.append(Terminals.begin(), Terminals.end());
4245 }
4246 // Try coalescing the collected copies immediately, and remove the nulls.
4247 // This prevents the WorkList from getting too large since most copies are
4248 // joinable on the first attempt.
4249 MutableArrayRef<MachineInstr *> CurrList(WorkList.begin() + PrevSize,
4250 WorkList.end());
4251 if (copyCoalesceWorkList(CurrList))
4252 WorkList.erase(
4253 std::remove(WorkList.begin() + PrevSize, WorkList.end(), nullptr),
4254 WorkList.end());
4255}
4256
4257void RegisterCoalescer::coalesceLocals() {
4258 copyCoalesceWorkList(LocalWorkList);
4259 for (MachineInstr *MI : LocalWorkList) {
4260 if (MI)
4261 WorkList.push_back(MI);
4262 }
4263 LocalWorkList.clear();
4264}
4265
4266void RegisterCoalescer::joinAllIntervals() {
4267 LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
4268 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
4269
4270 std::vector<MBBPriorityInfo> MBBs;
4271 MBBs.reserve(MF->size());
4272 for (MachineBasicBlock &MBB : *MF) {
4273 MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
4274 JoinSplitEdges && isSplitEdge(&MBB)));
4275 }
4276 llvm::sort(MBBs, [](const MBBPriorityInfo &LHS, const MBBPriorityInfo &RHS) {
4277 return compareMBBPriority(&LHS, &RHS) < 0;
4278 });
4279
4280 // Coalesce intervals in MBB priority order.
4281 unsigned CurrDepth = std::numeric_limits<unsigned>::max();
4282 for (MBBPriorityInfo &MBB : MBBs) {
4283 // Try coalescing the collected local copies for deeper loops.
4284 if (JoinGlobalCopies && MBB.Depth < CurrDepth) {
4285 coalesceLocals();
4286 CurrDepth = MBB.Depth;
4287 }
4288 copyCoalesceInMBB(MBB.MBB);
4289 }
4290 lateLiveIntervalUpdate();
4291 coalesceLocals();
4292
4293 // Joining intervals can allow other intervals to be joined. Iteratively join
4294 // until we make no progress.
4295 while (copyCoalesceWorkList(WorkList))
4296 /* empty */;
4297 lateLiveIntervalUpdate();
4298}
4299
4303 MFPropsModifier _(*this, MF);
4304 auto &LIS = MFAM.getResult<LiveIntervalsAnalysis>(MF);
4305 auto &Loops = MFAM.getResult<MachineLoopAnalysis>(MF);
4306 auto *SI = MFAM.getCachedResult<SlotIndexesAnalysis>(MF);
4307 auto *RegClassInfo = &MFAM.getResult<MachineRegisterClassAnalysis>(MF);
4308 RegisterCoalescer Impl(&LIS, SI, &Loops, RegClassInfo);
4309 if (!Impl.run(MF))
4310 return PreservedAnalyses::all();
4312 PA.preserveSet<CFGAnalyses>();
4313 PA.preserve<LiveIntervalsAnalysis>();
4314 PA.preserve<SlotIndexesAnalysis>();
4315 return PA;
4316}
4317
4318bool RegisterCoalescerLegacy::runOnMachineFunction(MachineFunction &MF) {
4319 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
4320 auto *Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
4321 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
4322 auto *RegClassInfo =
4323 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
4324 SlotIndexes *SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
4325 RegisterCoalescer Impl(LIS, SI, Loops, RegClassInfo);
4326 return Impl.run(MF);
4327}
4328
4329bool RegisterCoalescer::run(MachineFunction &fn) {
4330 LLVM_DEBUG(dbgs() << "********** REGISTER COALESCER **********\n"
4331 << "********** Function: " << fn.getName() << '\n');
4332
4333 // Variables changed between a setjmp and a longjump can have undefined value
4334 // after the longjmp. This behaviour can be observed if such a variable is
4335 // spilled, so longjmp won't restore the value in the spill slot.
4336 // RegisterCoalescer should not run in functions with a setjmp to avoid
4337 // merging such undefined variables with predictable ones.
4338 //
4339 // TODO: Could specifically disable coalescing registers live across setjmp
4340 // calls
4341 if (fn.exposesReturnsTwice()) {
4342 LLVM_DEBUG(
4343 dbgs() << "* Skipped as it exposes functions that returns twice.\n");
4344 return false;
4345 }
4346
4347 MF = &fn;
4348 MRI = &fn.getRegInfo();
4349 const TargetSubtargetInfo &STI = fn.getSubtarget();
4350 TRI = STI.getRegisterInfo();
4351 TII = STI.getInstrInfo();
4353 JoinGlobalCopies = STI.enableJoinGlobalCopies();
4354 else
4355 JoinGlobalCopies = (EnableGlobalCopies == cl::boolOrDefault::BOU_TRUE);
4356
4357 // If there are PHIs tracked by debug-info, they will need updating during
4358 // coalescing. Build an index of those PHIs to ease updating.
4359 SlotIndexes *Slots = LIS->getSlotIndexes();
4360 for (const auto &DebugPHI : MF->DebugPHIPositions) {
4361 MachineBasicBlock *MBB = DebugPHI.second.MBB;
4362 Register Reg = DebugPHI.second.Reg;
4363 unsigned SubReg = DebugPHI.second.SubReg;
4364 SlotIndex SI = Slots->getMBBStartIdx(MBB);
4365 PHIValPos P = {SI, Reg, SubReg};
4366 PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
4367 RegToPHIIdx[Reg].push_back(DebugPHI.first);
4368 }
4369
4370 // The MachineScheduler does not currently require JoinSplitEdges. This will
4371 // either be enabled unconditionally or replaced by a more general live range
4372 // splitting optimization.
4373 JoinSplitEdges = EnableJoinSplits;
4374
4375 if (VerifyCoalescing)
4376 MF->verify(LIS, SI, "Before register coalescing", &errs());
4377
4378 DbgVRegToValues.clear();
4380
4381 // Join (coalesce) intervals if requested.
4382 if (EnableJoining)
4383 joinAllIntervals();
4384
4385 // After deleting a lot of copies, register classes may be less constrained.
4386 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
4387 // DPR inflation.
4388 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
4389 InflateRegs.erase(llvm::unique(InflateRegs), InflateRegs.end());
4390 LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
4391 << " regs.\n");
4392 for (Register Reg : InflateRegs) {
4393 if (MRI->reg_nodbg_empty(Reg))
4394 continue;
4395 if (MRI->recomputeRegClass(Reg)) {
4396 LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
4397 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
4398 ++NumInflated;
4399
4400 LiveInterval &LI = LIS->getInterval(Reg);
4401 if (LI.hasSubRanges()) {
4402 // If the inflated register class does not support subregisters anymore
4403 // remove the subranges.
4405 LI.clearSubRanges();
4406 } else {
4407#ifndef NDEBUG
4409 // If subranges are still supported, then the same subregs
4410 // should still be supported.
4411 for (LiveInterval::SubRange &S : LI.subranges()) {
4412 assert((S.LaneMask & ~MaxMask).none());
4413 }
4414#endif
4415 }
4416 }
4417 }
4418 }
4419
4420 // After coalescing, update any PHIs that are being tracked by debug-info
4421 // with their new VReg locations.
4422 for (auto &p : MF->DebugPHIPositions) {
4423 auto it = PHIValToPos.find(p.first);
4424 assert(it != PHIValToPos.end());
4425 p.second.Reg = it->second.Reg;
4426 p.second.SubReg = it->second.SubReg;
4427 }
4428
4429 PHIValToPos.clear();
4430 RegToPHIIdx.clear();
4431
4432 LLVM_DEBUG(LIS->dump());
4433
4434 if (VerifyCoalescing)
4435 MF->verify(LIS, SI, "After register coalescing", &errs());
4436 return true;
4437}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
const HexagonInstrInfo * TII
Hexagon Hardware Loops
#define _
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
Basic Register Allocator
static cl::opt< bool > UseTerminalRule("terminal-rule", cl::desc("Apply the terminal rule"), cl::init(true), cl::Hidden)
static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS)
static bool isSplitEdge(const MachineBasicBlock *MBB)
Return true if this block should be vacated by the coalescer to eliminate branches.
static int compareMBBPriority(const MBBPriorityInfo *LHS, const MBBPriorityInfo *RHS)
C-style comparator that sorts first based on the loop depth of the basic block (the unsigned),...
static cl::opt< unsigned > LargeIntervalSizeThreshold("large-interval-size-threshold", cl::Hidden, cl::desc("If the valnos size of an interval is larger than the threshold, " "it is regarded as a large interval. "), cl::init(100))
static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def)
Check if any of the subranges of LI contain a definition at Def.
static std::pair< bool, bool > addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, const VNInfo *SrcValNo)
Copy segments with value number SrcValNo from liverange Src to live range @Dst and use value number D...
static bool isLiveThrough(const LiveQueryResult Q)
static bool isTerminalReg(Register DstReg, const MachineInstr &Copy, const MachineRegisterInfo *MRI)
Check if DstReg is a terminal node.
static cl::opt< bool > VerifyCoalescing("verify-coalescing", cl::desc("Verify machine instrs before and after register coalescing"), cl::Hidden)
static void collectPHIKills(const LiveRange &LR, const VNInfo *VNI, const SlotIndexes &Indexes, SmallVectorImpl< SlotIndex > &PHIKills)
Collect the ends of the predecessors where VNI is live-out into a PHI value of LR.
register Register static false bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, Register &Src, Register &Dst, unsigned &SrcSub, unsigned &DstSub)
static cl::opt< bool > EnableJoinSplits("join-splitedges", cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden)
Temporary flag to test critical edge unsplitting.
static cl::opt< bool > EnableJoining("join-liveintervals", cl::desc("Coalesce copies (default=true)"), cl::init(true), cl::Hidden)
static cl::opt< unsigned > LargeIntervalFreqThreshold("large-interval-freq-threshold", cl::Hidden, cl::desc("For a large interval, if it is coalesced with other live " "intervals many times more than the threshold, stop its " "coalescing to control the compile time. "), cl::init(256))
static cl::opt< unsigned > LateRematUpdateThreshold("late-remat-update-threshold", cl::Hidden, cl::desc("During rematerialization for a copy, if the def instruction has " "many other copy uses to be rematerialized, delay the multiple " "separate live interval update work and do them all at once after " "all those rematerialization are done. It will save a lot of " "repeated work. "), cl::init(100))
static cl::opt< cl::boolOrDefault > EnableGlobalCopies("join-globalcopies", cl::desc("Coalesce copies that span blocks (default=subtarget)"), cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden)
Temporary flag to test global copy optimization.
SI Optimize VGPR LiveRange
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static DenseMap< Register, std::vector< std::pair< SlotIndex, MachineInstr * > > > buildVRegToDbgValueMap(MachineFunction &MF, const LiveIntervals *Liveness)
static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS)
Value * RHS
Value * LHS
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A helper class for register coalescers.
unsigned getDstIdx() const
Return the subregister index that DstReg will be coalesced into, or 0.
bool isFlipped() const
Return true when getSrcReg is the register being defined by the original copy instruction.
bool isPartial() const
Return true if the original copy instruction did not copy the full register, but was a subreg operati...
bool flip()
Swap SrcReg and DstReg.
bool isPhys() const
Return true if DstReg is a physical register.
bool isCrossClass() const
Return true if DstReg is virtual and NewRC is a smaller register class than DstReg's.
Register getDstReg() const
Return the register (virtual or physical) that will remain after coalescing.
bool isCoalescable(const MachineInstr *) const
Return true if MI is a copy instruction that will become an identity copy after coalescing.
const TargetRegisterClass * getNewRC() const
Return the register class of the coalesced register.
bool setRegisters(const MachineInstr *)
Set registers to match the copy instruction MI.
unsigned getSrcIdx() const
Return the subregister index that SrcReg will be coalesced into, or 0.
Register getSrcReg() const
Return the virtual register that will be coalesced away.
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
bool isAsCheapAsAMove(const MachineInstr &MI) const override
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
LLVM_ABI void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
SubRange * createSubRangeFrom(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, const LiveRange &CopyFrom)
Like createSubRange() but the new range is filled with a copy of the liveness information in CopyFrom...
iterator_range< subrange_iterator > subranges()
LLVM_ABI void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, std::function< void(LiveInterval::SubRange &)> Apply, const SlotIndexes &Indexes, const TargetRegisterInfo &TRI, unsigned ComposeSubRegIdx=0)
Refines the subranges to support LaneMask.
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
LLVM_ABI void clearSubRanges()
Removes all subregister liveness information.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
LLVM_ABI bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI bool checkRegMaskInterference(const LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void pruneValue(LiveRange &LR, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
If LR has a live value at Kill, prune its live range by removing any liveness reachable from Kill.
void removeInterval(Register Reg)
Interval removal.
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
LLVM_ABI void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void dump() const
LLVM_ABI void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
Result of a LiveRange query.
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
bool isKill() const
Return true if the live-in value is killed by this instruction.
Callback methods for LiveRangeEdit owners.
SlotIndex rematerializeAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, const Remat &RM, const TargetRegisterInfo &, bool Late=false, unsigned SubIdx=0, MachineInstr *ReplaceIndexMI=nullptr, LaneBitmask UsedLanes=LaneBitmask::getAll())
rematerializeAt - Rematerialize RM.ParentVNI into DestReg by inserting an instruction into MBB before...
void eliminateDeadDefs(SmallVectorImpl< MachineInstr * > &Dead, ArrayRef< Register > RegsBeingSpilled={})
eliminateDeadDefs - Try to delete machine instructions that are now dead (allDefsAreDead returns true...
This class represents the liveness of a register, stack slot, etc.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
Segments::iterator iterator
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
LLVM_ABI void join(LiveRange &Other, const int *ValNoAssignments, const int *RHSValNoAssignments, SmallVectorImpl< VNInfo * > &NewVNInfo)
join - Join two live ranges (this, and other) together.
bool liveAt(SlotIndex index) const
LLVM_ABI VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
LLVM_ABI void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
bool empty() const
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool verify() const
Walk the range and assert if any invariants fail to hold.
LLVM_ABI VNInfo * MergeValueNumberInto(VNInfo *V1, VNInfo *V2)
MergeValueNumberInto - This method is called when two value numbers are found to be equivalent.
unsigned getNumValNums() const
iterator begin()
VNInfoList valnos
bool containsOneValue() const
size_t size() const
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none.
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
MCRegUnitRootIterator enumerates the root registers of a register unit.
bool isValid() const
Check if the iterator is at the end of the list.
LaneBitmask getLaneMask() const
Returns the combination of all lane masks of register in this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI bool hasEHPadSuccessor() const
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void setRegisterDefReadUndef(Register Reg, bool IsUndef=true)
Mark all subregister defs of register Reg with the undef flag.
bool isImplicitDef() const
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
LLVM_ABI std::pair< bool, bool > readsWritesVirtualRegister(Register Reg, SmallVectorImpl< unsigned > *Ops=nullptr) const
Return a pair of bools (reads, writes) indicating if this instruction reads or writes Reg.
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand,...
bool isFullCopy() const
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
LLVM_ABI bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
LLVM_ABI void substPhysReg(MCRegister Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI bool recomputeRegClass(Register Reg)
recomputeRegClass - Try to find a legal super-class of Reg's register class that still satisfies the ...
reg_instr_iterator reg_instr_begin(Register RegNo) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
static reg_instr_iterator reg_instr_end()
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
defusechain_instr_iterator< true, true, false, true > reg_instr_iterator
reg_instr_iterator/reg_instr_begin/reg_instr_end - Walk all defs and uses of the specified register,...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
iterator_range< reg_instr_nodbg_iterator > reg_nodbg_instructions(Register Reg) const
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool isProperSubClass(const TargetRegisterClass *RC) const
isProperSubClass - Returns true if RC has a legal super-class with more allocatable registers.
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
bool isEarlyClobber() const
isEarlyClobber - Returns true if this is an early-clobber slot.
bool isValid() const
Returns true if this is a valid index.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
SlotIndexes pass.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Returns the index past the last valid index in the given basic block.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Returns the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual bool enableJoinGlobalCopies() const
True if the subtarget should enable joining global copies.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
VNInfo - Value Number Information.
void markUnused()
Mark this value as unused.
BumpPtrAllocator Allocator
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
static LLVM_ABI bool allUsesAvailableAt(const MachineInstr *MI, SlotIndex UseIdx, const LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This namespace contains all of the command line option processing machinery.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
iterator end() const
Definition BasicBlock.h:89
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:313
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
@ Dead
Unused definition.
@ Kill
The last use of a register.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
LLVM_ABI void eraseInstrs(ArrayRef< MachineInstr * > DeadInstrs, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1817
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
static constexpr LaneBitmask getLane(unsigned Lane)
Definition LaneBitmask.h:83
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Remat - Information needed to rematerialize at a specific location.
This represents a simple continuous liveness interval for a value.