Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / CodeGen / RegisterCoalescer.cpp
blob9858482cd51b4a7cb74a1a50f89384915ef55c83
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.
13 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/LiveInterval.h"
25 #include "llvm/CodeGen/LiveIntervals.h"
26 #include "llvm/CodeGen/LiveRangeEdit.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/RegisterClassInfo.h"
37 #include "llvm/CodeGen/SlotIndexes.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetOpcodes.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/MC/LaneBitmask.h"
45 #include "llvm/MC/MCInstrDesc.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <iterator>
56 #include <limits>
57 #include <tuple>
58 #include <utility>
59 #include <vector>
61 using namespace llvm;
63 #define DEBUG_TYPE "regalloc"
65 STATISTIC(numJoins , "Number of interval joins performed");
66 STATISTIC(numCrossRCs , "Number of cross class joins performed");
67 STATISTIC(numCommutes , "Number of instruction commuting performed");
68 STATISTIC(numExtends , "Number of copies extended");
69 STATISTIC(NumReMats , "Number of instructions re-materialized");
70 STATISTIC(NumInflated , "Number of register classes inflated");
71 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
72 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
73 STATISTIC(NumShrinkToUses, "Number of shrinkToUses called");
75 static cl::opt<bool> EnableJoining("join-liveintervals",
76 cl::desc("Coalesce copies (default=true)"),
77 cl::init(true), cl::Hidden);
79 static cl::opt<bool> UseTerminalRule("terminal-rule",
80 cl::desc("Apply the terminal rule"),
81 cl::init(false), cl::Hidden);
83 /// Temporary flag to test critical edge unsplitting.
84 static cl::opt<bool>
85 EnableJoinSplits("join-splitedges",
86 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
88 /// Temporary flag to test global copy optimization.
89 static cl::opt<cl::boolOrDefault>
90 EnableGlobalCopies("join-globalcopies",
91 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
92 cl::init(cl::BOU_UNSET), cl::Hidden);
94 static cl::opt<bool>
95 VerifyCoalescing("verify-coalescing",
96 cl::desc("Verify machine instrs before and after register coalescing"),
97 cl::Hidden);
99 static cl::opt<unsigned> LateRematUpdateThreshold(
100 "late-remat-update-threshold", cl::Hidden,
101 cl::desc("During rematerialization for a copy, if the def instruction has "
102 "many other copy uses to be rematerialized, delay the multiple "
103 "separate live interval update work and do them all at once after "
104 "all those rematerialization are done. It will save a lot of "
105 "repeated work. "),
106 cl::init(100));
108 static cl::opt<unsigned> LargeIntervalSizeThreshold(
109 "large-interval-size-threshold", cl::Hidden,
110 cl::desc("If the valnos size of an interval is larger than the threshold, "
111 "it is regarded as a large interval. "),
112 cl::init(100));
114 static cl::opt<unsigned> LargeIntervalFreqThreshold(
115 "large-interval-freq-threshold", cl::Hidden,
116 cl::desc("For a large interval, if it is coalesed with other live "
117 "intervals many times more than the threshold, stop its "
118 "coalescing to control the compile time. "),
119 cl::init(256));
121 namespace {
123 class JoinVals;
125 class RegisterCoalescer : public MachineFunctionPass,
126 private LiveRangeEdit::Delegate {
127 MachineFunction* MF = nullptr;
128 MachineRegisterInfo* MRI = nullptr;
129 const TargetRegisterInfo* TRI = nullptr;
130 const TargetInstrInfo* TII = nullptr;
131 LiveIntervals *LIS = nullptr;
132 const MachineLoopInfo* Loops = nullptr;
133 AliasAnalysis *AA = nullptr;
134 RegisterClassInfo RegClassInfo;
136 /// Position and VReg of a PHI instruction during coalescing.
137 struct PHIValPos {
138 SlotIndex SI; ///< Slot where this PHI occurs.
139 Register Reg; ///< VReg the PHI occurs in.
140 unsigned SubReg; ///< Qualifying subregister for Reg.
143 /// Map from debug instruction number to PHI position during coalescing.
144 DenseMap<unsigned, PHIValPos> PHIValToPos;
145 /// Index of, for each VReg, which debug instruction numbers and
146 /// corresponding PHIs are sensitive to coalescing. Each VReg may have
147 /// multiple PHI defs, at different positions.
148 DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
150 /// Debug variable location tracking -- for each VReg, maintain an
151 /// ordered-by-slot-index set of DBG_VALUEs, to help quick
152 /// identification of whether coalescing may change location validity.
153 using DbgValueLoc = std::pair<SlotIndex, MachineInstr*>;
154 DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
156 /// A LaneMask to remember on which subregister live ranges we need to call
157 /// shrinkToUses() later.
158 LaneBitmask ShrinkMask;
160 /// True if the main range of the currently coalesced intervals should be
161 /// checked for smaller live intervals.
162 bool ShrinkMainRange = false;
164 /// True if the coalescer should aggressively coalesce global copies
165 /// in favor of keeping local copies.
166 bool JoinGlobalCopies = false;
168 /// True if the coalescer should aggressively coalesce fall-thru
169 /// blocks exclusively containing copies.
170 bool JoinSplitEdges = false;
172 /// Copy instructions yet to be coalesced.
173 SmallVector<MachineInstr*, 8> WorkList;
174 SmallVector<MachineInstr*, 8> LocalWorkList;
176 /// Set of instruction pointers that have been erased, and
177 /// that may be present in WorkList.
178 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
180 /// Dead instructions that are about to be deleted.
181 SmallVector<MachineInstr*, 8> DeadDefs;
183 /// Virtual registers to be considered for register class inflation.
184 SmallVector<Register, 8> InflateRegs;
186 /// The collection of live intervals which should have been updated
187 /// immediately after rematerialiation but delayed until
188 /// lateLiveIntervalUpdate is called.
189 DenseSet<Register> ToBeUpdated;
191 /// Record how many times the large live interval with many valnos
192 /// has been tried to join with other live interval.
193 DenseMap<Register, unsigned long> LargeLIVisitCounter;
195 /// Recursively eliminate dead defs in DeadDefs.
196 void eliminateDeadDefs(LiveRangeEdit *Edit = nullptr);
198 /// LiveRangeEdit callback for eliminateDeadDefs().
199 void LRE_WillEraseInstruction(MachineInstr *MI) override;
201 /// Coalesce the LocalWorkList.
202 void coalesceLocals();
204 /// Join compatible live intervals
205 void joinAllIntervals();
207 /// Coalesce copies in the specified MBB, putting
208 /// copies that cannot yet be coalesced into WorkList.
209 void copyCoalesceInMBB(MachineBasicBlock *MBB);
211 /// Tries to coalesce all copies in CurrList. Returns true if any progress
212 /// was made.
213 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
215 /// If one def has many copy like uses, and those copy uses are all
216 /// rematerialized, the live interval update needed for those
217 /// rematerializations will be delayed and done all at once instead
218 /// of being done multiple times. This is to save compile cost because
219 /// live interval update is costly.
220 void lateLiveIntervalUpdate();
222 /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
223 /// has no value defined in the predecessors. If the incoming value is the
224 /// same as defined by the copy itself, the value is considered undefined.
225 bool copyValueUndefInPredecessors(LiveRange &S,
226 const MachineBasicBlock *MBB,
227 LiveQueryResult SLRQ);
229 /// Set necessary undef flags on subregister uses after pruning out undef
230 /// lane segments from the subrange.
231 void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
232 LaneBitmask PrunedLanes);
234 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
235 /// src/dst of the copy instruction CopyMI. This returns true if the copy
236 /// was successfully coalesced away. If it is not currently possible to
237 /// coalesce this interval, but it may be possible if other things get
238 /// coalesced, then it returns true by reference in 'Again'.
239 bool joinCopy(MachineInstr *CopyMI, bool &Again);
241 /// Attempt to join these two intervals. On failure, this
242 /// returns false. The output "SrcInt" will not have been modified, so we
243 /// can use this information below to update aliases.
244 bool joinIntervals(CoalescerPair &CP);
246 /// Attempt joining two virtual registers. Return true on success.
247 bool joinVirtRegs(CoalescerPair &CP);
249 /// If a live interval has many valnos and is coalesced with other
250 /// live intervals many times, we regard such live interval as having
251 /// high compile time cost.
252 bool isHighCostLiveInterval(LiveInterval &LI);
254 /// Attempt joining with a reserved physreg.
255 bool joinReservedPhysReg(CoalescerPair &CP);
257 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
258 /// Subranges in @p LI which only partially interfere with the desired
259 /// LaneMask are split as necessary. @p LaneMask are the lanes that
260 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
261 /// lanemasks already adjusted to the coalesced register.
262 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
263 LaneBitmask LaneMask, CoalescerPair &CP,
264 unsigned DstIdx);
266 /// Join the liveranges of two subregisters. Joins @p RRange into
267 /// @p LRange, @p RRange may be invalid afterwards.
268 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
269 LaneBitmask LaneMask, const CoalescerPair &CP);
271 /// We found a non-trivially-coalescable copy. If the source value number is
272 /// defined by a copy from the destination reg see if we can merge these two
273 /// destination reg valno# into a single value number, eliminating a copy.
274 /// This returns true if an interval was modified.
275 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
277 /// Return true if there are definitions of IntB
278 /// other than BValNo val# that can reach uses of AValno val# of IntA.
279 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
280 VNInfo *AValNo, VNInfo *BValNo);
282 /// We found a non-trivially-coalescable copy.
283 /// If the source value number is defined by a commutable instruction and
284 /// its other operand is coalesced to the copy dest register, see if we
285 /// can transform the copy into a noop by commuting the definition.
286 /// This returns a pair of two flags:
287 /// - the first element is true if an interval was modified,
288 /// - the second element is true if the destination interval needs
289 /// to be shrunk after deleting the copy.
290 std::pair<bool,bool> removeCopyByCommutingDef(const CoalescerPair &CP,
291 MachineInstr *CopyMI);
293 /// We found a copy which can be moved to its less frequent predecessor.
294 bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
296 /// If the source of a copy is defined by a
297 /// trivial computation, replace the copy by rematerialize the definition.
298 bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
299 bool &IsDefCopy);
301 /// Return true if a copy involving a physreg should be joined.
302 bool canJoinPhys(const CoalescerPair &CP);
304 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
305 /// number if it is not zero. If DstReg is a physical register and the
306 /// existing subregister number of the def / use being updated is not zero,
307 /// make sure to set it to the correct physical subregister.
308 void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
310 /// If the given machine operand reads only undefined lanes add an undef
311 /// flag.
312 /// This can happen when undef uses were previously concealed by a copy
313 /// which we coalesced. Example:
314 /// %0:sub0<def,read-undef> = ...
315 /// %1 = COPY %0 <-- Coalescing COPY reveals undef
316 /// = use %1:sub1 <-- hidden undef use
317 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
318 MachineOperand &MO, unsigned SubRegIdx);
320 /// Handle copies of undef values. If the undef value is an incoming
321 /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
322 /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
323 /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
324 MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
326 /// Check whether or not we should apply the terminal rule on the
327 /// destination (Dst) of \p Copy.
328 /// When the terminal rule applies, Copy is not profitable to
329 /// coalesce.
330 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
331 /// at least one interference (Dst, Dst2). If Dst is terminal, the
332 /// terminal rule consists in checking that at least one of
333 /// interfering node, say Dst2, has an affinity of equal or greater
334 /// weight with Src.
335 /// In that case, Dst2 and Dst will not be able to be both coalesced
336 /// with Src. Since Dst2 exposes more coalescing opportunities than
337 /// Dst, we can drop \p Copy.
338 bool applyTerminalRule(const MachineInstr &Copy) const;
340 /// Wrapper method for \see LiveIntervals::shrinkToUses.
341 /// This method does the proper fixing of the live-ranges when the afore
342 /// mentioned method returns true.
343 void shrinkToUses(LiveInterval *LI,
344 SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
345 NumShrinkToUses++;
346 if (LIS->shrinkToUses(LI, Dead)) {
347 /// Check whether or not \p LI is composed by multiple connected
348 /// components and if that is the case, fix that.
349 SmallVector<LiveInterval*, 8> SplitLIs;
350 LIS->splitSeparateComponents(*LI, SplitLIs);
354 /// Wrapper Method to do all the necessary work when an Instruction is
355 /// deleted.
356 /// Optimizations should use this to make sure that deleted instructions
357 /// are always accounted for.
358 void deleteInstr(MachineInstr* MI) {
359 ErasedInstrs.insert(MI);
360 LIS->RemoveMachineInstrFromMaps(*MI);
361 MI->eraseFromParent();
364 /// Walk over function and initialize the DbgVRegToValues map.
365 void buildVRegToDbgValueMap(MachineFunction &MF);
367 /// Test whether, after merging, any DBG_VALUEs would refer to a
368 /// different value number than before merging, and whether this can
369 /// be resolved. If not, mark the DBG_VALUE as being undef.
370 void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
371 JoinVals &LHSVals, LiveRange &RHS,
372 JoinVals &RHSVals);
374 void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
375 LiveRange &RegRange, JoinVals &Vals2);
377 public:
378 static char ID; ///< Class identification, replacement for typeinfo
380 RegisterCoalescer() : MachineFunctionPass(ID) {
381 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
384 void getAnalysisUsage(AnalysisUsage &AU) const override;
386 void releaseMemory() override;
388 /// This is the pass entry point.
389 bool runOnMachineFunction(MachineFunction&) override;
391 /// Implement the dump method.
392 void print(raw_ostream &O, const Module* = nullptr) const override;
395 } // end anonymous namespace
397 char RegisterCoalescer::ID = 0;
399 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
401 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "register-coalescer",
402 "Register Coalescer", false, false)
403 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
404 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
405 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
406 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
407 INITIALIZE_PASS_END(RegisterCoalescer, "register-coalescer",
408 "Register Coalescer", false, false)
410 [[nodiscard]] static bool isMoveInstr(const TargetRegisterInfo &tri,
411 const MachineInstr *MI, Register &Src,
412 Register &Dst, unsigned &SrcSub,
413 unsigned &DstSub) {
414 if (MI->isCopy()) {
415 Dst = MI->getOperand(0).getReg();
416 DstSub = MI->getOperand(0).getSubReg();
417 Src = MI->getOperand(1).getReg();
418 SrcSub = MI->getOperand(1).getSubReg();
419 } else if (MI->isSubregToReg()) {
420 Dst = MI->getOperand(0).getReg();
421 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
422 MI->getOperand(3).getImm());
423 Src = MI->getOperand(2).getReg();
424 SrcSub = MI->getOperand(2).getSubReg();
425 } else
426 return false;
427 return true;
430 /// Return true if this block should be vacated by the coalescer to eliminate
431 /// branches. The important cases to handle in the coalescer are critical edges
432 /// split during phi elimination which contain only copies. Simple blocks that
433 /// contain non-branches should also be vacated, but this can be handled by an
434 /// earlier pass similar to early if-conversion.
435 static bool isSplitEdge(const MachineBasicBlock *MBB) {
436 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
437 return false;
439 for (const auto &MI : *MBB) {
440 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
441 return false;
443 return true;
446 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
447 SrcReg = DstReg = Register();
448 SrcIdx = DstIdx = 0;
449 NewRC = nullptr;
450 Flipped = CrossClass = false;
452 Register Src, Dst;
453 unsigned SrcSub = 0, DstSub = 0;
454 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
455 return false;
456 Partial = SrcSub || DstSub;
458 // If one register is a physreg, it must be Dst.
459 if (Src.isPhysical()) {
460 if (Dst.isPhysical())
461 return false;
462 std::swap(Src, Dst);
463 std::swap(SrcSub, DstSub);
464 Flipped = true;
467 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
469 if (Dst.isPhysical()) {
470 // Eliminate DstSub on a physreg.
471 if (DstSub) {
472 Dst = TRI.getSubReg(Dst, DstSub);
473 if (!Dst) return false;
474 DstSub = 0;
477 // Eliminate SrcSub by picking a corresponding Dst superregister.
478 if (SrcSub) {
479 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
480 if (!Dst) return false;
481 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
482 return false;
484 } else {
485 // Both registers are virtual.
486 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
487 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
489 // Both registers have subreg indices.
490 if (SrcSub && DstSub) {
491 // Copies between different sub-registers are never coalescable.
492 if (Src == Dst && SrcSub != DstSub)
493 return false;
495 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
496 SrcIdx, DstIdx);
497 if (!NewRC)
498 return false;
499 } else if (DstSub) {
500 // SrcReg will be merged with a sub-register of DstReg.
501 SrcIdx = DstSub;
502 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
503 } else if (SrcSub) {
504 // DstReg will be merged with a sub-register of SrcReg.
505 DstIdx = SrcSub;
506 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
507 } else {
508 // This is a straight copy without sub-registers.
509 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
512 // The combined constraint may be impossible to satisfy.
513 if (!NewRC)
514 return false;
516 // Prefer SrcReg to be a sub-register of DstReg.
517 // FIXME: Coalescer should support subregs symmetrically.
518 if (DstIdx && !SrcIdx) {
519 std::swap(Src, Dst);
520 std::swap(SrcIdx, DstIdx);
521 Flipped = !Flipped;
524 CrossClass = NewRC != DstRC || NewRC != SrcRC;
526 // Check our invariants
527 assert(Src.isVirtual() && "Src must be virtual");
528 assert(!(Dst.isPhysical() && DstSub) && "Cannot have a physical SubIdx");
529 SrcReg = Src;
530 DstReg = Dst;
531 return true;
534 bool CoalescerPair::flip() {
535 if (DstReg.isPhysical())
536 return false;
537 std::swap(SrcReg, DstReg);
538 std::swap(SrcIdx, DstIdx);
539 Flipped = !Flipped;
540 return true;
543 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
544 if (!MI)
545 return false;
546 Register Src, Dst;
547 unsigned SrcSub = 0, DstSub = 0;
548 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
549 return false;
551 // Find the virtual register that is SrcReg.
552 if (Dst == SrcReg) {
553 std::swap(Src, Dst);
554 std::swap(SrcSub, DstSub);
555 } else if (Src != SrcReg) {
556 return false;
559 // Now check that Dst matches DstReg.
560 if (DstReg.isPhysical()) {
561 if (!Dst.isPhysical())
562 return false;
563 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
564 // DstSub could be set for a physreg from INSERT_SUBREG.
565 if (DstSub)
566 Dst = TRI.getSubReg(Dst, DstSub);
567 // Full copy of Src.
568 if (!SrcSub)
569 return DstReg == Dst;
570 // This is a partial register copy. Check that the parts match.
571 return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
572 } else {
573 // DstReg is virtual.
574 if (DstReg != Dst)
575 return false;
576 // Registers match, do the subregisters line up?
577 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
578 TRI.composeSubRegIndices(DstIdx, DstSub);
582 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
583 AU.setPreservesCFG();
584 AU.addRequired<AAResultsWrapperPass>();
585 AU.addRequired<LiveIntervals>();
586 AU.addPreserved<LiveIntervals>();
587 AU.addPreserved<SlotIndexes>();
588 AU.addRequired<MachineLoopInfo>();
589 AU.addPreserved<MachineLoopInfo>();
590 AU.addPreservedID(MachineDominatorsID);
591 MachineFunctionPass::getAnalysisUsage(AU);
594 void RegisterCoalescer::eliminateDeadDefs(LiveRangeEdit *Edit) {
595 if (Edit) {
596 Edit->eliminateDeadDefs(DeadDefs);
597 return;
599 SmallVector<Register, 8> NewRegs;
600 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
601 nullptr, this).eliminateDeadDefs(DeadDefs);
604 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
605 // MI may be in WorkList. Make sure we don't visit it.
606 ErasedInstrs.insert(MI);
609 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
610 MachineInstr *CopyMI) {
611 assert(!CP.isPartial() && "This doesn't work for partial copies.");
612 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
614 LiveInterval &IntA =
615 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
616 LiveInterval &IntB =
617 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
618 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
620 // We have a non-trivially-coalescable copy with IntA being the source and
621 // IntB being the dest, thus this defines a value number in IntB. If the
622 // source value number (in IntA) is defined by a copy from B, see if we can
623 // merge these two pieces of B into a single value number, eliminating a copy.
624 // For example:
626 // A3 = B0
627 // ...
628 // B1 = A3 <- this copy
630 // In this case, B0 can be extended to where the B1 copy lives, allowing the
631 // B1 value number to be replaced with B0 (which simplifies the B
632 // liveinterval).
634 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
635 // the example above.
636 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
637 if (BS == IntB.end()) return false;
638 VNInfo *BValNo = BS->valno;
640 // Get the location that B is defined at. Two options: either this value has
641 // an unknown definition point or it is defined at CopyIdx. If unknown, we
642 // can't process it.
643 if (BValNo->def != CopyIdx) return false;
645 // AValNo is the value number in A that defines the copy, A3 in the example.
646 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
647 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
648 // The live segment might not exist after fun with physreg coalescing.
649 if (AS == IntA.end()) return false;
650 VNInfo *AValNo = AS->valno;
652 // If AValNo is defined as a copy from IntB, we can potentially process this.
653 // Get the instruction that defines this value number.
654 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
655 // Don't allow any partial copies, even if isCoalescable() allows them.
656 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
657 return false;
659 // Get the Segment in IntB that this value number starts with.
660 LiveInterval::iterator ValS =
661 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
662 if (ValS == IntB.end())
663 return false;
665 // Make sure that the end of the live segment is inside the same block as
666 // CopyMI.
667 MachineInstr *ValSEndInst =
668 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
669 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
670 return false;
672 // Okay, we now know that ValS ends in the same block that the CopyMI
673 // live-range starts. If there are no intervening live segments between them
674 // in IntB, we can merge them.
675 if (ValS+1 != BS) return false;
677 LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI));
679 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
680 // We are about to delete CopyMI, so need to remove it as the 'instruction
681 // that defines this value #'. Update the valnum with the new defining
682 // instruction #.
683 BValNo->def = FillerStart;
685 // Okay, we can merge them. We need to insert a new liverange:
686 // [ValS.end, BS.begin) of either value number, then we merge the
687 // two value numbers.
688 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
690 // Okay, merge "B1" into the same value number as "B0".
691 if (BValNo != ValS->valno)
692 IntB.MergeValueNumberInto(BValNo, ValS->valno);
694 // Do the same for the subregister segments.
695 for (LiveInterval::SubRange &S : IntB.subranges()) {
696 // Check for SubRange Segments of the form [1234r,1234d:0) which can be
697 // removed to prevent creating bogus SubRange Segments.
698 LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
699 if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
700 S.removeSegment(*SS, true);
701 continue;
703 // The subrange may have ended before FillerStart. If so, extend it.
704 if (!S.getVNInfoAt(FillerStart)) {
705 SlotIndex BBStart =
706 LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
707 S.extendInBlock(BBStart, FillerStart);
709 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
710 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
711 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
712 if (SubBValNo != SubValSNo)
713 S.MergeValueNumberInto(SubBValNo, SubValSNo);
716 LLVM_DEBUG(dbgs() << " result = " << IntB << '\n');
718 // If the source instruction was killing the source register before the
719 // merge, unset the isKill marker given the live range has been extended.
720 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), true);
721 if (UIdx != -1) {
722 ValSEndInst->getOperand(UIdx).setIsKill(false);
725 // Rewrite the copy.
726 CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
727 // If the copy instruction was killing the destination register or any
728 // subrange before the merge trim the live range.
729 bool RecomputeLiveRange = AS->end == CopyIdx;
730 if (!RecomputeLiveRange) {
731 for (LiveInterval::SubRange &S : IntA.subranges()) {
732 LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
733 if (SS != S.end() && SS->end == CopyIdx) {
734 RecomputeLiveRange = true;
735 break;
739 if (RecomputeLiveRange)
740 shrinkToUses(&IntA);
742 ++numExtends;
743 return true;
746 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
747 LiveInterval &IntB,
748 VNInfo *AValNo,
749 VNInfo *BValNo) {
750 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
751 // the PHI values.
752 if (LIS->hasPHIKill(IntA, AValNo))
753 return true;
755 for (LiveRange::Segment &ASeg : IntA.segments) {
756 if (ASeg.valno != AValNo) continue;
757 LiveInterval::iterator BI = llvm::upper_bound(IntB, ASeg.start);
758 if (BI != IntB.begin())
759 --BI;
760 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
761 if (BI->valno == BValNo)
762 continue;
763 if (BI->start <= ASeg.start && BI->end > ASeg.start)
764 return true;
765 if (BI->start > ASeg.start && BI->start < ASeg.end)
766 return true;
769 return false;
772 /// Copy segments with value number @p SrcValNo from liverange @p Src to live
773 /// range @Dst and use value number @p DstValNo there.
774 static std::pair<bool,bool>
775 addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src,
776 const VNInfo *SrcValNo) {
777 bool Changed = false;
778 bool MergedWithDead = false;
779 for (const LiveRange::Segment &S : Src.segments) {
780 if (S.valno != SrcValNo)
781 continue;
782 // This is adding a segment from Src that ends in a copy that is about
783 // to be removed. This segment is going to be merged with a pre-existing
784 // segment in Dst. This works, except in cases when the corresponding
785 // segment in Dst is dead. For example: adding [192r,208r:1) from Src
786 // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
787 // Recognized such cases, so that the segments can be shrunk.
788 LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
789 LiveRange::Segment &Merged = *Dst.addSegment(Added);
790 if (Merged.end.isDead())
791 MergedWithDead = true;
792 Changed = true;
794 return std::make_pair(Changed, MergedWithDead);
797 std::pair<bool,bool>
798 RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
799 MachineInstr *CopyMI) {
800 assert(!CP.isPhys());
802 LiveInterval &IntA =
803 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
804 LiveInterval &IntB =
805 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
807 // We found a non-trivially-coalescable copy with IntA being the source and
808 // IntB being the dest, thus this defines a value number in IntB. If the
809 // source value number (in IntA) is defined by a commutable instruction and
810 // its other operand is coalesced to the copy dest register, see if we can
811 // transform the copy into a noop by commuting the definition. For example,
813 // A3 = op A2 killed B0
814 // ...
815 // B1 = A3 <- this copy
816 // ...
817 // = op A3 <- more uses
819 // ==>
821 // B2 = op B0 killed A2
822 // ...
823 // B1 = B2 <- now an identity copy
824 // ...
825 // = op B2 <- more uses
827 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
828 // the example above.
829 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
830 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
831 assert(BValNo != nullptr && BValNo->def == CopyIdx);
833 // AValNo is the value number in A that defines the copy, A3 in the example.
834 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
835 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
836 if (AValNo->isPHIDef())
837 return { false, false };
838 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
839 if (!DefMI)
840 return { false, false };
841 if (!DefMI->isCommutable())
842 return { false, false };
843 // If DefMI is a two-address instruction then commuting it will change the
844 // destination register.
845 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg());
846 assert(DefIdx != -1);
847 unsigned UseOpIdx;
848 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
849 return { false, false };
851 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
852 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
853 // passed to the method. That _other_ operand is chosen by
854 // the findCommutedOpIndices() method.
856 // That is obviously an area for improvement in case of instructions having
857 // more than 2 operands. For example, if some instruction has 3 commutable
858 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
859 // op#2<->op#3) of commute transformation should be considered/tried here.
860 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
861 if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
862 return { false, false };
864 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
865 Register NewReg = NewDstMO.getReg();
866 if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
867 return { false, false };
869 // Make sure there are no other definitions of IntB that would reach the
870 // uses which the new definition can reach.
871 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
872 return { false, false };
874 // If some of the uses of IntA.reg is already coalesced away, return false.
875 // It's not possible to determine whether it's safe to perform the coalescing.
876 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg())) {
877 MachineInstr *UseMI = MO.getParent();
878 unsigned OpNo = &MO - &UseMI->getOperand(0);
879 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
880 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
881 if (US == IntA.end() || US->valno != AValNo)
882 continue;
883 // If this use is tied to a def, we can't rewrite the register.
884 if (UseMI->isRegTiedToDefOperand(OpNo))
885 return { false, false };
888 LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
889 << *DefMI);
891 // At this point we have decided that it is legal to do this
892 // transformation. Start by commuting the instruction.
893 MachineBasicBlock *MBB = DefMI->getParent();
894 MachineInstr *NewMI =
895 TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
896 if (!NewMI)
897 return { false, false };
898 if (IntA.reg().isVirtual() && IntB.reg().isVirtual() &&
899 !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
900 return { false, false };
901 if (NewMI != DefMI) {
902 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
903 MachineBasicBlock::iterator Pos = DefMI;
904 MBB->insert(Pos, NewMI);
905 MBB->erase(DefMI);
908 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
909 // A = or A, B
910 // ...
911 // B = A
912 // ...
913 // C = killed A
914 // ...
915 // = B
917 // Update uses of IntA of the specific Val# with IntB.
918 for (MachineOperand &UseMO :
919 llvm::make_early_inc_range(MRI->use_operands(IntA.reg()))) {
920 if (UseMO.isUndef())
921 continue;
922 MachineInstr *UseMI = UseMO.getParent();
923 if (UseMI->isDebugInstr()) {
924 // FIXME These don't have an instruction index. Not clear we have enough
925 // info to decide whether to do this replacement or not. For now do it.
926 UseMO.setReg(NewReg);
927 continue;
929 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
930 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
931 assert(US != IntA.end() && "Use must be live");
932 if (US->valno != AValNo)
933 continue;
934 // Kill flags are no longer accurate. They are recomputed after RA.
935 UseMO.setIsKill(false);
936 if (NewReg.isPhysical())
937 UseMO.substPhysReg(NewReg, *TRI);
938 else
939 UseMO.setReg(NewReg);
940 if (UseMI == CopyMI)
941 continue;
942 if (!UseMI->isCopy())
943 continue;
944 if (UseMI->getOperand(0).getReg() != IntB.reg() ||
945 UseMI->getOperand(0).getSubReg())
946 continue;
948 // This copy will become a noop. If it's defining a new val#, merge it into
949 // BValNo.
950 SlotIndex DefIdx = UseIdx.getRegSlot();
951 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
952 if (!DVNI)
953 continue;
954 LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
955 assert(DVNI->def == DefIdx);
956 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
957 for (LiveInterval::SubRange &S : IntB.subranges()) {
958 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
959 if (!SubDVNI)
960 continue;
961 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
962 assert(SubBValNo->def == CopyIdx);
963 S.MergeValueNumberInto(SubDVNI, SubBValNo);
966 deleteInstr(UseMI);
969 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
970 // is updated.
971 bool ShrinkB = false;
972 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
973 if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
974 if (!IntA.hasSubRanges()) {
975 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg());
976 IntA.createSubRangeFrom(Allocator, Mask, IntA);
977 } else if (!IntB.hasSubRanges()) {
978 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntB.reg());
979 IntB.createSubRangeFrom(Allocator, Mask, IntB);
981 SlotIndex AIdx = CopyIdx.getRegSlot(true);
982 LaneBitmask MaskA;
983 const SlotIndexes &Indexes = *LIS->getSlotIndexes();
984 for (LiveInterval::SubRange &SA : IntA.subranges()) {
985 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
986 // Even if we are dealing with a full copy, some lanes can
987 // still be undefined.
988 // E.g.,
989 // undef A.subLow = ...
990 // B = COPY A <== A.subHigh is undefined here and does
991 // not have a value number.
992 if (!ASubValNo)
993 continue;
994 MaskA |= SA.LaneMask;
996 IntB.refineSubRanges(
997 Allocator, SA.LaneMask,
998 [&Allocator, &SA, CopyIdx, ASubValNo,
999 &ShrinkB](LiveInterval::SubRange &SR) {
1000 VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
1001 : SR.getVNInfoAt(CopyIdx);
1002 assert(BSubValNo != nullptr);
1003 auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
1004 ShrinkB |= P.second;
1005 if (P.first)
1006 BSubValNo->def = ASubValNo->def;
1008 Indexes, *TRI);
1010 // Go over all subranges of IntB that have not been covered by IntA,
1011 // and delete the segments starting at CopyIdx. This can happen if
1012 // IntA has undef lanes that are defined in IntB.
1013 for (LiveInterval::SubRange &SB : IntB.subranges()) {
1014 if ((SB.LaneMask & MaskA).any())
1015 continue;
1016 if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
1017 if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
1018 SB.removeSegment(*S, true);
1022 BValNo->def = AValNo->def;
1023 auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
1024 ShrinkB |= P.second;
1025 LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
1027 LIS->removeVRegDefAt(IntA, AValNo->def);
1029 LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
1030 ++numCommutes;
1031 return { true, ShrinkB };
1034 /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
1035 /// predecessor of BB2, and if B is not redefined on the way from A = B
1036 /// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
1037 /// execution goes through the path from BB0 to BB2. We may move B = A
1038 /// to the predecessor without such reversed copy.
1039 /// So we will transform the program from:
1040 /// BB0:
1041 /// A = B; BB1:
1042 /// ... ...
1043 /// / \ /
1044 /// BB2:
1045 /// ...
1046 /// B = A;
1048 /// to:
1050 /// BB0: BB1:
1051 /// A = B; ...
1052 /// ... B = A;
1053 /// / \ /
1054 /// BB2:
1055 /// ...
1057 /// A special case is when BB0 and BB2 are the same BB which is the only
1058 /// BB in a loop:
1059 /// BB1:
1060 /// ...
1061 /// BB0/BB2: ----
1062 /// B = A; |
1063 /// ... |
1064 /// A = B; |
1065 /// |-------
1066 /// |
1067 /// We may hoist B = A from BB0/BB2 to BB1.
1069 /// The major preconditions for correctness to remove such partial
1070 /// redundancy include:
1071 /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
1072 /// the PHI is defined by the reversed copy A = B in BB0.
1073 /// 2. No B is referenced from the start of BB2 to B = A.
1074 /// 3. No B is defined from A = B to the end of BB0.
1075 /// 4. BB1 has only one successor.
1077 /// 2 and 4 implicitly ensure B is not live at the end of BB1.
1078 /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
1079 /// colder place, which not only prevent endless loop, but also make sure
1080 /// the movement of copy is beneficial.
1081 bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
1082 MachineInstr &CopyMI) {
1083 assert(!CP.isPhys());
1084 if (!CopyMI.isFullCopy())
1085 return false;
1087 MachineBasicBlock &MBB = *CopyMI.getParent();
1088 // If this block is the target of an invoke/inlineasm_br, moving the copy into
1089 // the predecessor is tricker, and we don't handle it.
1090 if (MBB.isEHPad() || MBB.isInlineAsmBrIndirectTarget())
1091 return false;
1093 if (MBB.pred_size() != 2)
1094 return false;
1096 LiveInterval &IntA =
1097 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
1098 LiveInterval &IntB =
1099 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
1101 // A is defined by PHI at the entry of MBB.
1102 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
1103 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
1104 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
1105 if (!AValNo->isPHIDef())
1106 return false;
1108 // No B is referenced before CopyMI in MBB.
1109 if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
1110 return false;
1112 // MBB has two predecessors: one contains A = B so no copy will be inserted
1113 // for it. The other one will have a copy moved from MBB.
1114 bool FoundReverseCopy = false;
1115 MachineBasicBlock *CopyLeftBB = nullptr;
1116 for (MachineBasicBlock *Pred : MBB.predecessors()) {
1117 VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
1118 MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
1119 if (!DefMI || !DefMI->isFullCopy()) {
1120 CopyLeftBB = Pred;
1121 continue;
1123 // Check DefMI is a reverse copy and it is in BB Pred.
1124 if (DefMI->getOperand(0).getReg() != IntA.reg() ||
1125 DefMI->getOperand(1).getReg() != IntB.reg() ||
1126 DefMI->getParent() != Pred) {
1127 CopyLeftBB = Pred;
1128 continue;
1130 // If there is any other def of B after DefMI and before the end of Pred,
1131 // we need to keep the copy of B = A at the end of Pred if we remove
1132 // B = A from MBB.
1133 bool ValB_Changed = false;
1134 for (auto *VNI : IntB.valnos) {
1135 if (VNI->isUnused())
1136 continue;
1137 if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
1138 ValB_Changed = true;
1139 break;
1142 if (ValB_Changed) {
1143 CopyLeftBB = Pred;
1144 continue;
1146 FoundReverseCopy = true;
1149 // If no reverse copy is found in predecessors, nothing to do.
1150 if (!FoundReverseCopy)
1151 return false;
1153 // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
1154 // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
1155 // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
1156 // update IntA/IntB.
1158 // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
1159 // MBB is hotter than CopyLeftBB.
1160 if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
1161 return false;
1163 // Now (almost sure it's) ok to move copy.
1164 if (CopyLeftBB) {
1165 // Position in CopyLeftBB where we should insert new copy.
1166 auto InsPos = CopyLeftBB->getFirstTerminator();
1168 // Make sure that B isn't referenced in the terminators (if any) at the end
1169 // of the predecessor since we're about to insert a new definition of B
1170 // before them.
1171 if (InsPos != CopyLeftBB->end()) {
1172 SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
1173 if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
1174 return false;
1177 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
1178 << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
1180 // Insert new copy to CopyLeftBB.
1181 MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1182 TII->get(TargetOpcode::COPY), IntB.reg())
1183 .addReg(IntA.reg());
1184 SlotIndex NewCopyIdx =
1185 LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1186 IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1187 for (LiveInterval::SubRange &SR : IntB.subranges())
1188 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1190 // If the newly created Instruction has an address of an instruction that was
1191 // deleted before (object recycled by the allocator) it needs to be removed from
1192 // the deleted list.
1193 ErasedInstrs.erase(NewCopyMI);
1194 } else {
1195 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
1196 << printMBBReference(MBB) << '\t' << CopyMI);
1199 // Remove CopyMI.
1200 // Note: This is fine to remove the copy before updating the live-ranges.
1201 // While updating the live-ranges, we only look at slot indices and
1202 // never go back to the instruction.
1203 // Mark instructions as deleted.
1204 deleteInstr(&CopyMI);
1206 // Update the liveness.
1207 SmallVector<SlotIndex, 8> EndPoints;
1208 VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
1209 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
1210 &EndPoints);
1211 BValNo->markUnused();
1212 // Extend IntB to the EndPoints of its original live interval.
1213 LIS->extendToIndices(IntB, EndPoints);
1215 // Now, do the same for its subranges.
1216 for (LiveInterval::SubRange &SR : IntB.subranges()) {
1217 EndPoints.clear();
1218 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1219 assert(BValNo && "All sublanes should be live");
1220 LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
1221 BValNo->markUnused();
1222 // We can have a situation where the result of the original copy is live,
1223 // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
1224 // the copy appear as an endpoint from pruneValue(), but we don't want it
1225 // to because the copy has been removed. We can go ahead and remove that
1226 // endpoint; there is no other situation here that there could be a use at
1227 // the same place as we know that the copy is a full copy.
1228 for (unsigned I = 0; I != EndPoints.size(); ) {
1229 if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
1230 EndPoints[I] = EndPoints.back();
1231 EndPoints.pop_back();
1232 continue;
1234 ++I;
1236 SmallVector<SlotIndex, 8> Undefs;
1237 IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
1238 *LIS->getSlotIndexes());
1239 LIS->extendToIndices(SR, EndPoints, Undefs);
1241 // If any dead defs were extended, truncate them.
1242 shrinkToUses(&IntB);
1244 // Finally, update the live-range of IntA.
1245 shrinkToUses(&IntA);
1246 return true;
1249 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
1250 /// defining a subregister.
1251 static bool definesFullReg(const MachineInstr &MI, Register Reg) {
1252 assert(!Reg.isPhysical() && "This code cannot handle physreg aliasing");
1254 for (const MachineOperand &Op : MI.all_defs()) {
1255 if (Op.getReg() != Reg)
1256 continue;
1257 // Return true if we define the full register or don't care about the value
1258 // inside other subregisters.
1259 if (Op.getSubReg() == 0 || Op.isUndef())
1260 return true;
1262 return false;
1265 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
1266 MachineInstr *CopyMI,
1267 bool &IsDefCopy) {
1268 IsDefCopy = false;
1269 Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1270 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1271 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1272 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1273 if (SrcReg.isPhysical())
1274 return false;
1276 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1277 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1278 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1279 if (!ValNo)
1280 return false;
1281 if (ValNo->isPHIDef() || ValNo->isUnused())
1282 return false;
1283 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
1284 if (!DefMI)
1285 return false;
1286 if (DefMI->isCopyLike()) {
1287 IsDefCopy = true;
1288 return false;
1290 if (!TII->isAsCheapAsAMove(*DefMI))
1291 return false;
1293 SmallVector<Register, 8> NewRegs;
1294 LiveRangeEdit Edit(&SrcInt, NewRegs, *MF, *LIS, nullptr, this);
1295 if (!Edit.checkRematerializable(ValNo, DefMI))
1296 return false;
1298 if (!definesFullReg(*DefMI, SrcReg))
1299 return false;
1300 bool SawStore = false;
1301 if (!DefMI->isSafeToMove(AA, SawStore))
1302 return false;
1303 const MCInstrDesc &MCID = DefMI->getDesc();
1304 if (MCID.getNumDefs() != 1)
1305 return false;
1306 // Only support subregister destinations when the def is read-undef.
1307 MachineOperand &DstOperand = CopyMI->getOperand(0);
1308 Register CopyDstReg = DstOperand.getReg();
1309 if (DstOperand.getSubReg() && !DstOperand.isUndef())
1310 return false;
1312 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1313 // the register substantially (beyond both source and dest size). This is bad
1314 // for performance since it can cascade through a function, introducing many
1315 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1316 // around after a few subreg copies).
1317 if (SrcIdx && DstIdx)
1318 return false;
1320 [[maybe_unused]] const unsigned DefSubIdx = DefMI->getOperand(0).getSubReg();
1321 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
1322 if (!DefMI->isImplicitDef()) {
1323 if (DstReg.isPhysical()) {
1324 Register NewDstReg = DstReg;
1326 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
1327 DefMI->getOperand(0).getSubReg());
1328 if (NewDstIdx)
1329 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1331 // Finally, make sure that the physical subregister that will be
1332 // constructed later is permitted for the instruction.
1333 if (!DefRC->contains(NewDstReg))
1334 return false;
1335 } else {
1336 // Theoretically, some stack frame reference could exist. Just make sure
1337 // it hasn't actually happened.
1338 assert(DstReg.isVirtual() &&
1339 "Only expect to deal with virtual or physical registers");
1343 LiveRangeEdit::Remat RM(ValNo);
1344 RM.OrigMI = DefMI;
1345 if (!Edit.canRematerializeAt(RM, ValNo, CopyIdx, true))
1346 return false;
1348 DebugLoc DL = CopyMI->getDebugLoc();
1349 MachineBasicBlock *MBB = CopyMI->getParent();
1350 MachineBasicBlock::iterator MII =
1351 std::next(MachineBasicBlock::iterator(CopyMI));
1352 Edit.rematerializeAt(*MBB, MII, DstReg, RM, *TRI, false, SrcIdx, CopyMI);
1353 MachineInstr &NewMI = *std::prev(MII);
1354 NewMI.setDebugLoc(DL);
1356 // In a situation like the following:
1357 // %0:subreg = instr ; DefMI, subreg = DstIdx
1358 // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
1359 // instead of widening %1 to the register class of %0 simply do:
1360 // %1 = instr
1361 const TargetRegisterClass *NewRC = CP.getNewRC();
1362 if (DstIdx != 0) {
1363 MachineOperand &DefMO = NewMI.getOperand(0);
1364 if (DefMO.getSubReg() == DstIdx) {
1365 assert(SrcIdx == 0 && CP.isFlipped()
1366 && "Shouldn't have SrcIdx+DstIdx at this point");
1367 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1368 const TargetRegisterClass *CommonRC =
1369 TRI->getCommonSubClass(DefRC, DstRC);
1370 if (CommonRC != nullptr) {
1371 NewRC = CommonRC;
1373 // Instruction might contain "undef %0:subreg" as use operand:
1374 // %0:subreg = instr op_1, ..., op_N, undef %0:subreg, op_N+2, ...
1376 // Need to check all operands.
1377 for (MachineOperand &MO : NewMI.operands()) {
1378 if (MO.isReg() && MO.getReg() == DstReg && MO.getSubReg() == DstIdx) {
1379 MO.setSubReg(0);
1383 DstIdx = 0;
1384 DefMO.setIsUndef(false); // Only subregs can have def+undef.
1389 // CopyMI may have implicit operands, save them so that we can transfer them
1390 // over to the newly materialized instruction after CopyMI is removed.
1391 SmallVector<MachineOperand, 4> ImplicitOps;
1392 ImplicitOps.reserve(CopyMI->getNumOperands() -
1393 CopyMI->getDesc().getNumOperands());
1394 for (unsigned I = CopyMI->getDesc().getNumOperands(),
1395 E = CopyMI->getNumOperands();
1396 I != E; ++I) {
1397 MachineOperand &MO = CopyMI->getOperand(I);
1398 if (MO.isReg()) {
1399 assert(MO.isImplicit() && "No explicit operands after implicit operands.");
1400 assert((MO.getReg().isPhysical() ||
1401 (MO.getSubReg() == 0 && MO.getReg() == DstOperand.getReg())) &&
1402 "unexpected implicit virtual register def");
1403 ImplicitOps.push_back(MO);
1407 CopyMI->eraseFromParent();
1408 ErasedInstrs.insert(CopyMI);
1410 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1411 // We need to remember these so we can add intervals once we insert
1412 // NewMI into SlotIndexes.
1414 // We also expect to have tied implicit-defs of super registers originating
1415 // from SUBREG_TO_REG, such as:
1416 // $edi = MOV32r0 implicit-def dead $eflags, implicit-def $rdi
1417 // undef %0.sub_32bit = MOV32r0 implicit-def dead $eflags, implicit-def %0
1419 // The implicit-def of the super register may have been reduced to
1420 // subregisters depending on the uses.
1422 bool NewMIDefinesFullReg = false;
1424 SmallVector<MCRegister, 4> NewMIImplDefs;
1425 for (unsigned i = NewMI.getDesc().getNumOperands(),
1426 e = NewMI.getNumOperands();
1427 i != e; ++i) {
1428 MachineOperand &MO = NewMI.getOperand(i);
1429 if (MO.isReg() && MO.isDef()) {
1430 assert(MO.isImplicit());
1431 if (MO.getReg().isPhysical()) {
1432 if (MO.getReg() == DstReg)
1433 NewMIDefinesFullReg = true;
1435 assert(MO.isImplicit() && MO.getReg().isPhysical() &&
1436 (MO.isDead() ||
1437 (DefSubIdx &&
1438 ((TRI->getSubReg(MO.getReg(), DefSubIdx) ==
1439 MCRegister((unsigned)NewMI.getOperand(0).getReg())) ||
1440 TRI->isSubRegisterEq(NewMI.getOperand(0).getReg(),
1441 MO.getReg())))));
1442 NewMIImplDefs.push_back(MO.getReg().asMCReg());
1443 } else {
1444 assert(MO.getReg() == NewMI.getOperand(0).getReg());
1446 // We're only expecting another def of the main output, so the range
1447 // should get updated with the regular output range.
1449 // FIXME: The range updating below probably needs updating to look at
1450 // the super register if subranges are tracked.
1451 assert(!MRI->shouldTrackSubRegLiveness(DstReg) &&
1452 "subrange update for implicit-def of super register may not be "
1453 "properly handled");
1458 if (DstReg.isVirtual()) {
1459 unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1461 if (DefRC != nullptr) {
1462 if (NewIdx)
1463 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1464 else
1465 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1466 assert(NewRC && "subreg chosen for remat incompatible with instruction");
1468 // Remap subranges to new lanemask and change register class.
1469 LiveInterval &DstInt = LIS->getInterval(DstReg);
1470 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1471 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1473 MRI->setRegClass(DstReg, NewRC);
1475 // Update machine operands and add flags.
1476 updateRegDefsUses(DstReg, DstReg, DstIdx);
1477 NewMI.getOperand(0).setSubReg(NewIdx);
1478 // updateRegDefUses can add an "undef" flag to the definition, since
1479 // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
1480 // sure that "undef" is not set.
1481 if (NewIdx == 0)
1482 NewMI.getOperand(0).setIsUndef(false);
1483 // Add dead subregister definitions if we are defining the whole register
1484 // but only part of it is live.
1485 // This could happen if the rematerialization instruction is rematerializing
1486 // more than actually is used in the register.
1487 // An example would be:
1488 // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1489 // ; Copying only part of the register here, but the rest is undef.
1490 // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
1491 // ==>
1492 // ; Materialize all the constants but only using one
1493 // %2 = LOAD_CONSTANTS 5, 8
1495 // at this point for the part that wasn't defined before we could have
1496 // subranges missing the definition.
1497 if (NewIdx == 0 && DstInt.hasSubRanges()) {
1498 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1499 SlotIndex DefIndex =
1500 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1501 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
1502 VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
1503 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1504 if (!SR.liveAt(DefIndex))
1505 SR.createDeadDef(DefIndex, Alloc);
1506 MaxMask &= ~SR.LaneMask;
1508 if (MaxMask.any()) {
1509 LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
1510 SR->createDeadDef(DefIndex, Alloc);
1514 // Make sure that the subrange for resultant undef is removed
1515 // For example:
1516 // %1:sub1<def,read-undef> = LOAD CONSTANT 1
1517 // %2 = COPY %1
1518 // ==>
1519 // %2:sub1<def, read-undef> = LOAD CONSTANT 1
1520 // ; Correct but need to remove the subrange for %2:sub0
1521 // ; as it is now undef
1522 if (NewIdx != 0 && DstInt.hasSubRanges()) {
1523 // The affected subregister segments can be removed.
1524 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1525 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
1526 bool UpdatedSubRanges = false;
1527 SlotIndex DefIndex =
1528 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1529 VNInfo::Allocator &Alloc = LIS->getVNInfoAllocator();
1530 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1531 if ((SR.LaneMask & DstMask).none()) {
1532 LLVM_DEBUG(dbgs()
1533 << "Removing undefined SubRange "
1534 << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
1536 if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
1537 // VNI is in ValNo - remove any segments in this SubRange that have
1538 // this ValNo
1539 SR.removeValNo(RmValNo);
1542 // We may not have a defined value at this point, but still need to
1543 // clear out any empty subranges tentatively created by
1544 // updateRegDefUses. The original subrange def may have only undefed
1545 // some lanes.
1546 UpdatedSubRanges = true;
1547 } else {
1548 // We know that this lane is defined by this instruction,
1549 // but at this point it may be empty because it is not used by
1550 // anything. This happens when updateRegDefUses adds the missing
1551 // lanes. Assign that lane a dead def so that the interferences
1552 // are properly modeled.
1553 if (SR.empty())
1554 SR.createDeadDef(DefIndex, Alloc);
1557 if (UpdatedSubRanges)
1558 DstInt.removeEmptySubRanges();
1560 } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1561 // The New instruction may be defining a sub-register of what's actually
1562 // been asked for. If so it must implicitly define the whole thing.
1563 assert(DstReg.isPhysical() &&
1564 "Only expect virtual or physical registers in remat");
1565 NewMI.getOperand(0).setIsDead(true);
1567 if (!NewMIDefinesFullReg) {
1568 NewMI.addOperand(MachineOperand::CreateReg(
1569 CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1572 // Record small dead def live-ranges for all the subregisters
1573 // of the destination register.
1574 // Otherwise, variables that live through may miss some
1575 // interferences, thus creating invalid allocation.
1576 // E.g., i386 code:
1577 // %1 = somedef ; %1 GR8
1578 // %2 = remat ; %2 GR32
1579 // CL = COPY %2.sub_8bit
1580 // = somedef %1 ; %1 GR8
1581 // =>
1582 // %1 = somedef ; %1 GR8
1583 // dead ECX = remat ; implicit-def CL
1584 // = somedef %1 ; %1 GR8
1585 // %1 will see the interferences with CL but not with CH since
1586 // no live-ranges would have been created for ECX.
1587 // Fix that!
1588 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1589 for (MCRegUnit Unit : TRI->regunits(NewMI.getOperand(0).getReg()))
1590 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1591 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1594 if (NewMI.getOperand(0).getSubReg())
1595 NewMI.getOperand(0).setIsUndef();
1597 // Transfer over implicit operands to the rematerialized instruction.
1598 for (MachineOperand &MO : ImplicitOps)
1599 NewMI.addOperand(MO);
1601 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1602 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1603 MCRegister Reg = NewMIImplDefs[i];
1604 for (MCRegUnit Unit : TRI->regunits(Reg))
1605 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1606 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1609 LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
1610 ++NumReMats;
1612 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1613 // to describe DstReg instead.
1614 if (MRI->use_nodbg_empty(SrcReg)) {
1615 for (MachineOperand &UseMO :
1616 llvm::make_early_inc_range(MRI->use_operands(SrcReg))) {
1617 MachineInstr *UseMI = UseMO.getParent();
1618 if (UseMI->isDebugInstr()) {
1619 if (DstReg.isPhysical())
1620 UseMO.substPhysReg(DstReg, *TRI);
1621 else
1622 UseMO.setReg(DstReg);
1623 // Move the debug value directly after the def of the rematerialized
1624 // value in DstReg.
1625 MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
1626 LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1631 if (ToBeUpdated.count(SrcReg))
1632 return true;
1634 unsigned NumCopyUses = 0;
1635 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
1636 if (UseMO.getParent()->isCopyLike())
1637 NumCopyUses++;
1639 if (NumCopyUses < LateRematUpdateThreshold) {
1640 // The source interval can become smaller because we removed a use.
1641 shrinkToUses(&SrcInt, &DeadDefs);
1642 if (!DeadDefs.empty())
1643 eliminateDeadDefs(&Edit);
1644 } else {
1645 ToBeUpdated.insert(SrcReg);
1647 return true;
1650 MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1651 // ProcessImplicitDefs may leave some copies of <undef> values, it only
1652 // removes local variables. When we have a copy like:
1654 // %1 = COPY undef %2
1656 // We delete the copy and remove the corresponding value number from %1.
1657 // Any uses of that value number are marked as <undef>.
1659 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1660 // CoalescerPair may have a new register class with adjusted subreg indices
1661 // at this point.
1662 Register SrcReg, DstReg;
1663 unsigned SrcSubIdx = 0, DstSubIdx = 0;
1664 if(!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1665 return nullptr;
1667 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1668 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1669 // CopyMI is undef iff SrcReg is not live before the instruction.
1670 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1671 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1672 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1673 if ((SR.LaneMask & SrcMask).none())
1674 continue;
1675 if (SR.liveAt(Idx))
1676 return nullptr;
1678 } else if (SrcLI.liveAt(Idx))
1679 return nullptr;
1681 // If the undef copy defines a live-out value (i.e. an input to a PHI def),
1682 // then replace it with an IMPLICIT_DEF.
1683 LiveInterval &DstLI = LIS->getInterval(DstReg);
1684 SlotIndex RegIndex = Idx.getRegSlot();
1685 LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
1686 assert(Seg != nullptr && "No segment for defining instruction");
1687 VNInfo *V = DstLI.getVNInfoAt(Seg->end);
1689 // The source interval may also have been on an undef use, in which case the
1690 // copy introduced a live value.
1691 if (((V && V->isPHIDef()) || (!V && !DstLI.liveAt(Idx)))) {
1692 CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1693 for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
1694 MachineOperand &MO = CopyMI->getOperand(i-1);
1695 if (MO.isReg() && MO.isUse())
1696 CopyMI->removeOperand(i-1);
1698 LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
1699 "implicit def\n");
1700 return CopyMI;
1703 // Remove any DstReg segments starting at the instruction.
1704 LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1706 // Remove value or merge with previous one in case of a subregister def.
1707 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1708 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1709 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1711 // The affected subregister segments can be removed.
1712 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1713 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1714 if ((SR.LaneMask & DstMask).none())
1715 continue;
1717 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1718 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1719 SR.removeValNo(SVNI);
1721 DstLI.removeEmptySubRanges();
1722 } else
1723 LIS->removeVRegDefAt(DstLI, RegIndex);
1725 // Mark uses as undef.
1726 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1727 if (MO.isDef() /*|| MO.isUndef()*/)
1728 continue;
1729 const MachineInstr &MI = *MO.getParent();
1730 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1731 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1732 bool isLive;
1733 if (!UseMask.all() && DstLI.hasSubRanges()) {
1734 isLive = false;
1735 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1736 if ((SR.LaneMask & UseMask).none())
1737 continue;
1738 if (SR.liveAt(UseIdx)) {
1739 isLive = true;
1740 break;
1743 } else
1744 isLive = DstLI.liveAt(UseIdx);
1745 if (isLive)
1746 continue;
1747 MO.setIsUndef(true);
1748 LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1751 // A def of a subregister may be a use of the other subregisters, so
1752 // deleting a def of a subregister may also remove uses. Since CopyMI
1753 // is still part of the function (but about to be erased), mark all
1754 // defs of DstReg in it as <undef>, so that shrinkToUses would
1755 // ignore them.
1756 for (MachineOperand &MO : CopyMI->all_defs())
1757 if (MO.getReg() == DstReg)
1758 MO.setIsUndef(true);
1759 LIS->shrinkToUses(&DstLI);
1761 return CopyMI;
1764 void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1765 MachineOperand &MO, unsigned SubRegIdx) {
1766 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1767 if (MO.isDef())
1768 Mask = ~Mask;
1769 bool IsUndef = true;
1770 for (const LiveInterval::SubRange &S : Int.subranges()) {
1771 if ((S.LaneMask & Mask).none())
1772 continue;
1773 if (S.liveAt(UseIdx)) {
1774 IsUndef = false;
1775 break;
1778 if (IsUndef) {
1779 MO.setIsUndef(true);
1780 // We found out some subregister use is actually reading an undefined
1781 // value. In some cases the whole vreg has become undefined at this
1782 // point so we have to potentially shrink the main range if the
1783 // use was ending a live segment there.
1784 LiveQueryResult Q = Int.Query(UseIdx);
1785 if (Q.valueOut() == nullptr)
1786 ShrinkMainRange = true;
1790 void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
1791 unsigned SubIdx) {
1792 bool DstIsPhys = DstReg.isPhysical();
1793 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1795 if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
1796 for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
1797 unsigned SubReg = MO.getSubReg();
1798 if (SubReg == 0 || MO.isUndef())
1799 continue;
1800 MachineInstr &MI = *MO.getParent();
1801 if (MI.isDebugInstr())
1802 continue;
1803 SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
1804 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1808 SmallPtrSet<MachineInstr*, 8> Visited;
1809 for (MachineRegisterInfo::reg_instr_iterator
1810 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1811 I != E; ) {
1812 MachineInstr *UseMI = &*(I++);
1814 // Each instruction can only be rewritten once because sub-register
1815 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1816 // the UseMI operands removes them from the SrcReg use-def chain, but when
1817 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1818 // operands mentioning the virtual register.
1819 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1820 continue;
1822 SmallVector<unsigned,8> Ops;
1823 bool Reads, Writes;
1824 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1826 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1827 // because SrcReg is a sub-register.
1828 if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
1829 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1831 // Replace SrcReg with DstReg in all UseMI operands.
1832 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1833 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1835 // Adjust <undef> flags in case of sub-register joins. We don't want to
1836 // turn a full def into a read-modify-write sub-register def and vice
1837 // versa.
1838 if (SubIdx && MO.isDef())
1839 MO.setIsUndef(!Reads);
1841 // A subreg use of a partially undef (super) register may be a complete
1842 // undef use now and then has to be marked that way.
1843 if (MO.isUse() && !DstIsPhys) {
1844 unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
1845 if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
1846 if (!DstInt->hasSubRanges()) {
1847 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1848 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
1849 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1850 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1851 DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1852 // The unused lanes are just empty live-ranges at this point.
1853 // It is the caller responsibility to set the proper
1854 // dead segments if there is an actual dead def of the
1855 // unused lanes. This may happen with rematerialization.
1856 DstInt->createSubRange(Allocator, UnusedLanes);
1858 SlotIndex MIIdx = UseMI->isDebugInstr()
1859 ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
1860 : LIS->getInstructionIndex(*UseMI);
1861 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1862 addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
1866 if (DstIsPhys)
1867 MO.substPhysReg(DstReg, *TRI);
1868 else
1869 MO.substVirtReg(DstReg, SubIdx, *TRI);
1872 LLVM_DEBUG({
1873 dbgs() << "\t\tupdated: ";
1874 if (!UseMI->isDebugInstr())
1875 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
1876 dbgs() << *UseMI;
1881 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1882 // Always join simple intervals that are defined by a single copy from a
1883 // reserved register. This doesn't increase register pressure, so it is
1884 // always beneficial.
1885 if (!MRI->isReserved(CP.getDstReg())) {
1886 LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1887 return false;
1890 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1891 if (JoinVInt.containsOneValue())
1892 return true;
1894 LLVM_DEBUG(
1895 dbgs() << "\tCannot join complex intervals into reserved register.\n");
1896 return false;
1899 bool RegisterCoalescer::copyValueUndefInPredecessors(
1900 LiveRange &S, const MachineBasicBlock *MBB, LiveQueryResult SLRQ) {
1901 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
1902 SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
1903 if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
1904 // If this is a self loop, we may be reading the same value.
1905 if (V->id != SLRQ.valueOutOrDead()->id)
1906 return false;
1910 return true;
1913 void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
1914 Register Reg,
1915 LaneBitmask PrunedLanes) {
1916 // If we had other instructions in the segment reading the undef sublane
1917 // value, we need to mark them with undef.
1918 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
1919 unsigned SubRegIdx = MO.getSubReg();
1920 if (SubRegIdx == 0 || MO.isUndef())
1921 continue;
1923 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1924 SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
1925 for (LiveInterval::SubRange &S : LI.subranges()) {
1926 if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
1927 MO.setIsUndef();
1928 break;
1933 LI.removeEmptySubRanges();
1935 // A def of a subregister may be a use of other register lanes. Replacing
1936 // such a def with a def of a different register will eliminate the use,
1937 // and may cause the recorded live range to be larger than the actual
1938 // liveness in the program IR.
1939 LIS->shrinkToUses(&LI);
1942 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1943 Again = false;
1944 LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
1946 CoalescerPair CP(*TRI);
1947 if (!CP.setRegisters(CopyMI)) {
1948 LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
1949 return false;
1952 if (CP.getNewRC()) {
1953 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1954 auto DstRC = MRI->getRegClass(CP.getDstReg());
1955 unsigned SrcIdx = CP.getSrcIdx();
1956 unsigned DstIdx = CP.getDstIdx();
1957 if (CP.isFlipped()) {
1958 std::swap(SrcIdx, DstIdx);
1959 std::swap(SrcRC, DstRC);
1961 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1962 CP.getNewRC(), *LIS)) {
1963 LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1964 return false;
1968 // Dead code elimination. This really should be handled by MachineDCE, but
1969 // sometimes dead copies slip through, and we can't generate invalid live
1970 // ranges.
1971 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1972 LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
1973 DeadDefs.push_back(CopyMI);
1974 eliminateDeadDefs();
1975 return true;
1978 // Eliminate undefs.
1979 if (!CP.isPhys()) {
1980 // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
1981 if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
1982 if (UndefMI->isImplicitDef())
1983 return false;
1984 deleteInstr(CopyMI);
1985 return false; // Not coalescable.
1989 // Coalesced copies are normally removed immediately, but transformations
1990 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1991 // When that happens, just join the values and remove the copy.
1992 if (CP.getSrcReg() == CP.getDstReg()) {
1993 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1994 LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1995 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1996 LiveQueryResult LRQ = LI.Query(CopyIdx);
1997 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1998 VNInfo *ReadVNI = LRQ.valueIn();
1999 assert(ReadVNI && "No value before copy and no <undef> flag.");
2000 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
2002 // Track incoming undef lanes we need to eliminate from the subrange.
2003 LaneBitmask PrunedLanes;
2004 MachineBasicBlock *MBB = CopyMI->getParent();
2006 // Process subregister liveranges.
2007 for (LiveInterval::SubRange &S : LI.subranges()) {
2008 LiveQueryResult SLRQ = S.Query(CopyIdx);
2009 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
2010 if (VNInfo *SReadVNI = SLRQ.valueIn())
2011 SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
2013 // If this copy introduced an undef subrange from an incoming value,
2014 // we need to eliminate the undef live in values from the subrange.
2015 if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
2016 LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n");
2017 PrunedLanes |= S.LaneMask;
2018 S.removeValNo(SDefVNI);
2023 LI.MergeValueNumberInto(DefVNI, ReadVNI);
2024 if (PrunedLanes.any()) {
2025 LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: "
2026 << PrunedLanes << '\n');
2027 setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
2030 LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
2032 deleteInstr(CopyMI);
2033 return true;
2036 // Enforce policies.
2037 if (CP.isPhys()) {
2038 LLVM_DEBUG(dbgs() << "\tConsidering merging "
2039 << printReg(CP.getSrcReg(), TRI) << " with "
2040 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
2041 if (!canJoinPhys(CP)) {
2042 // Before giving up coalescing, if definition of source is defined by
2043 // trivial computation, try rematerializing it.
2044 bool IsDefCopy = false;
2045 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
2046 return true;
2047 if (IsDefCopy)
2048 Again = true; // May be possible to coalesce later.
2049 return false;
2051 } else {
2052 // When possible, let DstReg be the larger interval.
2053 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
2054 LIS->getInterval(CP.getDstReg()).size())
2055 CP.flip();
2057 LLVM_DEBUG({
2058 dbgs() << "\tConsidering merging to "
2059 << TRI->getRegClassName(CP.getNewRC()) << " with ";
2060 if (CP.getDstIdx() && CP.getSrcIdx())
2061 dbgs() << printReg(CP.getDstReg()) << " in "
2062 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
2063 << printReg(CP.getSrcReg()) << " in "
2064 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
2065 else
2066 dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
2067 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
2071 ShrinkMask = LaneBitmask::getNone();
2072 ShrinkMainRange = false;
2074 // Okay, attempt to join these two intervals. On failure, this returns false.
2075 // Otherwise, if one of the intervals being joined is a physreg, this method
2076 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
2077 // been modified, so we can use this information below to update aliases.
2078 if (!joinIntervals(CP)) {
2079 // Coalescing failed.
2081 // If definition of source is defined by trivial computation, try
2082 // rematerializing it.
2083 bool IsDefCopy = false;
2084 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
2085 return true;
2087 // If we can eliminate the copy without merging the live segments, do so
2088 // now.
2089 if (!CP.isPartial() && !CP.isPhys()) {
2090 bool Changed = adjustCopiesBackFrom(CP, CopyMI);
2091 bool Shrink = false;
2092 if (!Changed)
2093 std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
2094 if (Changed) {
2095 deleteInstr(CopyMI);
2096 if (Shrink) {
2097 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
2098 LiveInterval &DstLI = LIS->getInterval(DstReg);
2099 shrinkToUses(&DstLI);
2100 LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n');
2102 LLVM_DEBUG(dbgs() << "\tTrivial!\n");
2103 return true;
2107 // Try and see if we can partially eliminate the copy by moving the copy to
2108 // its predecessor.
2109 if (!CP.isPartial() && !CP.isPhys())
2110 if (removePartialRedundancy(CP, *CopyMI))
2111 return true;
2113 // Otherwise, we are unable to join the intervals.
2114 LLVM_DEBUG(dbgs() << "\tInterference!\n");
2115 Again = true; // May be possible to coalesce later.
2116 return false;
2119 // Coalescing to a virtual register that is of a sub-register class of the
2120 // other. Make sure the resulting register is set to the right register class.
2121 if (CP.isCrossClass()) {
2122 ++numCrossRCs;
2123 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
2126 // Removing sub-register copies can ease the register class constraints.
2127 // Make sure we attempt to inflate the register class of DstReg.
2128 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
2129 InflateRegs.push_back(CP.getDstReg());
2131 // CopyMI has been erased by joinIntervals at this point. Remove it from
2132 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
2133 // to the work list. This keeps ErasedInstrs from growing needlessly.
2134 ErasedInstrs.erase(CopyMI);
2136 // Rewrite all SrcReg operands to DstReg.
2137 // Also update DstReg operands to include DstIdx if it is set.
2138 if (CP.getDstIdx())
2139 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
2140 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
2142 // Shrink subregister ranges if necessary.
2143 if (ShrinkMask.any()) {
2144 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2145 for (LiveInterval::SubRange &S : LI.subranges()) {
2146 if ((S.LaneMask & ShrinkMask).none())
2147 continue;
2148 LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
2149 << ")\n");
2150 LIS->shrinkToUses(S, LI.reg());
2151 ShrinkMainRange = true;
2153 LI.removeEmptySubRanges();
2156 // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
2157 // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
2158 // is not up-to-date, need to update the merged live interval here.
2159 if (ToBeUpdated.count(CP.getSrcReg()))
2160 ShrinkMainRange = true;
2162 if (ShrinkMainRange) {
2163 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2164 shrinkToUses(&LI);
2167 // SrcReg is guaranteed to be the register whose live interval that is
2168 // being merged.
2169 LIS->removeInterval(CP.getSrcReg());
2171 // Update regalloc hint.
2172 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
2174 LLVM_DEBUG({
2175 dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
2176 << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
2177 dbgs() << "\tResult = ";
2178 if (CP.isPhys())
2179 dbgs() << printReg(CP.getDstReg(), TRI);
2180 else
2181 dbgs() << LIS->getInterval(CP.getDstReg());
2182 dbgs() << '\n';
2185 ++numJoins;
2186 return true;
2189 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2190 Register DstReg = CP.getDstReg();
2191 Register SrcReg = CP.getSrcReg();
2192 assert(CP.isPhys() && "Must be a physreg copy");
2193 assert(MRI->isReserved(DstReg) && "Not a reserved register");
2194 LiveInterval &RHS = LIS->getInterval(SrcReg);
2195 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
2197 assert(RHS.containsOneValue() && "Invalid join with reserved register");
2199 // Optimization for reserved registers like ESP. We can only merge with a
2200 // reserved physreg if RHS has a single value that is a copy of DstReg.
2201 // The live range of the reserved register will look like a set of dead defs
2202 // - we don't properly track the live range of reserved registers.
2204 // Deny any overlapping intervals. This depends on all the reserved
2205 // register live ranges to look like dead defs.
2206 if (!MRI->isConstantPhysReg(DstReg)) {
2207 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2208 // Abort if not all the regunits are reserved.
2209 for (MCRegUnitRootIterator RI(Unit, TRI); RI.isValid(); ++RI) {
2210 if (!MRI->isReserved(*RI))
2211 return false;
2213 if (RHS.overlaps(LIS->getRegUnit(Unit))) {
2214 LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(Unit, TRI)
2215 << '\n');
2216 return false;
2220 // We must also check for overlaps with regmask clobbers.
2221 BitVector RegMaskUsable;
2222 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
2223 !RegMaskUsable.test(DstReg)) {
2224 LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
2225 return false;
2229 // Skip any value computations, we are not adding new values to the
2230 // reserved register. Also skip merging the live ranges, the reserved
2231 // register live range doesn't need to be accurate as long as all the
2232 // defs are there.
2234 // Delete the identity copy.
2235 MachineInstr *CopyMI;
2236 if (CP.isFlipped()) {
2237 // Physreg is copied into vreg
2238 // %y = COPY %physreg_x
2239 // ... //< no other def of %physreg_x here
2240 // use %y
2241 // =>
2242 // ...
2243 // use %physreg_x
2244 CopyMI = MRI->getVRegDef(SrcReg);
2245 deleteInstr(CopyMI);
2246 } else {
2247 // VReg is copied into physreg:
2248 // %y = def
2249 // ... //< no other def or use of %physreg_x here
2250 // %physreg_x = COPY %y
2251 // =>
2252 // %physreg_x = def
2253 // ...
2254 if (!MRI->hasOneNonDBGUse(SrcReg)) {
2255 LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
2256 return false;
2259 if (!LIS->intervalIsInOneMBB(RHS)) {
2260 LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
2261 return false;
2264 MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
2265 CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
2266 SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
2267 SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
2269 if (!MRI->isConstantPhysReg(DstReg)) {
2270 // We checked above that there are no interfering defs of the physical
2271 // register. However, for this case, where we intend to move up the def of
2272 // the physical register, we also need to check for interfering uses.
2273 SlotIndexes *Indexes = LIS->getSlotIndexes();
2274 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
2275 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
2276 MachineInstr *MI = LIS->getInstructionFromIndex(SI);
2277 if (MI->readsRegister(DstReg, TRI)) {
2278 LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
2279 return false;
2284 // We're going to remove the copy which defines a physical reserved
2285 // register, so remove its valno, etc.
2286 LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
2287 << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
2289 LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
2290 deleteInstr(CopyMI);
2292 // Create a new dead def at the new def location.
2293 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2294 LiveRange &LR = LIS->getRegUnit(Unit);
2295 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
2299 // We don't track kills for reserved registers.
2300 MRI->clearKillFlags(CP.getSrcReg());
2302 return true;
2305 //===----------------------------------------------------------------------===//
2306 // Interference checking and interval joining
2307 //===----------------------------------------------------------------------===//
2309 // In the easiest case, the two live ranges being joined are disjoint, and
2310 // there is no interference to consider. It is quite common, though, to have
2311 // overlapping live ranges, and we need to check if the interference can be
2312 // resolved.
2314 // The live range of a single SSA value forms a sub-tree of the dominator tree.
2315 // This means that two SSA values overlap if and only if the def of one value
2316 // is contained in the live range of the other value. As a special case, the
2317 // overlapping values can be defined at the same index.
2319 // The interference from an overlapping def can be resolved in these cases:
2321 // 1. Coalescable copies. The value is defined by a copy that would become an
2322 // identity copy after joining SrcReg and DstReg. The copy instruction will
2323 // be removed, and the value will be merged with the source value.
2325 // There can be several copies back and forth, causing many values to be
2326 // merged into one. We compute a list of ultimate values in the joined live
2327 // range as well as a mappings from the old value numbers.
2329 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
2330 // predecessors have a live out value. It doesn't cause real interference,
2331 // and can be merged into the value it overlaps. Like a coalescable copy, it
2332 // can be erased after joining.
2334 // 3. Copy of external value. The overlapping def may be a copy of a value that
2335 // is already in the other register. This is like a coalescable copy, but
2336 // the live range of the source register must be trimmed after erasing the
2337 // copy instruction:
2339 // %src = COPY %ext
2340 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
2342 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
2343 // defining one lane at a time:
2345 // %dst:ssub0<def,read-undef> = FOO
2346 // %src = BAR
2347 // %dst:ssub1 = COPY %src
2349 // The live range of %src overlaps the %dst value defined by FOO, but
2350 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
2351 // which was undef anyway.
2353 // The value mapping is more complicated in this case. The final live range
2354 // will have different value numbers for both FOO and BAR, but there is no
2355 // simple mapping from old to new values. It may even be necessary to add
2356 // new PHI values.
2358 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
2359 // is live, but never read. This can happen because we don't compute
2360 // individual live ranges per lane.
2362 // %dst = FOO
2363 // %src = BAR
2364 // %dst:ssub1 = COPY %src
2366 // This kind of interference is only resolved locally. If the clobbered
2367 // lane value escapes the block, the join is aborted.
2369 namespace {
2371 /// Track information about values in a single virtual register about to be
2372 /// joined. Objects of this class are always created in pairs - one for each
2373 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
2374 /// pair)
2375 class JoinVals {
2376 /// Live range we work on.
2377 LiveRange &LR;
2379 /// (Main) register we work on.
2380 const Register Reg;
2382 /// Reg (and therefore the values in this liverange) will end up as
2383 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
2384 /// CP.SrcIdx.
2385 const unsigned SubIdx;
2387 /// The LaneMask that this liverange will occupy the coalesced register. May
2388 /// be smaller than the lanemask produced by SubIdx when merging subranges.
2389 const LaneBitmask LaneMask;
2391 /// This is true when joining sub register ranges, false when joining main
2392 /// ranges.
2393 const bool SubRangeJoin;
2395 /// Whether the current LiveInterval tracks subregister liveness.
2396 const bool TrackSubRegLiveness;
2398 /// Values that will be present in the final live range.
2399 SmallVectorImpl<VNInfo*> &NewVNInfo;
2401 const CoalescerPair &CP;
2402 LiveIntervals *LIS;
2403 SlotIndexes *Indexes;
2404 const TargetRegisterInfo *TRI;
2406 /// Value number assignments. Maps value numbers in LI to entries in
2407 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
2408 SmallVector<int, 8> Assignments;
2410 public:
2411 /// Conflict resolution for overlapping values.
2412 enum ConflictResolution {
2413 /// No overlap, simply keep this value.
2414 CR_Keep,
2416 /// Merge this value into OtherVNI and erase the defining instruction.
2417 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
2418 /// values.
2419 CR_Erase,
2421 /// Merge this value into OtherVNI but keep the defining instruction.
2422 /// This is for the special case where OtherVNI is defined by the same
2423 /// instruction.
2424 CR_Merge,
2426 /// Keep this value, and have it replace OtherVNI where possible. This
2427 /// complicates value mapping since OtherVNI maps to two different values
2428 /// before and after this def.
2429 /// Used when clobbering undefined or dead lanes.
2430 CR_Replace,
2432 /// Unresolved conflict. Visit later when all values have been mapped.
2433 CR_Unresolved,
2435 /// Unresolvable conflict. Abort the join.
2436 CR_Impossible
2439 private:
2440 /// Per-value info for LI. The lane bit masks are all relative to the final
2441 /// joined register, so they can be compared directly between SrcReg and
2442 /// DstReg.
2443 struct Val {
2444 ConflictResolution Resolution = CR_Keep;
2446 /// Lanes written by this def, 0 for unanalyzed values.
2447 LaneBitmask WriteLanes;
2449 /// Lanes with defined values in this register. Other lanes are undef and
2450 /// safe to clobber.
2451 LaneBitmask ValidLanes;
2453 /// Value in LI being redefined by this def.
2454 VNInfo *RedefVNI = nullptr;
2456 /// Value in the other live range that overlaps this def, if any.
2457 VNInfo *OtherVNI = nullptr;
2459 /// Is this value an IMPLICIT_DEF that can be erased?
2461 /// IMPLICIT_DEF values should only exist at the end of a basic block that
2462 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
2463 /// safely erased if they are overlapping a live value in the other live
2464 /// interval.
2466 /// Weird control flow graphs and incomplete PHI handling in
2467 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
2468 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
2469 /// normal values.
2470 bool ErasableImplicitDef = false;
2472 /// True when the live range of this value will be pruned because of an
2473 /// overlapping CR_Replace value in the other live range.
2474 bool Pruned = false;
2476 /// True once Pruned above has been computed.
2477 bool PrunedComputed = false;
2479 /// True if this value is determined to be identical to OtherVNI
2480 /// (in valuesIdentical). This is used with CR_Erase where the erased
2481 /// copy is redundant, i.e. the source value is already the same as
2482 /// the destination. In such cases the subranges need to be updated
2483 /// properly. See comment at pruneSubRegValues for more info.
2484 bool Identical = false;
2486 Val() = default;
2488 bool isAnalyzed() const { return WriteLanes.any(); }
2490 /// Mark this value as an IMPLICIT_DEF which must be kept as if it were an
2491 /// ordinary value.
2492 void mustKeepImplicitDef(const TargetRegisterInfo &TRI,
2493 const MachineInstr &ImpDef) {
2494 assert(ImpDef.isImplicitDef());
2495 ErasableImplicitDef = false;
2496 ValidLanes = TRI.getSubRegIndexLaneMask(ImpDef.getOperand(0).getSubReg());
2500 /// One entry per value number in LI.
2501 SmallVector<Val, 8> Vals;
2503 /// Compute the bitmask of lanes actually written by DefMI.
2504 /// Set Redef if there are any partial register definitions that depend on the
2505 /// previous value of the register.
2506 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2508 /// Find the ultimate value that VNI was copied from.
2509 std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
2511 bool valuesIdentical(VNInfo *Value0, VNInfo *Value1, const JoinVals &Other) const;
2513 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2514 /// Return a conflict resolution when possible, but leave the hard cases as
2515 /// CR_Unresolved.
2516 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2517 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2518 /// The recursion always goes upwards in the dominator tree, making loops
2519 /// impossible.
2520 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2522 /// Compute the value assignment for ValNo in RI.
2523 /// This may be called recursively by analyzeValue(), but never for a ValNo on
2524 /// the stack.
2525 void computeAssignment(unsigned ValNo, JoinVals &Other);
2527 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2528 /// the extent of the tainted lanes in the block.
2530 /// Multiple values in Other.LR can be affected since partial redefinitions
2531 /// can preserve previously tainted lanes.
2533 /// 1 %dst = VLOAD <-- Define all lanes in %dst
2534 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
2535 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
2536 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2538 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2539 /// entry to TaintedVals.
2541 /// Returns false if the tainted lanes extend beyond the basic block.
2542 bool
2543 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2544 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
2546 /// Return true if MI uses any of the given Lanes from Reg.
2547 /// This does not include partial redefinitions of Reg.
2548 bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
2550 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2551 /// be pruned:
2553 /// %dst = COPY %src
2554 /// %src = COPY %dst <-- This value to be pruned.
2555 /// %dst = COPY %src <-- This value is a copy of a pruned value.
2556 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2558 public:
2559 JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
2560 SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
2561 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2562 bool TrackSubRegLiveness)
2563 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2564 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2565 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2566 TRI(TRI), Assignments(LR.getNumValNums(), -1),
2567 Vals(LR.getNumValNums()) {}
2569 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2570 /// Returns false if any conflicts were impossible to resolve.
2571 bool mapValues(JoinVals &Other);
2573 /// Try to resolve conflicts that require all values to be mapped.
2574 /// Returns false if any conflicts were impossible to resolve.
2575 bool resolveConflicts(JoinVals &Other);
2577 /// Prune the live range of values in Other.LR where they would conflict with
2578 /// CR_Replace values in LR. Collect end points for restoring the live range
2579 /// after joining.
2580 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2581 bool changeInstrs);
2583 /// Removes subranges starting at copies that get removed. This sometimes
2584 /// happens when undefined subranges are copied around. These ranges contain
2585 /// no useful information and can be removed.
2586 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
2588 /// Pruning values in subranges can lead to removing segments in these
2589 /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2590 /// the main range also need to be removed. This function will mark
2591 /// the corresponding values in the main range as pruned, so that
2592 /// eraseInstrs can do the final cleanup.
2593 /// The parameter @p LI must be the interval whose main range is the
2594 /// live range LR.
2595 void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2597 /// Erase any machine instructions that have been coalesced away.
2598 /// Add erased instructions to ErasedInstrs.
2599 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2600 /// the erased instrs.
2601 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2602 SmallVectorImpl<Register> &ShrinkRegs,
2603 LiveInterval *LI = nullptr);
2605 /// Remove liverange defs at places where implicit defs will be removed.
2606 void removeImplicitDefs();
2608 /// Get the value assignments suitable for passing to LiveInterval::join.
2609 const int *getAssignments() const { return Assignments.data(); }
2611 /// Get the conflict resolution for a value number.
2612 ConflictResolution getResolution(unsigned Num) const {
2613 return Vals[Num].Resolution;
2617 } // end anonymous namespace
2619 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
2620 const {
2621 LaneBitmask L;
2622 for (const MachineOperand &MO : DefMI->all_defs()) {
2623 if (MO.getReg() != Reg)
2624 continue;
2625 L |= TRI->getSubRegIndexLaneMask(
2626 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2627 if (MO.readsReg())
2628 Redef = true;
2630 return L;
2633 std::pair<const VNInfo *, Register>
2634 JoinVals::followCopyChain(const VNInfo *VNI) const {
2635 Register TrackReg = Reg;
2637 while (!VNI->isPHIDef()) {
2638 SlotIndex Def = VNI->def;
2639 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2640 assert(MI && "No defining instruction");
2641 if (!MI->isFullCopy())
2642 return std::make_pair(VNI, TrackReg);
2643 Register SrcReg = MI->getOperand(1).getReg();
2644 if (!SrcReg.isVirtual())
2645 return std::make_pair(VNI, TrackReg);
2647 const LiveInterval &LI = LIS->getInterval(SrcReg);
2648 const VNInfo *ValueIn;
2649 // No subrange involved.
2650 if (!SubRangeJoin || !LI.hasSubRanges()) {
2651 LiveQueryResult LRQ = LI.Query(Def);
2652 ValueIn = LRQ.valueIn();
2653 } else {
2654 // Query subranges. Ensure that all matching ones take us to the same def
2655 // (allowing some of them to be undef).
2656 ValueIn = nullptr;
2657 for (const LiveInterval::SubRange &S : LI.subranges()) {
2658 // Transform lanemask to a mask in the joined live interval.
2659 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2660 if ((SMask & LaneMask).none())
2661 continue;
2662 LiveQueryResult LRQ = S.Query(Def);
2663 if (!ValueIn) {
2664 ValueIn = LRQ.valueIn();
2665 continue;
2667 if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
2668 return std::make_pair(VNI, TrackReg);
2671 if (ValueIn == nullptr) {
2672 // Reaching an undefined value is legitimate, for example:
2674 // 1 undef %0.sub1 = ... ;; %0.sub0 == undef
2675 // 2 %1 = COPY %0 ;; %1 is defined here.
2676 // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
2677 // ;; but it's equivalent to "undef".
2678 return std::make_pair(nullptr, SrcReg);
2680 VNI = ValueIn;
2681 TrackReg = SrcReg;
2683 return std::make_pair(VNI, TrackReg);
2686 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2687 const JoinVals &Other) const {
2688 const VNInfo *Orig0;
2689 Register Reg0;
2690 std::tie(Orig0, Reg0) = followCopyChain(Value0);
2691 if (Orig0 == Value1 && Reg0 == Other.Reg)
2692 return true;
2694 const VNInfo *Orig1;
2695 Register Reg1;
2696 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2697 // If both values are undefined, and the source registers are the same
2698 // register, the values are identical. Filter out cases where only one
2699 // value is defined.
2700 if (Orig0 == nullptr || Orig1 == nullptr)
2701 return Orig0 == Orig1 && Reg0 == Reg1;
2703 // The values are equal if they are defined at the same place and use the
2704 // same register. Note that we cannot compare VNInfos directly as some of
2705 // them might be from a copy created in mergeSubRangeInto() while the other
2706 // is from the original LiveInterval.
2707 return Orig0->def == Orig1->def && Reg0 == Reg1;
2710 JoinVals::ConflictResolution
2711 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
2712 Val &V = Vals[ValNo];
2713 assert(!V.isAnalyzed() && "Value has already been analyzed!");
2714 VNInfo *VNI = LR.getValNumInfo(ValNo);
2715 if (VNI->isUnused()) {
2716 V.WriteLanes = LaneBitmask::getAll();
2717 return CR_Keep;
2720 // Get the instruction defining this value, compute the lanes written.
2721 const MachineInstr *DefMI = nullptr;
2722 if (VNI->isPHIDef()) {
2723 // Conservatively assume that all lanes in a PHI are valid.
2724 LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
2725 : TRI->getSubRegIndexLaneMask(SubIdx);
2726 V.ValidLanes = V.WriteLanes = Lanes;
2727 } else {
2728 DefMI = Indexes->getInstructionFromIndex(VNI->def);
2729 assert(DefMI != nullptr);
2730 if (SubRangeJoin) {
2731 // We don't care about the lanes when joining subregister ranges.
2732 V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
2733 if (DefMI->isImplicitDef()) {
2734 V.ValidLanes = LaneBitmask::getNone();
2735 V.ErasableImplicitDef = true;
2737 } else {
2738 bool Redef = false;
2739 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2741 // If this is a read-modify-write instruction, there may be more valid
2742 // lanes than the ones written by this instruction.
2743 // This only covers partial redef operands. DefMI may have normal use
2744 // operands reading the register. They don't contribute valid lanes.
2746 // This adds ssub1 to the set of valid lanes in %src:
2748 // %src:ssub1 = FOO
2750 // This leaves only ssub1 valid, making any other lanes undef:
2752 // %src:ssub1<def,read-undef> = FOO %src:ssub2
2754 // The <read-undef> flag on the def operand means that old lane values are
2755 // not important.
2756 if (Redef) {
2757 V.RedefVNI = LR.Query(VNI->def).valueIn();
2758 assert((TrackSubRegLiveness || V.RedefVNI) &&
2759 "Instruction is reading nonexistent value");
2760 if (V.RedefVNI != nullptr) {
2761 computeAssignment(V.RedefVNI->id, Other);
2762 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2766 // An IMPLICIT_DEF writes undef values.
2767 if (DefMI->isImplicitDef()) {
2768 // We normally expect IMPLICIT_DEF values to be live only until the end
2769 // of their block. If the value is really live longer and gets pruned in
2770 // another block, this flag is cleared again.
2772 // Clearing the valid lanes is deferred until it is sure this can be
2773 // erased.
2774 V.ErasableImplicitDef = true;
2779 // Find the value in Other that overlaps VNI->def, if any.
2780 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2782 // It is possible that both values are defined by the same instruction, or
2783 // the values are PHIs defined in the same block. When that happens, the two
2784 // values should be merged into one, but not into any preceding value.
2785 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2786 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2787 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
2789 // One value stays, the other is merged. Keep the earlier one, or the first
2790 // one we see.
2791 if (OtherVNI->def < VNI->def)
2792 Other.computeAssignment(OtherVNI->id, *this);
2793 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2794 // This is an early-clobber def overlapping a live-in value in the other
2795 // register. Not mergeable.
2796 V.OtherVNI = OtherLRQ.valueIn();
2797 return CR_Impossible;
2799 V.OtherVNI = OtherVNI;
2800 Val &OtherV = Other.Vals[OtherVNI->id];
2801 // Keep this value, check for conflicts when analyzing OtherVNI. Avoid
2802 // revisiting OtherVNI->id in JoinVals::computeAssignment() below before it
2803 // is assigned.
2804 if (!OtherV.isAnalyzed() || Other.Assignments[OtherVNI->id] == -1)
2805 return CR_Keep;
2806 // Both sides have been analyzed now.
2807 // Allow overlapping PHI values. Any real interference would show up in a
2808 // predecessor, the PHI itself can't introduce any conflicts.
2809 if (VNI->isPHIDef())
2810 return CR_Merge;
2811 if ((V.ValidLanes & OtherV.ValidLanes).any())
2812 // Overlapping lanes can't be resolved.
2813 return CR_Impossible;
2814 else
2815 return CR_Merge;
2818 // No simultaneous def. Is Other live at the def?
2819 V.OtherVNI = OtherLRQ.valueIn();
2820 if (!V.OtherVNI)
2821 // No overlap, no conflict.
2822 return CR_Keep;
2824 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2826 // We have overlapping values, or possibly a kill of Other.
2827 // Recursively compute assignments up the dominator tree.
2828 Other.computeAssignment(V.OtherVNI->id, *this);
2829 Val &OtherV = Other.Vals[V.OtherVNI->id];
2831 if (OtherV.ErasableImplicitDef) {
2832 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2833 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2834 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2835 // technically.
2837 // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2838 // to erase the IMPLICIT_DEF instruction.
2840 // Additionally we must keep an IMPLICIT_DEF if we're redefining an incoming
2841 // value.
2843 MachineInstr *OtherImpDef =
2844 Indexes->getInstructionFromIndex(V.OtherVNI->def);
2845 MachineBasicBlock *OtherMBB = OtherImpDef->getParent();
2846 if (DefMI &&
2847 (DefMI->getParent() != OtherMBB || LIS->isLiveInToMBB(LR, OtherMBB))) {
2848 LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2849 << " extends into "
2850 << printMBBReference(*DefMI->getParent())
2851 << ", keeping it.\n");
2852 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2853 } else if (OtherMBB->hasEHPadSuccessor()) {
2854 // If OtherV is defined in a basic block that has EH pad successors then
2855 // we get the same problem not just if OtherV is live beyond its basic
2856 // block, but beyond the last call instruction in its basic block. Handle
2857 // this case conservatively.
2858 LLVM_DEBUG(
2859 dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2860 << " may be live into EH pad successors, keeping it.\n");
2861 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2862 } else {
2863 // We deferred clearing these lanes in case we needed to save them
2864 OtherV.ValidLanes &= ~OtherV.WriteLanes;
2868 // Allow overlapping PHI values. Any real interference would show up in a
2869 // predecessor, the PHI itself can't introduce any conflicts.
2870 if (VNI->isPHIDef())
2871 return CR_Replace;
2873 // Check for simple erasable conflicts.
2874 if (DefMI->isImplicitDef())
2875 return CR_Erase;
2877 // Include the non-conflict where DefMI is a coalescable copy that kills
2878 // OtherVNI. We still want the copy erased and value numbers merged.
2879 if (CP.isCoalescable(DefMI)) {
2880 // Some of the lanes copied from OtherVNI may be undef, making them undef
2881 // here too.
2882 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2883 return CR_Erase;
2886 // This may not be a real conflict if DefMI simply kills Other and defines
2887 // VNI.
2888 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2889 return CR_Keep;
2891 // Handle the case where VNI and OtherVNI can be proven to be identical:
2893 // %other = COPY %ext
2894 // %this = COPY %ext <-- Erase this copy
2896 if (DefMI->isFullCopy() && !CP.isPartial() &&
2897 valuesIdentical(VNI, V.OtherVNI, Other)) {
2898 V.Identical = true;
2899 return CR_Erase;
2902 // The remaining checks apply to the lanes, which aren't tracked here. This
2903 // was already decided to be OK via the following CR_Replace condition.
2904 // CR_Replace.
2905 if (SubRangeJoin)
2906 return CR_Replace;
2908 // If the lanes written by this instruction were all undef in OtherVNI, it is
2909 // still safe to join the live ranges. This can't be done with a simple value
2910 // mapping, though - OtherVNI will map to multiple values:
2912 // 1 %dst:ssub0 = FOO <-- OtherVNI
2913 // 2 %src = BAR <-- VNI
2914 // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
2915 // 4 BAZ killed %dst
2916 // 5 QUUX killed %src
2918 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2919 // handles this complex value mapping.
2920 if ((V.WriteLanes & OtherV.ValidLanes).none())
2921 return CR_Replace;
2923 // If the other live range is killed by DefMI and the live ranges are still
2924 // overlapping, it must be because we're looking at an early clobber def:
2926 // %dst<def,early-clobber> = ASM killed %src
2928 // In this case, it is illegal to merge the two live ranges since the early
2929 // clobber def would clobber %src before it was read.
2930 if (OtherLRQ.isKill()) {
2931 // This case where the def doesn't overlap the kill is handled above.
2932 assert(VNI->def.isEarlyClobber() &&
2933 "Only early clobber defs can overlap a kill");
2934 return CR_Impossible;
2937 // VNI is clobbering live lanes in OtherVNI, but there is still the
2938 // possibility that no instructions actually read the clobbered lanes.
2939 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2940 // Otherwise Other.RI wouldn't be live here.
2941 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
2942 return CR_Impossible;
2944 if (TrackSubRegLiveness) {
2945 auto &OtherLI = LIS->getInterval(Other.Reg);
2946 // If OtherVNI does not have subranges, it means all the lanes of OtherVNI
2947 // share the same live range, so we just need to check whether they have
2948 // any conflict bit in their LaneMask.
2949 if (!OtherLI.hasSubRanges()) {
2950 LaneBitmask OtherMask = TRI->getSubRegIndexLaneMask(Other.SubIdx);
2951 return (OtherMask & V.WriteLanes).none() ? CR_Replace : CR_Impossible;
2954 // If we are clobbering some active lanes of OtherVNI at VNI->def, it is
2955 // impossible to resolve the conflict. Otherwise, we can just replace
2956 // OtherVNI because of no real conflict.
2957 for (LiveInterval::SubRange &OtherSR : OtherLI.subranges()) {
2958 LaneBitmask OtherMask =
2959 TRI->composeSubRegIndexLaneMask(Other.SubIdx, OtherSR.LaneMask);
2960 if ((OtherMask & V.WriteLanes).none())
2961 continue;
2963 auto OtherSRQ = OtherSR.Query(VNI->def);
2964 if (OtherSRQ.valueIn() && OtherSRQ.endPoint() > VNI->def) {
2965 // VNI is clobbering some lanes of OtherVNI, they have real conflict.
2966 return CR_Impossible;
2970 // VNI is NOT clobbering any lane of OtherVNI, just replace OtherVNI.
2971 return CR_Replace;
2974 // We need to verify that no instructions are reading the clobbered lanes.
2975 // To save compile time, we'll only check that locally. Don't allow the
2976 // tainted value to escape the basic block.
2977 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2978 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2979 return CR_Impossible;
2981 // There are still some things that could go wrong besides clobbered lanes
2982 // being read, for example OtherVNI may be only partially redefined in MBB,
2983 // and some clobbered lanes could escape the block. Save this analysis for
2984 // resolveConflicts() when all values have been mapped. We need to know
2985 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2986 // that now - the recursive analyzeValue() calls must go upwards in the
2987 // dominator tree.
2988 return CR_Unresolved;
2991 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2992 Val &V = Vals[ValNo];
2993 if (V.isAnalyzed()) {
2994 // Recursion should always move up the dominator tree, so ValNo is not
2995 // supposed to reappear before it has been assigned.
2996 assert(Assignments[ValNo] != -1 && "Bad recursion?");
2997 return;
2999 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
3000 case CR_Erase:
3001 case CR_Merge:
3002 // Merge this ValNo into OtherVNI.
3003 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
3004 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
3005 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
3006 LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
3007 << LR.getValNumInfo(ValNo)->def << " into "
3008 << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
3009 << V.OtherVNI->def << " --> @"
3010 << NewVNInfo[Assignments[ValNo]]->def << '\n');
3011 break;
3012 case CR_Replace:
3013 case CR_Unresolved: {
3014 // The other value is going to be pruned if this join is successful.
3015 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
3016 Val &OtherV = Other.Vals[V.OtherVNI->id];
3017 OtherV.Pruned = true;
3018 [[fallthrough]];
3020 default:
3021 // This value number needs to go in the final joined live range.
3022 Assignments[ValNo] = NewVNInfo.size();
3023 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
3024 break;
3028 bool JoinVals::mapValues(JoinVals &Other) {
3029 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3030 computeAssignment(i, Other);
3031 if (Vals[i].Resolution == CR_Impossible) {
3032 LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
3033 << '@' << LR.getValNumInfo(i)->def << '\n');
3034 return false;
3037 return true;
3040 bool JoinVals::
3041 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
3042 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
3043 VNInfo *VNI = LR.getValNumInfo(ValNo);
3044 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3045 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
3047 // Scan Other.LR from VNI.def to MBBEnd.
3048 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
3049 assert(OtherI != Other.LR.end() && "No conflict?");
3050 do {
3051 // OtherI is pointing to a tainted value. Abort the join if the tainted
3052 // lanes escape the block.
3053 SlotIndex End = OtherI->end;
3054 if (End >= MBBEnd) {
3055 LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
3056 << OtherI->valno->id << '@' << OtherI->start << '\n');
3057 return false;
3059 LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
3060 << OtherI->valno->id << '@' << OtherI->start << " to "
3061 << End << '\n');
3062 // A dead def is not a problem.
3063 if (End.isDead())
3064 break;
3065 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
3067 // Check for another def in the MBB.
3068 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
3069 break;
3071 // Lanes written by the new def are no longer tainted.
3072 const Val &OV = Other.Vals[OtherI->valno->id];
3073 TaintedLanes &= ~OV.WriteLanes;
3074 if (!OV.RedefVNI)
3075 break;
3076 } while (TaintedLanes.any());
3077 return true;
3080 bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
3081 LaneBitmask Lanes) const {
3082 if (MI.isDebugOrPseudoInstr())
3083 return false;
3084 for (const MachineOperand &MO : MI.all_uses()) {
3085 if (MO.getReg() != Reg)
3086 continue;
3087 if (!MO.readsReg())
3088 continue;
3089 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
3090 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
3091 return true;
3093 return false;
3096 bool JoinVals::resolveConflicts(JoinVals &Other) {
3097 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3098 Val &V = Vals[i];
3099 assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
3100 if (V.Resolution != CR_Unresolved)
3101 continue;
3102 LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
3103 << LR.getValNumInfo(i)->def
3104 << ' ' << PrintLaneMask(LaneMask) << '\n');
3105 if (SubRangeJoin)
3106 return false;
3108 ++NumLaneConflicts;
3109 assert(V.OtherVNI && "Inconsistent conflict resolution.");
3110 VNInfo *VNI = LR.getValNumInfo(i);
3111 const Val &OtherV = Other.Vals[V.OtherVNI->id];
3113 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
3114 // join, those lanes will be tainted with a wrong value. Get the extent of
3115 // the tainted lanes.
3116 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
3117 SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
3118 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
3119 // Tainted lanes would extend beyond the basic block.
3120 return false;
3122 assert(!TaintExtent.empty() && "There should be at least one conflict.");
3124 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
3125 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3126 MachineBasicBlock::iterator MI = MBB->begin();
3127 if (!VNI->isPHIDef()) {
3128 MI = Indexes->getInstructionFromIndex(VNI->def);
3129 if (!VNI->def.isEarlyClobber()) {
3130 // No need to check the instruction defining VNI for reads.
3131 ++MI;
3134 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
3135 "Interference ends on VNI->def. Should have been handled earlier");
3136 MachineInstr *LastMI =
3137 Indexes->getInstructionFromIndex(TaintExtent.front().first);
3138 assert(LastMI && "Range must end at a proper instruction");
3139 unsigned TaintNum = 0;
3140 while (true) {
3141 assert(MI != MBB->end() && "Bad LastMI");
3142 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
3143 LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
3144 return false;
3146 // LastMI is the last instruction to use the current value.
3147 if (&*MI == LastMI) {
3148 if (++TaintNum == TaintExtent.size())
3149 break;
3150 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
3151 assert(LastMI && "Range must end at a proper instruction");
3152 TaintedLanes = TaintExtent[TaintNum].second;
3154 ++MI;
3157 // The tainted lanes are unused.
3158 V.Resolution = CR_Replace;
3159 ++NumLaneResolves;
3161 return true;
3164 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
3165 Val &V = Vals[ValNo];
3166 if (V.Pruned || V.PrunedComputed)
3167 return V.Pruned;
3169 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
3170 return V.Pruned;
3172 // Follow copies up the dominator tree and check if any intermediate value
3173 // has been pruned.
3174 V.PrunedComputed = true;
3175 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
3176 return V.Pruned;
3179 void JoinVals::pruneValues(JoinVals &Other,
3180 SmallVectorImpl<SlotIndex> &EndPoints,
3181 bool changeInstrs) {
3182 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3183 SlotIndex Def = LR.getValNumInfo(i)->def;
3184 switch (Vals[i].Resolution) {
3185 case CR_Keep:
3186 break;
3187 case CR_Replace: {
3188 // This value takes precedence over the value in Other.LR.
3189 LIS->pruneValue(Other.LR, Def, &EndPoints);
3190 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
3191 // instructions are only inserted to provide a live-out value for PHI
3192 // predecessors, so the instruction should simply go away once its value
3193 // has been replaced.
3194 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3195 bool EraseImpDef = OtherV.ErasableImplicitDef &&
3196 OtherV.Resolution == CR_Keep;
3197 if (!Def.isBlock()) {
3198 if (changeInstrs) {
3199 // Remove <def,read-undef> flags. This def is now a partial redef.
3200 // Also remove dead flags since the joined live range will
3201 // continue past this instruction.
3202 for (MachineOperand &MO :
3203 Indexes->getInstructionFromIndex(Def)->operands()) {
3204 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
3205 if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
3206 MO.setIsUndef(false);
3207 MO.setIsDead(false);
3211 // This value will reach instructions below, but we need to make sure
3212 // the live range also reaches the instruction at Def.
3213 if (!EraseImpDef)
3214 EndPoints.push_back(Def);
3216 LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
3217 << ": " << Other.LR << '\n');
3218 break;
3220 case CR_Erase:
3221 case CR_Merge:
3222 if (isPrunedValue(i, Other)) {
3223 // This value is ultimately a copy of a pruned value in LR or Other.LR.
3224 // We can no longer trust the value mapping computed by
3225 // computeAssignment(), the value that was originally copied could have
3226 // been replaced.
3227 LIS->pruneValue(LR, Def, &EndPoints);
3228 LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
3229 << Def << ": " << LR << '\n');
3231 break;
3232 case CR_Unresolved:
3233 case CR_Impossible:
3234 llvm_unreachable("Unresolved conflicts");
3239 // Check if the segment consists of a copied live-through value (i.e. the copy
3240 // in the block only extended the liveness, of an undef value which we may need
3241 // to handle).
3242 static bool isLiveThrough(const LiveQueryResult Q) {
3243 return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
3246 /// Consider the following situation when coalescing the copy between
3247 /// %31 and %45 at 800. (The vertical lines represent live range segments.)
3249 /// Main range Subrange 0004 (sub2)
3250 /// %31 %45 %31 %45
3251 /// 544 %45 = COPY %28 + +
3252 /// | v1 | v1
3253 /// 560B bb.1: + +
3254 /// 624 = %45.sub2 | v2 | v2
3255 /// 800 %31 = COPY %45 + + + +
3256 /// | v0 | v0
3257 /// 816 %31.sub1 = ... + |
3258 /// 880 %30 = COPY %31 | v1 +
3259 /// 928 %45 = COPY %30 | + +
3260 /// | | v0 | v0 <--+
3261 /// 992B ; backedge -> bb.1 | + + |
3262 /// 1040 = %31.sub0 + |
3263 /// This value must remain
3264 /// live-out!
3266 /// Assuming that %31 is coalesced into %45, the copy at 928 becomes
3267 /// redundant, since it copies the value from %45 back into it. The
3268 /// conflict resolution for the main range determines that %45.v0 is
3269 /// to be erased, which is ok since %31.v1 is identical to it.
3270 /// The problem happens with the subrange for sub2: it has to be live
3271 /// on exit from the block, but since 928 was actually a point of
3272 /// definition of %45.sub2, %45.sub2 was not live immediately prior
3273 /// to that definition. As a result, when 928 was erased, the value v0
3274 /// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
3275 /// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
3276 /// providing an incorrect value to the use at 624.
3278 /// Since the main-range values %31.v1 and %45.v0 were proved to be
3279 /// identical, the corresponding values in subranges must also be the
3280 /// same. A redundant copy is removed because it's not needed, and not
3281 /// because it copied an undefined value, so any liveness that originated
3282 /// from that copy cannot disappear. When pruning a value that started
3283 /// at the removed copy, the corresponding identical value must be
3284 /// extended to replace it.
3285 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
3286 // Look for values being erased.
3287 bool DidPrune = false;
3288 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3289 Val &V = Vals[i];
3290 // We should trigger in all cases in which eraseInstrs() does something.
3291 // match what eraseInstrs() is doing, print a message so
3292 if (V.Resolution != CR_Erase &&
3293 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
3294 continue;
3296 // Check subranges at the point where the copy will be removed.
3297 SlotIndex Def = LR.getValNumInfo(i)->def;
3298 SlotIndex OtherDef;
3299 if (V.Identical)
3300 OtherDef = V.OtherVNI->def;
3302 // Print message so mismatches with eraseInstrs() can be diagnosed.
3303 LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
3304 << '\n');
3305 for (LiveInterval::SubRange &S : LI.subranges()) {
3306 LiveQueryResult Q = S.Query(Def);
3308 // If a subrange starts at the copy then an undefined value has been
3309 // copied and we must remove that subrange value as well.
3310 VNInfo *ValueOut = Q.valueOutOrDead();
3311 if (ValueOut != nullptr && (Q.valueIn() == nullptr ||
3312 (V.Identical && V.Resolution == CR_Erase &&
3313 ValueOut->def == Def))) {
3314 LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
3315 << " at " << Def << "\n");
3316 SmallVector<SlotIndex,8> EndPoints;
3317 LIS->pruneValue(S, Def, &EndPoints);
3318 DidPrune = true;
3319 // Mark value number as unused.
3320 ValueOut->markUnused();
3322 if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
3323 // If V is identical to V.OtherVNI (and S was live at OtherDef),
3324 // then we can't simply prune V from S. V needs to be replaced
3325 // with V.OtherVNI.
3326 LIS->extendToIndices(S, EndPoints);
3329 // We may need to eliminate the subrange if the copy introduced a live
3330 // out undef value.
3331 if (ValueOut->isPHIDef())
3332 ShrinkMask |= S.LaneMask;
3333 continue;
3336 // If a subrange ends at the copy, then a value was copied but only
3337 // partially used later. Shrink the subregister range appropriately.
3339 // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
3340 // conservatively correct.
3341 if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
3342 (V.Resolution == CR_Erase && isLiveThrough(Q))) {
3343 LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
3344 << PrintLaneMask(S.LaneMask) << " at " << Def
3345 << "\n");
3346 ShrinkMask |= S.LaneMask;
3350 if (DidPrune)
3351 LI.removeEmptySubRanges();
3354 /// Check if any of the subranges of @p LI contain a definition at @p Def.
3355 static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
3356 for (LiveInterval::SubRange &SR : LI.subranges()) {
3357 if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
3358 if (VNI->def == Def)
3359 return true;
3361 return false;
3364 void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
3365 assert(&static_cast<LiveRange&>(LI) == &LR);
3367 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3368 if (Vals[i].Resolution != CR_Keep)
3369 continue;
3370 VNInfo *VNI = LR.getValNumInfo(i);
3371 if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
3372 continue;
3373 Vals[i].Pruned = true;
3374 ShrinkMainRange = true;
3378 void JoinVals::removeImplicitDefs() {
3379 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3380 Val &V = Vals[i];
3381 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
3382 continue;
3384 VNInfo *VNI = LR.getValNumInfo(i);
3385 VNI->markUnused();
3386 LR.removeValNo(VNI);
3390 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
3391 SmallVectorImpl<Register> &ShrinkRegs,
3392 LiveInterval *LI) {
3393 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3394 // Get the def location before markUnused() below invalidates it.
3395 VNInfo *VNI = LR.getValNumInfo(i);
3396 SlotIndex Def = VNI->def;
3397 switch (Vals[i].Resolution) {
3398 case CR_Keep: {
3399 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
3400 // longer. The IMPLICIT_DEF instructions are only inserted by
3401 // PHIElimination to guarantee that all PHI predecessors have a value.
3402 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
3403 break;
3404 // Remove value number i from LR.
3405 // For intervals with subranges, removing a segment from the main range
3406 // may require extending the previous segment: for each definition of
3407 // a subregister, there will be a corresponding def in the main range.
3408 // That def may fall in the middle of a segment from another subrange.
3409 // In such cases, removing this def from the main range must be
3410 // complemented by extending the main range to account for the liveness
3411 // of the other subrange.
3412 // The new end point of the main range segment to be extended.
3413 SlotIndex NewEnd;
3414 if (LI != nullptr) {
3415 LiveRange::iterator I = LR.FindSegmentContaining(Def);
3416 assert(I != LR.end());
3417 // Do not extend beyond the end of the segment being removed.
3418 // The segment may have been pruned in preparation for joining
3419 // live ranges.
3420 NewEnd = I->end;
3423 LR.removeValNo(VNI);
3424 // Note that this VNInfo is reused and still referenced in NewVNInfo,
3425 // make it appear like an unused value number.
3426 VNI->markUnused();
3428 if (LI != nullptr && LI->hasSubRanges()) {
3429 assert(static_cast<LiveRange*>(LI) == &LR);
3430 // Determine the end point based on the subrange information:
3431 // minimum of (earliest def of next segment,
3432 // latest end point of containing segment)
3433 SlotIndex ED, LE;
3434 for (LiveInterval::SubRange &SR : LI->subranges()) {
3435 LiveRange::iterator I = SR.find(Def);
3436 if (I == SR.end())
3437 continue;
3438 if (I->start > Def)
3439 ED = ED.isValid() ? std::min(ED, I->start) : I->start;
3440 else
3441 LE = LE.isValid() ? std::max(LE, I->end) : I->end;
3443 if (LE.isValid())
3444 NewEnd = std::min(NewEnd, LE);
3445 if (ED.isValid())
3446 NewEnd = std::min(NewEnd, ED);
3448 // We only want to do the extension if there was a subrange that
3449 // was live across Def.
3450 if (LE.isValid()) {
3451 LiveRange::iterator S = LR.find(Def);
3452 if (S != LR.begin())
3453 std::prev(S)->end = NewEnd;
3456 LLVM_DEBUG({
3457 dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
3458 if (LI != nullptr)
3459 dbgs() << "\t\t LHS = " << *LI << '\n';
3461 [[fallthrough]];
3464 case CR_Erase: {
3465 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3466 assert(MI && "No instruction to erase");
3467 if (MI->isCopy()) {
3468 Register Reg = MI->getOperand(1).getReg();
3469 if (Reg.isVirtual() && Reg != CP.getSrcReg() && Reg != CP.getDstReg())
3470 ShrinkRegs.push_back(Reg);
3472 ErasedInstrs.insert(MI);
3473 LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
3474 LIS->RemoveMachineInstrFromMaps(*MI);
3475 MI->eraseFromParent();
3476 break;
3478 default:
3479 break;
3484 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
3485 LaneBitmask LaneMask,
3486 const CoalescerPair &CP) {
3487 SmallVector<VNInfo*, 16> NewVNInfo;
3488 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
3489 NewVNInfo, CP, LIS, TRI, true, true);
3490 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
3491 NewVNInfo, CP, LIS, TRI, true, true);
3493 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
3494 // We should be able to resolve all conflicts here as we could successfully do
3495 // it on the mainrange already. There is however a problem when multiple
3496 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
3497 // interferences.
3498 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3499 // We already determined that it is legal to merge the intervals, so this
3500 // should never fail.
3501 llvm_unreachable("*** Couldn't join subrange!\n");
3503 if (!LHSVals.resolveConflicts(RHSVals) ||
3504 !RHSVals.resolveConflicts(LHSVals)) {
3505 // We already determined that it is legal to merge the intervals, so this
3506 // should never fail.
3507 llvm_unreachable("*** Couldn't join subrange!\n");
3510 // The merging algorithm in LiveInterval::join() can't handle conflicting
3511 // value mappings, so we need to remove any live ranges that overlap a
3512 // CR_Replace resolution. Collect a set of end points that can be used to
3513 // restore the live range after joining.
3514 SmallVector<SlotIndex, 8> EndPoints;
3515 LHSVals.pruneValues(RHSVals, EndPoints, false);
3516 RHSVals.pruneValues(LHSVals, EndPoints, false);
3518 LHSVals.removeImplicitDefs();
3519 RHSVals.removeImplicitDefs();
3521 LRange.verify();
3522 RRange.verify();
3524 // Join RRange into LHS.
3525 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3526 NewVNInfo);
3528 LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask)
3529 << ' ' << LRange << "\n");
3530 if (EndPoints.empty())
3531 return;
3533 // Recompute the parts of the live range we had to remove because of
3534 // CR_Replace conflicts.
3535 LLVM_DEBUG({
3536 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3537 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3538 dbgs() << EndPoints[i];
3539 if (i != n-1)
3540 dbgs() << ',';
3542 dbgs() << ": " << LRange << '\n';
3544 LIS->extendToIndices(LRange, EndPoints);
3547 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
3548 const LiveRange &ToMerge,
3549 LaneBitmask LaneMask,
3550 CoalescerPair &CP,
3551 unsigned ComposeSubRegIdx) {
3552 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3553 LI.refineSubRanges(
3554 Allocator, LaneMask,
3555 [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
3556 if (SR.empty()) {
3557 SR.assign(ToMerge, Allocator);
3558 } else {
3559 // joinSubRegRange() destroys the merged range, so we need a copy.
3560 LiveRange RangeCopy(ToMerge, Allocator);
3561 joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
3564 *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
3567 bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
3568 if (LI.valnos.size() < LargeIntervalSizeThreshold)
3569 return false;
3570 auto &Counter = LargeLIVisitCounter[LI.reg()];
3571 if (Counter < LargeIntervalFreqThreshold) {
3572 Counter++;
3573 return false;
3575 return true;
3578 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
3579 SmallVector<VNInfo*, 16> NewVNInfo;
3580 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
3581 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
3582 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
3583 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
3584 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3585 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
3586 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3588 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
3590 if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS))
3591 return false;
3593 // First compute NewVNInfo and the simple value mappings.
3594 // Detect impossible conflicts early.
3595 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3596 return false;
3598 // Some conflicts can only be resolved after all values have been mapped.
3599 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3600 return false;
3602 // All clear, the live ranges can be merged.
3603 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
3604 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
3606 // Transform lanemasks from the LHS to masks in the coalesced register and
3607 // create initial subranges if necessary.
3608 unsigned DstIdx = CP.getDstIdx();
3609 if (!LHS.hasSubRanges()) {
3610 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
3611 : TRI->getSubRegIndexLaneMask(DstIdx);
3612 // LHS must support subregs or we wouldn't be in this codepath.
3613 assert(Mask.any());
3614 LHS.createSubRangeFrom(Allocator, Mask, LHS);
3615 } else if (DstIdx != 0) {
3616 // Transform LHS lanemasks to new register class if necessary.
3617 for (LiveInterval::SubRange &R : LHS.subranges()) {
3618 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3619 R.LaneMask = Mask;
3622 LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
3623 << '\n');
3625 // Determine lanemasks of RHS in the coalesced register and merge subranges.
3626 unsigned SrcIdx = CP.getSrcIdx();
3627 if (!RHS.hasSubRanges()) {
3628 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3629 : TRI->getSubRegIndexLaneMask(SrcIdx);
3630 mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
3631 } else {
3632 // Pair up subranges and merge.
3633 for (LiveInterval::SubRange &R : RHS.subranges()) {
3634 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3635 mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
3638 LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
3640 // Pruning implicit defs from subranges may result in the main range
3641 // having stale segments.
3642 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3644 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3645 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3648 // The merging algorithm in LiveInterval::join() can't handle conflicting
3649 // value mappings, so we need to remove any live ranges that overlap a
3650 // CR_Replace resolution. Collect a set of end points that can be used to
3651 // restore the live range after joining.
3652 SmallVector<SlotIndex, 8> EndPoints;
3653 LHSVals.pruneValues(RHSVals, EndPoints, true);
3654 RHSVals.pruneValues(LHSVals, EndPoints, true);
3656 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3657 // registers to require trimming.
3658 SmallVector<Register, 8> ShrinkRegs;
3659 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3660 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3661 while (!ShrinkRegs.empty())
3662 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3664 // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3665 checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3667 // If the RHS covers any PHI locations that were tracked for debug-info, we
3668 // must update tracking information to reflect the join.
3669 auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
3670 if (RegIt != RegToPHIIdx.end()) {
3671 // Iterate over all the debug instruction numbers assigned this register.
3672 for (unsigned InstID : RegIt->second) {
3673 auto PHIIt = PHIValToPos.find(InstID);
3674 assert(PHIIt != PHIValToPos.end());
3675 const SlotIndex &SI = PHIIt->second.SI;
3677 // Does the RHS cover the position of this PHI?
3678 auto LII = RHS.find(SI);
3679 if (LII == RHS.end() || LII->start > SI)
3680 continue;
3682 // Accept two kinds of subregister movement:
3683 // * When we merge from one register class into a larger register:
3684 // %1:gr16 = some-inst
3685 // ->
3686 // %2:gr32.sub_16bit = some-inst
3687 // * When the PHI is already in a subregister, and the larger class
3688 // is coalesced:
3689 // %2:gr32.sub_16bit = some-inst
3690 // %3:gr32 = COPY %2
3691 // ->
3692 // %3:gr32.sub_16bit = some-inst
3693 // Test for subregister move:
3694 if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
3695 // If we're moving between different subregisters, ignore this join.
3696 // The PHI will not get a location, dropping variable locations.
3697 if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
3698 continue;
3700 // Update our tracking of where the PHI is.
3701 PHIIt->second.Reg = CP.getDstReg();
3703 // If we merge into a sub-register of a larger class (test above),
3704 // update SubReg.
3705 if (CP.getSrcIdx() != 0)
3706 PHIIt->second.SubReg = CP.getSrcIdx();
3709 // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
3710 // different VRegs now. Copy old collection of debug instruction numbers and
3711 // erase the old one:
3712 auto InstrNums = RegIt->second;
3713 RegToPHIIdx.erase(RegIt);
3715 // There might already be PHIs being tracked in the destination VReg. Insert
3716 // into an existing tracking collection, or insert a new one.
3717 RegIt = RegToPHIIdx.find(CP.getDstReg());
3718 if (RegIt != RegToPHIIdx.end())
3719 RegIt->second.insert(RegIt->second.end(), InstrNums.begin(),
3720 InstrNums.end());
3721 else
3722 RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
3725 // Join RHS into LHS.
3726 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3728 // Kill flags are going to be wrong if the live ranges were overlapping.
3729 // Eventually, we should simply clear all kill flags when computing live
3730 // ranges. They are reinserted after register allocation.
3731 MRI->clearKillFlags(LHS.reg());
3732 MRI->clearKillFlags(RHS.reg());
3734 if (!EndPoints.empty()) {
3735 // Recompute the parts of the live range we had to remove because of
3736 // CR_Replace conflicts.
3737 LLVM_DEBUG({
3738 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3739 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3740 dbgs() << EndPoints[i];
3741 if (i != n-1)
3742 dbgs() << ',';
3744 dbgs() << ": " << LHS << '\n';
3746 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
3749 return true;
3752 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3753 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3756 void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF)
3758 const SlotIndexes &Slots = *LIS->getSlotIndexes();
3759 SmallVector<MachineInstr *, 8> ToInsert;
3761 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3762 // vreg => DbgValueLoc map.
3763 auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3764 for (auto *X : ToInsert) {
3765 for (const auto &Op : X->debug_operands()) {
3766 if (Op.isReg() && Op.getReg().isVirtual())
3767 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
3771 ToInsert.clear();
3774 // Iterate over all instructions, collecting them into the ToInsert vector.
3775 // Once a non-debug instruction is found, record the slot index of the
3776 // collected DBG_VALUEs.
3777 for (auto &MBB : MF) {
3778 SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3780 for (auto &MI : MBB) {
3781 if (MI.isDebugValue()) {
3782 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
3783 return MO.isReg() && MO.getReg().isVirtual();
3785 ToInsert.push_back(&MI);
3786 } else if (!MI.isDebugOrPseudoInstr()) {
3787 CurrentSlot = Slots.getInstructionIndex(MI);
3788 CloseNewDVRange(CurrentSlot);
3792 // Close range of DBG_VALUEs at the end of blocks.
3793 CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3796 // Sort all DBG_VALUEs we've seen by slot number.
3797 for (auto &Pair : DbgVRegToValues)
3798 llvm::sort(Pair.second);
3801 void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3802 LiveRange &LHS,
3803 JoinVals &LHSVals,
3804 LiveRange &RHS,
3805 JoinVals &RHSVals) {
3806 auto ScanForDstReg = [&](Register Reg) {
3807 checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3810 auto ScanForSrcReg = [&](Register Reg) {
3811 checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3814 // Scan for unsound updates of both the source and destination register.
3815 ScanForSrcReg(CP.getSrcReg());
3816 ScanForDstReg(CP.getDstReg());
3819 void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
3820 LiveRange &OtherLR,
3821 LiveRange &RegLR,
3822 JoinVals &RegVals) {
3823 // Are there any DBG_VALUEs to examine?
3824 auto VRegMapIt = DbgVRegToValues.find(Reg);
3825 if (VRegMapIt == DbgVRegToValues.end())
3826 return;
3828 auto &DbgValueSet = VRegMapIt->second;
3829 auto DbgValueSetIt = DbgValueSet.begin();
3830 auto SegmentIt = OtherLR.begin();
3832 bool LastUndefResult = false;
3833 SlotIndex LastUndefIdx;
3835 // If the "Other" register is live at a slot Idx, test whether Reg can
3836 // safely be merged with it, or should be marked undef.
3837 auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3838 &LastUndefIdx](SlotIndex Idx) -> bool {
3839 // Our worst-case performance typically happens with asan, causing very
3840 // many DBG_VALUEs of the same location. Cache a copy of the most recent
3841 // result for this edge-case.
3842 if (LastUndefIdx == Idx)
3843 return LastUndefResult;
3845 // If the other range was live, and Reg's was not, the register coalescer
3846 // will not have tried to resolve any conflicts. We don't know whether
3847 // the DBG_VALUE will refer to the same value number, so it must be made
3848 // undef.
3849 auto OtherIt = RegLR.find(Idx);
3850 if (OtherIt == RegLR.end())
3851 return true;
3853 // Both the registers were live: examine the conflict resolution record for
3854 // the value number Reg refers to. CR_Keep meant that this value number
3855 // "won" and the merged register definitely refers to that value. CR_Erase
3856 // means the value number was a redundant copy of the other value, which
3857 // was coalesced and Reg deleted. It's safe to refer to the other register
3858 // (which will be the source of the copy).
3859 auto Resolution = RegVals.getResolution(OtherIt->valno->id);
3860 LastUndefResult = Resolution != JoinVals::CR_Keep &&
3861 Resolution != JoinVals::CR_Erase;
3862 LastUndefIdx = Idx;
3863 return LastUndefResult;
3866 // Iterate over both the live-range of the "Other" register, and the set of
3867 // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
3868 // slot index. This relies on the DbgValueSet being ordered.
3869 while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
3870 if (DbgValueSetIt->first < SegmentIt->end) {
3871 // "Other" is live and there is a DBG_VALUE of Reg: test if we should
3872 // set it undef.
3873 if (DbgValueSetIt->first >= SegmentIt->start) {
3874 bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
3875 bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
3876 if (HasReg && ShouldUndefReg) {
3877 // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
3878 DbgValueSetIt->second->setDebugValueUndef();
3879 continue;
3882 ++DbgValueSetIt;
3883 } else {
3884 ++SegmentIt;
3889 namespace {
3891 /// Information concerning MBB coalescing priority.
3892 struct MBBPriorityInfo {
3893 MachineBasicBlock *MBB;
3894 unsigned Depth;
3895 bool IsSplit;
3897 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
3898 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
3901 } // end anonymous namespace
3903 /// C-style comparator that sorts first based on the loop depth of the basic
3904 /// block (the unsigned), and then on the MBB number.
3906 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
3907 static int compareMBBPriority(const MBBPriorityInfo *LHS,
3908 const MBBPriorityInfo *RHS) {
3909 // Deeper loops first
3910 if (LHS->Depth != RHS->Depth)
3911 return LHS->Depth > RHS->Depth ? -1 : 1;
3913 // Try to unsplit critical edges next.
3914 if (LHS->IsSplit != RHS->IsSplit)
3915 return LHS->IsSplit ? -1 : 1;
3917 // Prefer blocks that are more connected in the CFG. This takes care of
3918 // the most difficult copies first while intervals are short.
3919 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3920 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3921 if (cl != cr)
3922 return cl > cr ? -1 : 1;
3924 // As a last resort, sort by block number.
3925 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3928 /// \returns true if the given copy uses or defines a local live range.
3929 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
3930 if (!Copy->isCopy())
3931 return false;
3933 if (Copy->getOperand(1).isUndef())
3934 return false;
3936 Register SrcReg = Copy->getOperand(1).getReg();
3937 Register DstReg = Copy->getOperand(0).getReg();
3938 if (SrcReg.isPhysical() || DstReg.isPhysical())
3939 return false;
3941 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
3942 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
3945 void RegisterCoalescer::lateLiveIntervalUpdate() {
3946 for (Register reg : ToBeUpdated) {
3947 if (!LIS->hasInterval(reg))
3948 continue;
3949 LiveInterval &LI = LIS->getInterval(reg);
3950 shrinkToUses(&LI, &DeadDefs);
3951 if (!DeadDefs.empty())
3952 eliminateDeadDefs();
3954 ToBeUpdated.clear();
3957 bool RegisterCoalescer::
3958 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
3959 bool Progress = false;
3960 for (MachineInstr *&MI : CurrList) {
3961 if (!MI)
3962 continue;
3963 // Skip instruction pointers that have already been erased, for example by
3964 // dead code elimination.
3965 if (ErasedInstrs.count(MI)) {
3966 MI = nullptr;
3967 continue;
3969 bool Again = false;
3970 bool Success = joinCopy(MI, Again);
3971 Progress |= Success;
3972 if (Success || !Again)
3973 MI = nullptr;
3975 return Progress;
3978 /// Check if DstReg is a terminal node.
3979 /// I.e., it does not have any affinity other than \p Copy.
3980 static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
3981 const MachineRegisterInfo *MRI) {
3982 assert(Copy.isCopyLike());
3983 // Check if the destination of this copy as any other affinity.
3984 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
3985 if (&MI != &Copy && MI.isCopyLike())
3986 return false;
3987 return true;
3990 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
3991 assert(Copy.isCopyLike());
3992 if (!UseTerminalRule)
3993 return false;
3994 Register SrcReg, DstReg;
3995 unsigned SrcSubReg = 0, DstSubReg = 0;
3996 if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
3997 return false;
3998 // Check if the destination of this copy has any other affinity.
3999 if (DstReg.isPhysical() ||
4000 // If SrcReg is a physical register, the copy won't be coalesced.
4001 // Ignoring it may have other side effect (like missing
4002 // rematerialization). So keep it.
4003 SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
4004 return false;
4006 // DstReg is a terminal node. Check if it interferes with any other
4007 // copy involving SrcReg.
4008 const MachineBasicBlock *OrigBB = Copy.getParent();
4009 const LiveInterval &DstLI = LIS->getInterval(DstReg);
4010 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
4011 // Technically we should check if the weight of the new copy is
4012 // interesting compared to the other one and update the weight
4013 // of the copies accordingly. However, this would only work if
4014 // we would gather all the copies first then coalesce, whereas
4015 // right now we interleave both actions.
4016 // For now, just consider the copies that are in the same block.
4017 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
4018 continue;
4019 Register OtherSrcReg, OtherReg;
4020 unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
4021 if (!isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
4022 OtherSubReg))
4023 return false;
4024 if (OtherReg == SrcReg)
4025 OtherReg = OtherSrcReg;
4026 // Check if OtherReg is a non-terminal.
4027 if (OtherReg.isPhysical() || isTerminalReg(OtherReg, MI, MRI))
4028 continue;
4029 // Check that OtherReg interfere with DstReg.
4030 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
4031 LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
4032 << '\n');
4033 return true;
4036 return false;
4039 void
4040 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
4041 LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
4043 // Collect all copy-like instructions in MBB. Don't start coalescing anything
4044 // yet, it might invalidate the iterator.
4045 const unsigned PrevSize = WorkList.size();
4046 if (JoinGlobalCopies) {
4047 SmallVector<MachineInstr*, 2> LocalTerminals;
4048 SmallVector<MachineInstr*, 2> GlobalTerminals;
4049 // Coalesce copies bottom-up to coalesce local defs before local uses. They
4050 // are not inherently easier to resolve, but slightly preferable until we
4051 // have local live range splitting. In particular this is required by
4052 // cmp+jmp macro fusion.
4053 for (MachineInstr &MI : *MBB) {
4054 if (!MI.isCopyLike())
4055 continue;
4056 bool ApplyTerminalRule = applyTerminalRule(MI);
4057 if (isLocalCopy(&MI, LIS)) {
4058 if (ApplyTerminalRule)
4059 LocalTerminals.push_back(&MI);
4060 else
4061 LocalWorkList.push_back(&MI);
4062 } else {
4063 if (ApplyTerminalRule)
4064 GlobalTerminals.push_back(&MI);
4065 else
4066 WorkList.push_back(&MI);
4069 // Append the copies evicted by the terminal rule at the end of the list.
4070 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
4071 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
4073 else {
4074 SmallVector<MachineInstr*, 2> Terminals;
4075 for (MachineInstr &MII : *MBB)
4076 if (MII.isCopyLike()) {
4077 if (applyTerminalRule(MII))
4078 Terminals.push_back(&MII);
4079 else
4080 WorkList.push_back(&MII);
4082 // Append the copies evicted by the terminal rule at the end of the list.
4083 WorkList.append(Terminals.begin(), Terminals.end());
4085 // Try coalescing the collected copies immediately, and remove the nulls.
4086 // This prevents the WorkList from getting too large since most copies are
4087 // joinable on the first attempt.
4088 MutableArrayRef<MachineInstr*>
4089 CurrList(WorkList.begin() + PrevSize, WorkList.end());
4090 if (copyCoalesceWorkList(CurrList))
4091 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
4092 nullptr), WorkList.end());
4095 void RegisterCoalescer::coalesceLocals() {
4096 copyCoalesceWorkList(LocalWorkList);
4097 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
4098 if (LocalWorkList[j])
4099 WorkList.push_back(LocalWorkList[j]);
4101 LocalWorkList.clear();
4104 void RegisterCoalescer::joinAllIntervals() {
4105 LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
4106 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
4108 std::vector<MBBPriorityInfo> MBBs;
4109 MBBs.reserve(MF->size());
4110 for (MachineBasicBlock &MBB : *MF) {
4111 MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
4112 JoinSplitEdges && isSplitEdge(&MBB)));
4114 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
4116 // Coalesce intervals in MBB priority order.
4117 unsigned CurrDepth = std::numeric_limits<unsigned>::max();
4118 for (MBBPriorityInfo &MBB : MBBs) {
4119 // Try coalescing the collected local copies for deeper loops.
4120 if (JoinGlobalCopies && MBB.Depth < CurrDepth) {
4121 coalesceLocals();
4122 CurrDepth = MBB.Depth;
4124 copyCoalesceInMBB(MBB.MBB);
4126 lateLiveIntervalUpdate();
4127 coalesceLocals();
4129 // Joining intervals can allow other intervals to be joined. Iteratively join
4130 // until we make no progress.
4131 while (copyCoalesceWorkList(WorkList))
4132 /* empty */ ;
4133 lateLiveIntervalUpdate();
4136 void RegisterCoalescer::releaseMemory() {
4137 ErasedInstrs.clear();
4138 WorkList.clear();
4139 DeadDefs.clear();
4140 InflateRegs.clear();
4141 LargeLIVisitCounter.clear();
4144 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
4145 LLVM_DEBUG(dbgs() << "********** REGISTER COALESCER **********\n"
4146 << "********** Function: " << fn.getName() << '\n');
4148 // Variables changed between a setjmp and a longjump can have undefined value
4149 // after the longjmp. This behaviour can be observed if such a variable is
4150 // spilled, so longjmp won't restore the value in the spill slot.
4151 // RegisterCoalescer should not run in functions with a setjmp to avoid
4152 // merging such undefined variables with predictable ones.
4154 // TODO: Could specifically disable coalescing registers live across setjmp
4155 // calls
4156 if (fn.exposesReturnsTwice()) {
4157 LLVM_DEBUG(
4158 dbgs() << "* Skipped as it exposes functions that returns twice.\n");
4159 return false;
4162 MF = &fn;
4163 MRI = &fn.getRegInfo();
4164 const TargetSubtargetInfo &STI = fn.getSubtarget();
4165 TRI = STI.getRegisterInfo();
4166 TII = STI.getInstrInfo();
4167 LIS = &getAnalysis<LiveIntervals>();
4168 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4169 Loops = &getAnalysis<MachineLoopInfo>();
4170 if (EnableGlobalCopies == cl::BOU_UNSET)
4171 JoinGlobalCopies = STI.enableJoinGlobalCopies();
4172 else
4173 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
4175 // If there are PHIs tracked by debug-info, they will need updating during
4176 // coalescing. Build an index of those PHIs to ease updating.
4177 SlotIndexes *Slots = LIS->getSlotIndexes();
4178 for (const auto &DebugPHI : MF->DebugPHIPositions) {
4179 MachineBasicBlock *MBB = DebugPHI.second.MBB;
4180 Register Reg = DebugPHI.second.Reg;
4181 unsigned SubReg = DebugPHI.second.SubReg;
4182 SlotIndex SI = Slots->getMBBStartIdx(MBB);
4183 PHIValPos P = {SI, Reg, SubReg};
4184 PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
4185 RegToPHIIdx[Reg].push_back(DebugPHI.first);
4188 // The MachineScheduler does not currently require JoinSplitEdges. This will
4189 // either be enabled unconditionally or replaced by a more general live range
4190 // splitting optimization.
4191 JoinSplitEdges = EnableJoinSplits;
4193 if (VerifyCoalescing)
4194 MF->verify(this, "Before register coalescing");
4196 DbgVRegToValues.clear();
4197 buildVRegToDbgValueMap(fn);
4199 RegClassInfo.runOnMachineFunction(fn);
4201 // Join (coalesce) intervals if requested.
4202 if (EnableJoining)
4203 joinAllIntervals();
4205 // After deleting a lot of copies, register classes may be less constrained.
4206 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
4207 // DPR inflation.
4208 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
4209 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
4210 InflateRegs.end());
4211 LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
4212 << " regs.\n");
4213 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
4214 Register Reg = InflateRegs[i];
4215 if (MRI->reg_nodbg_empty(Reg))
4216 continue;
4217 if (MRI->recomputeRegClass(Reg)) {
4218 LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
4219 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
4220 ++NumInflated;
4222 LiveInterval &LI = LIS->getInterval(Reg);
4223 if (LI.hasSubRanges()) {
4224 // If the inflated register class does not support subregisters anymore
4225 // remove the subranges.
4226 if (!MRI->shouldTrackSubRegLiveness(Reg)) {
4227 LI.clearSubRanges();
4228 } else {
4229 #ifndef NDEBUG
4230 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
4231 // If subranges are still supported, then the same subregs
4232 // should still be supported.
4233 for (LiveInterval::SubRange &S : LI.subranges()) {
4234 assert((S.LaneMask & ~MaxMask).none());
4236 #endif
4242 // After coalescing, update any PHIs that are being tracked by debug-info
4243 // with their new VReg locations.
4244 for (auto &p : MF->DebugPHIPositions) {
4245 auto it = PHIValToPos.find(p.first);
4246 assert(it != PHIValToPos.end());
4247 p.second.Reg = it->second.Reg;
4248 p.second.SubReg = it->second.SubReg;
4251 PHIValToPos.clear();
4252 RegToPHIIdx.clear();
4254 LLVM_DEBUG(dump());
4255 if (VerifyCoalescing)
4256 MF->verify(this, "After register coalescing");
4257 return true;
4260 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
4261 LIS->print(O, m);