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