1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #include "RegisterCoalescer.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/LiveRangeEdit.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegisterClassInfo.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "regalloc"
47 STATISTIC(numJoins , "Number of interval joins performed");
48 STATISTIC(numCrossRCs , "Number of cross class joins performed");
49 STATISTIC(numCommutes , "Number of instruction commuting performed");
50 STATISTIC(numExtends , "Number of copies extended");
51 STATISTIC(NumReMats , "Number of instructions re-materialized");
52 STATISTIC(NumInflated , "Number of register classes inflated");
53 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
54 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
57 EnableJoining("join-liveintervals",
58 cl::desc("Coalesce copies (default=true)"),
61 static cl::opt<bool> UseTerminalRule("terminal-rule",
62 cl::desc("Apply the terminal rule"),
65 /// Temporary flag to test critical edge unsplitting.
67 EnableJoinSplits("join-splitedges",
68 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
70 /// Temporary flag to test global copy optimization.
71 static cl::opt<cl::boolOrDefault>
72 EnableGlobalCopies("join-globalcopies",
73 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
74 cl::init(cl::BOU_UNSET), cl::Hidden);
77 VerifyCoalescing("verify-coalescing",
78 cl::desc("Verify machine instrs before and after register coalescing"),
82 class RegisterCoalescer : public MachineFunctionPass,
83 private LiveRangeEdit::Delegate {
85 MachineRegisterInfo* MRI;
86 const TargetMachine* TM;
87 const TargetRegisterInfo* TRI;
88 const TargetInstrInfo* TII;
90 const MachineLoopInfo* Loops;
92 RegisterClassInfo RegClassInfo;
94 /// A LaneMask to remember on which subregister live ranges we need to call
95 /// shrinkToUses() later.
98 /// True if the main range of the currently coalesced intervals should be
99 /// checked for smaller live intervals.
100 bool ShrinkMainRange;
102 /// \brief True if the coalescer should aggressively coalesce global copies
103 /// in favor of keeping local copies.
104 bool JoinGlobalCopies;
106 /// \brief True if the coalescer should aggressively coalesce fall-thru
107 /// blocks exclusively containing copies.
110 /// Copy instructions yet to be coalesced.
111 SmallVector<MachineInstr*, 8> WorkList;
112 SmallVector<MachineInstr*, 8> LocalWorkList;
114 /// Set of instruction pointers that have been erased, and
115 /// that may be present in WorkList.
116 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
118 /// Dead instructions that are about to be deleted.
119 SmallVector<MachineInstr*, 8> DeadDefs;
121 /// Virtual registers to be considered for register class inflation.
122 SmallVector<unsigned, 8> InflateRegs;
124 /// Recursively eliminate dead defs in DeadDefs.
125 void eliminateDeadDefs();
127 /// LiveRangeEdit callback for eliminateDeadDefs().
128 void LRE_WillEraseInstruction(MachineInstr *MI) override;
130 /// Coalesce the LocalWorkList.
131 void coalesceLocals();
133 /// Join compatible live intervals
134 void joinAllIntervals();
136 /// Coalesce copies in the specified MBB, putting
137 /// copies that cannot yet be coalesced into WorkList.
138 void copyCoalesceInMBB(MachineBasicBlock *MBB);
140 /// Tries to coalesce all copies in CurrList. Returns true if any progress
142 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
144 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
145 /// src/dst of the copy instruction CopyMI. This returns true if the copy
146 /// was successfully coalesced away. If it is not currently possible to
147 /// coalesce this interval, but it may be possible if other things get
148 /// coalesced, then it returns true by reference in 'Again'.
149 bool joinCopy(MachineInstr *TheCopy, bool &Again);
151 /// Attempt to join these two intervals. On failure, this
152 /// returns false. The output "SrcInt" will not have been modified, so we
153 /// can use this information below to update aliases.
154 bool joinIntervals(CoalescerPair &CP);
156 /// Attempt joining two virtual registers. Return true on success.
157 bool joinVirtRegs(CoalescerPair &CP);
159 /// Attempt joining with a reserved physreg.
160 bool joinReservedPhysReg(CoalescerPair &CP);
162 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
163 /// Subranges in @p LI which only partially interfere with the desired
164 /// LaneMask are split as necessary. @p LaneMask are the lanes that
165 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
166 /// lanemasks already adjusted to the coalesced register.
167 /// @returns false if live range conflicts couldn't get resolved.
168 bool mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
169 unsigned LaneMask, CoalescerPair &CP);
171 /// Join the liveranges of two subregisters. Joins @p RRange into
172 /// @p LRange, @p RRange may be invalid afterwards.
173 /// @returns false if live range conflicts couldn't get resolved.
174 bool joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
175 unsigned LaneMask, const CoalescerPair &CP);
177 /// We found a non-trivially-coalescable copy. If the source value number is
178 /// defined by a copy from the destination reg see if we can merge these two
179 /// destination reg valno# into a single value number, eliminating a copy.
180 /// This returns true if an interval was modified.
181 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
183 /// Return true if there are definitions of IntB
184 /// other than BValNo val# that can reach uses of AValno val# of IntA.
185 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
186 VNInfo *AValNo, VNInfo *BValNo);
188 /// We found a non-trivially-coalescable copy.
189 /// If the source value number is defined by a commutable instruction and
190 /// its other operand is coalesced to the copy dest register, see if we
191 /// can transform the copy into a noop by commuting the definition.
192 /// This returns true if an interval was modified.
193 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
195 /// If the source of a copy is defined by a
196 /// trivial computation, replace the copy by rematerialize the definition.
197 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
200 /// Return true if a copy involving a physreg should be joined.
201 bool canJoinPhys(const CoalescerPair &CP);
203 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
204 /// number if it is not zero. If DstReg is a physical register and the
205 /// existing subregister number of the def / use being updated is not zero,
206 /// make sure to set it to the correct physical subregister.
207 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
209 /// Handle copies of undef values.
210 /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
211 bool eliminateUndefCopy(MachineInstr *CopyMI);
213 /// Check whether or not we should apply the terminal rule on the
214 /// destination (Dst) of \p Copy.
215 /// When the terminal rule applies, Copy is not profitable to
217 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
218 /// at least one interference (Dst, Dst2). If Dst is terminal, the
219 /// terminal rule consists in checking that at least one of
220 /// interfering node, say Dst2, has an affinity of equal or greater
222 /// In that case, Dst2 and Dst will not be able to be both coalesced
223 /// with Src. Since Dst2 exposes more coalescing opportunities than
224 /// Dst, we can drop \p Copy.
225 bool applyTerminalRule(const MachineInstr &Copy) const;
228 static char ID; ///< Class identification, replacement for typeinfo
229 RegisterCoalescer() : MachineFunctionPass(ID) {
230 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
233 void getAnalysisUsage(AnalysisUsage &AU) const override;
235 void releaseMemory() override;
237 /// This is the pass entry point.
238 bool runOnMachineFunction(MachineFunction&) override;
240 /// Implement the dump method.
241 void print(raw_ostream &O, const Module* = nullptr) const override;
243 } // end anonymous namespace
245 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
247 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
248 "Simple Register Coalescing", false, false)
249 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
250 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
251 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
252 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
253 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
254 "Simple Register Coalescing", false, false)
256 char RegisterCoalescer::ID = 0;
258 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
259 unsigned &Src, unsigned &Dst,
260 unsigned &SrcSub, unsigned &DstSub) {
262 Dst = MI->getOperand(0).getReg();
263 DstSub = MI->getOperand(0).getSubReg();
264 Src = MI->getOperand(1).getReg();
265 SrcSub = MI->getOperand(1).getSubReg();
266 } else if (MI->isSubregToReg()) {
267 Dst = MI->getOperand(0).getReg();
268 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
269 MI->getOperand(3).getImm());
270 Src = MI->getOperand(2).getReg();
271 SrcSub = MI->getOperand(2).getSubReg();
277 /// Return true if this block should be vacated by the coalescer to eliminate
278 /// branches. The important cases to handle in the coalescer are critical edges
279 /// split during phi elimination which contain only copies. Simple blocks that
280 /// contain non-branches should also be vacated, but this can be handled by an
281 /// earlier pass similar to early if-conversion.
282 static bool isSplitEdge(const MachineBasicBlock *MBB) {
283 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
286 for (const auto &MI : *MBB) {
287 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
293 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
297 Flipped = CrossClass = false;
299 unsigned Src, Dst, SrcSub, DstSub;
300 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
302 Partial = SrcSub || DstSub;
304 // If one register is a physreg, it must be Dst.
305 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
306 if (TargetRegisterInfo::isPhysicalRegister(Dst))
309 std::swap(SrcSub, DstSub);
313 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
315 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
316 // Eliminate DstSub on a physreg.
318 Dst = TRI.getSubReg(Dst, DstSub);
319 if (!Dst) return false;
323 // Eliminate SrcSub by picking a corresponding Dst superregister.
325 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
326 if (!Dst) return false;
327 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
331 // Both registers are virtual.
332 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
333 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
335 // Both registers have subreg indices.
336 if (SrcSub && DstSub) {
337 // Copies between different sub-registers are never coalescable.
338 if (Src == Dst && SrcSub != DstSub)
341 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
346 // SrcReg will be merged with a sub-register of DstReg.
348 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
350 // DstReg will be merged with a sub-register of SrcReg.
352 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
354 // This is a straight copy without sub-registers.
355 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
358 // The combined constraint may be impossible to satisfy.
362 // Prefer SrcReg to be a sub-register of DstReg.
363 // FIXME: Coalescer should support subregs symmetrically.
364 if (DstIdx && !SrcIdx) {
366 std::swap(SrcIdx, DstIdx);
370 CrossClass = NewRC != DstRC || NewRC != SrcRC;
372 // Check our invariants
373 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
374 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
375 "Cannot have a physical SubIdx");
381 bool CoalescerPair::flip() {
382 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
384 std::swap(SrcReg, DstReg);
385 std::swap(SrcIdx, DstIdx);
390 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
393 unsigned Src, Dst, SrcSub, DstSub;
394 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
397 // Find the virtual register that is SrcReg.
400 std::swap(SrcSub, DstSub);
401 } else if (Src != SrcReg) {
405 // Now check that Dst matches DstReg.
406 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
407 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
409 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
410 // DstSub could be set for a physreg from INSERT_SUBREG.
412 Dst = TRI.getSubReg(Dst, DstSub);
415 return DstReg == Dst;
416 // This is a partial register copy. Check that the parts match.
417 return TRI.getSubReg(DstReg, SrcSub) == Dst;
419 // DstReg is virtual.
422 // Registers match, do the subregisters line up?
423 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
424 TRI.composeSubRegIndices(DstIdx, DstSub);
428 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
429 AU.setPreservesCFG();
430 AU.addRequired<AliasAnalysis>();
431 AU.addRequired<LiveIntervals>();
432 AU.addPreserved<LiveIntervals>();
433 AU.addPreserved<SlotIndexes>();
434 AU.addRequired<MachineLoopInfo>();
435 AU.addPreserved<MachineLoopInfo>();
436 AU.addPreservedID(MachineDominatorsID);
437 MachineFunctionPass::getAnalysisUsage(AU);
440 void RegisterCoalescer::eliminateDeadDefs() {
441 SmallVector<unsigned, 8> NewRegs;
442 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
443 nullptr, this).eliminateDeadDefs(DeadDefs);
446 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
447 // MI may be in WorkList. Make sure we don't visit it.
448 ErasedInstrs.insert(MI);
451 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
452 MachineInstr *CopyMI) {
453 assert(!CP.isPartial() && "This doesn't work for partial copies.");
454 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
457 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
459 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
460 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
462 // We have a non-trivially-coalescable copy with IntA being the source and
463 // IntB being the dest, thus this defines a value number in IntB. If the
464 // source value number (in IntA) is defined by a copy from B, see if we can
465 // merge these two pieces of B into a single value number, eliminating a copy.
470 // B1 = A3 <- this copy
472 // In this case, B0 can be extended to where the B1 copy lives, allowing the
473 // B1 value number to be replaced with B0 (which simplifies the B
476 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
477 // the example above.
478 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
479 if (BS == IntB.end()) return false;
480 VNInfo *BValNo = BS->valno;
482 // Get the location that B is defined at. Two options: either this value has
483 // an unknown definition point or it is defined at CopyIdx. If unknown, we
485 if (BValNo->def != CopyIdx) return false;
487 // AValNo is the value number in A that defines the copy, A3 in the example.
488 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
489 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
490 // The live segment might not exist after fun with physreg coalescing.
491 if (AS == IntA.end()) return false;
492 VNInfo *AValNo = AS->valno;
494 // If AValNo is defined as a copy from IntB, we can potentially process this.
495 // Get the instruction that defines this value number.
496 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
497 // Don't allow any partial copies, even if isCoalescable() allows them.
498 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
501 // Get the Segment in IntB that this value number starts with.
502 LiveInterval::iterator ValS =
503 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
504 if (ValS == IntB.end())
507 // Make sure that the end of the live segment is inside the same block as
509 MachineInstr *ValSEndInst =
510 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
511 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
514 // Okay, we now know that ValS ends in the same block that the CopyMI
515 // live-range starts. If there are no intervening live segments between them
516 // in IntB, we can merge them.
517 if (ValS+1 != BS) return false;
519 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
521 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
522 // We are about to delete CopyMI, so need to remove it as the 'instruction
523 // that defines this value #'. Update the valnum with the new defining
525 BValNo->def = FillerStart;
527 // Okay, we can merge them. We need to insert a new liverange:
528 // [ValS.end, BS.begin) of either value number, then we merge the
529 // two value numbers.
530 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
532 // Okay, merge "B1" into the same value number as "B0".
533 if (BValNo != ValS->valno)
534 IntB.MergeValueNumberInto(BValNo, ValS->valno);
536 // Do the same for the subregister segments.
537 for (LiveInterval::SubRange &S : IntB.subranges()) {
538 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
539 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
540 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
541 if (SubBValNo != SubValSNo)
542 S.MergeValueNumberInto(SubBValNo, SubValSNo);
545 DEBUG(dbgs() << " result = " << IntB << '\n');
547 // If the source instruction was killing the source register before the
548 // merge, unset the isKill marker given the live range has been extended.
549 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
551 ValSEndInst->getOperand(UIdx).setIsKill(false);
554 // Rewrite the copy. If the copy instruction was killing the destination
555 // register before the merge, find the last use and trim the live range. That
556 // will also add the isKill marker.
557 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
558 if (AS->end == CopyIdx)
559 LIS->shrinkToUses(&IntA);
565 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
569 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
571 if (LIS->hasPHIKill(IntA, AValNo))
574 for (LiveRange::Segment &ASeg : IntA.segments) {
575 if (ASeg.valno != AValNo) continue;
576 LiveInterval::iterator BI =
577 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
578 if (BI != IntB.begin())
580 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
581 if (BI->valno == BValNo)
583 if (BI->start <= ASeg.start && BI->end > ASeg.start)
585 if (BI->start > ASeg.start && BI->start < ASeg.end)
592 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
593 /// range @Dst and use value number @p DstValNo there.
594 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
595 const LiveRange &Src, const VNInfo *SrcValNo)
597 for (const LiveRange::Segment &S : Src.segments) {
598 if (S.valno != SrcValNo)
600 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
604 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
605 MachineInstr *CopyMI) {
606 assert(!CP.isPhys());
609 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
611 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
613 // We found a non-trivially-coalescable copy with IntA being the source and
614 // IntB being the dest, thus this defines a value number in IntB. If the
615 // source value number (in IntA) is defined by a commutable instruction and
616 // its other operand is coalesced to the copy dest register, see if we can
617 // transform the copy into a noop by commuting the definition. For example,
619 // A3 = op A2 B0<kill>
621 // B1 = A3 <- this copy
623 // = op A3 <- more uses
627 // B2 = op B0 A2<kill>
629 // B1 = B2 <- now an identity copy
631 // = op B2 <- more uses
633 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
634 // the example above.
635 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
636 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
637 assert(BValNo != nullptr && BValNo->def == CopyIdx);
639 // AValNo is the value number in A that defines the copy, A3 in the example.
640 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
641 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
642 if (AValNo->isPHIDef())
644 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
647 if (!DefMI->isCommutable())
649 // If DefMI is a two-address instruction then commuting it will change the
650 // destination register.
651 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
652 assert(DefIdx != -1);
654 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
656 unsigned Op1, Op2, NewDstIdx;
657 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
661 else if (Op2 == UseOpIdx)
666 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
667 unsigned NewReg = NewDstMO.getReg();
668 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
671 // Make sure there are no other definitions of IntB that would reach the
672 // uses which the new definition can reach.
673 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
676 // If some of the uses of IntA.reg is already coalesced away, return false.
677 // It's not possible to determine whether it's safe to perform the coalescing.
678 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
679 MachineInstr *UseMI = MO.getParent();
680 unsigned OpNo = &MO - &UseMI->getOperand(0);
681 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
682 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
683 if (US == IntA.end() || US->valno != AValNo)
685 // If this use is tied to a def, we can't rewrite the register.
686 if (UseMI->isRegTiedToDefOperand(OpNo))
690 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
693 // At this point we have decided that it is legal to do this
694 // transformation. Start by commuting the instruction.
695 MachineBasicBlock *MBB = DefMI->getParent();
696 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
699 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
700 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
701 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
703 if (NewMI != DefMI) {
704 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
705 MachineBasicBlock::iterator Pos = DefMI;
706 MBB->insert(Pos, NewMI);
710 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
719 // Update uses of IntA of the specific Val# with IntB.
720 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
722 UI != UE; /* ++UI is below because of possible MI removal */) {
723 MachineOperand &UseMO = *UI;
727 MachineInstr *UseMI = UseMO.getParent();
728 if (UseMI->isDebugValue()) {
729 // FIXME These don't have an instruction index. Not clear we have enough
730 // info to decide whether to do this replacement or not. For now do it.
731 UseMO.setReg(NewReg);
734 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
735 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
736 assert(US != IntA.end() && "Use must be live");
737 if (US->valno != AValNo)
739 // Kill flags are no longer accurate. They are recomputed after RA.
740 UseMO.setIsKill(false);
741 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
742 UseMO.substPhysReg(NewReg, *TRI);
744 UseMO.setReg(NewReg);
747 if (!UseMI->isCopy())
749 if (UseMI->getOperand(0).getReg() != IntB.reg ||
750 UseMI->getOperand(0).getSubReg())
753 // This copy will become a noop. If it's defining a new val#, merge it into
755 SlotIndex DefIdx = UseIdx.getRegSlot();
756 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
759 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
760 assert(DVNI->def == DefIdx);
761 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
762 for (LiveInterval::SubRange &S : IntB.subranges()) {
763 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
766 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
767 assert(SubBValNo->def == CopyIdx);
768 S.MergeValueNumberInto(SubDVNI, SubBValNo);
771 ErasedInstrs.insert(UseMI);
772 LIS->RemoveMachineInstrFromMaps(UseMI);
773 UseMI->eraseFromParent();
776 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
778 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
779 if (IntB.hasSubRanges()) {
780 if (!IntA.hasSubRanges()) {
781 unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
782 IntA.createSubRangeFrom(Allocator, Mask, IntA);
784 SlotIndex AIdx = CopyIdx.getRegSlot(true);
785 for (LiveInterval::SubRange &SA : IntA.subranges()) {
786 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
787 assert(ASubValNo != nullptr);
789 unsigned AMask = SA.LaneMask;
790 for (LiveInterval::SubRange &SB : IntB.subranges()) {
791 unsigned BMask = SB.LaneMask;
792 unsigned Common = BMask & AMask;
797 dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
798 unsigned BRest = BMask & ~AMask;
799 LiveInterval::SubRange *CommonRange;
802 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
803 // Duplicate SubRange for newly merged common stuff.
804 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
806 // We van reuse the L SubRange.
807 SB.LaneMask = Common;
810 LiveRange RangeCopy(SB, Allocator);
812 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
813 assert(BSubValNo->def == CopyIdx);
814 BSubValNo->def = ASubValNo->def;
815 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
819 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
820 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
821 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
822 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
827 BValNo->def = AValNo->def;
828 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
829 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
831 LIS->removeVRegDefAt(IntA, AValNo->def);
833 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
838 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
839 /// defining a subregister.
840 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
841 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
842 "This code cannot handle physreg aliasing");
843 for (const MachineOperand &Op : MI.operands()) {
844 if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
846 // Return true if we define the full register or don't care about the value
847 // inside other subregisters.
848 if (Op.getSubReg() == 0 || Op.isUndef())
854 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
855 MachineInstr *CopyMI,
858 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
859 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
860 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
861 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
862 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
865 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
866 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
867 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
868 assert(ValNo && "CopyMI input register not live");
869 if (ValNo->isPHIDef() || ValNo->isUnused())
871 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
874 if (DefMI->isCopyLike()) {
878 if (!TII->isAsCheapAsAMove(DefMI))
880 if (!TII->isTriviallyReMaterializable(DefMI, AA))
882 if (!definesFullReg(*DefMI, SrcReg))
884 bool SawStore = false;
885 if (!DefMI->isSafeToMove(TII, AA, SawStore))
887 const MCInstrDesc &MCID = DefMI->getDesc();
888 if (MCID.getNumDefs() != 1)
890 // Only support subregister destinations when the def is read-undef.
891 MachineOperand &DstOperand = CopyMI->getOperand(0);
892 unsigned CopyDstReg = DstOperand.getReg();
893 if (DstOperand.getSubReg() && !DstOperand.isUndef())
896 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
897 // the register substantially (beyond both source and dest size). This is bad
898 // for performance since it can cascade through a function, introducing many
899 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
900 // around after a few subreg copies).
901 if (SrcIdx && DstIdx)
904 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
905 if (!DefMI->isImplicitDef()) {
906 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
907 unsigned NewDstReg = DstReg;
909 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
910 DefMI->getOperand(0).getSubReg());
912 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
914 // Finally, make sure that the physical subregister that will be
915 // constructed later is permitted for the instruction.
916 if (!DefRC->contains(NewDstReg))
919 // Theoretically, some stack frame reference could exist. Just make sure
920 // it hasn't actually happened.
921 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
922 "Only expect to deal with virtual or physical registers");
926 MachineBasicBlock *MBB = CopyMI->getParent();
927 MachineBasicBlock::iterator MII =
928 std::next(MachineBasicBlock::iterator(CopyMI));
929 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
930 MachineInstr *NewMI = std::prev(MII);
932 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
933 CopyMI->eraseFromParent();
934 ErasedInstrs.insert(CopyMI);
936 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
937 // We need to remember these so we can add intervals once we insert
938 // NewMI into SlotIndexes.
939 SmallVector<unsigned, 4> NewMIImplDefs;
940 for (unsigned i = NewMI->getDesc().getNumOperands(),
941 e = NewMI->getNumOperands(); i != e; ++i) {
942 MachineOperand &MO = NewMI->getOperand(i);
944 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
945 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
946 NewMIImplDefs.push_back(MO.getReg());
950 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
951 const TargetRegisterClass *NewRC = CP.getNewRC();
952 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
954 if (DefRC != nullptr) {
956 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
958 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
959 assert(NewRC && "subreg chosen for remat incompatible with instruction");
961 MRI->setRegClass(DstReg, NewRC);
963 updateRegDefsUses(DstReg, DstReg, DstIdx);
964 NewMI->getOperand(0).setSubReg(NewIdx);
965 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
966 // The New instruction may be defining a sub-register of what's actually
967 // been asked for. If so it must implicitly define the whole thing.
968 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
969 "Only expect virtual or physical registers in remat");
970 NewMI->getOperand(0).setIsDead(true);
971 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
975 // Record small dead def live-ranges for all the subregisters
976 // of the destination register.
977 // Otherwise, variables that live through may miss some
978 // interferences, thus creating invalid allocation.
980 // vreg1 = somedef ; vreg1 GR8
981 // vreg2 = remat ; vreg2 GR32
982 // CL = COPY vreg2.sub_8bit
983 // = somedef vreg1 ; vreg1 GR8
985 // vreg1 = somedef ; vreg1 GR8
986 // ECX<def, dead> = remat ; CL<imp-def>
987 // = somedef vreg1 ; vreg1 GR8
988 // vreg1 will see the inteferences with CL but not with CH since
989 // no live-ranges would have been created for ECX.
991 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
992 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
993 Units.isValid(); ++Units)
994 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
995 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
998 if (NewMI->getOperand(0).getSubReg())
999 NewMI->getOperand(0).setIsUndef();
1001 // CopyMI may have implicit operands, transfer them over to the newly
1002 // rematerialized instruction. And update implicit def interval valnos.
1003 for (unsigned i = CopyMI->getDesc().getNumOperands(),
1004 e = CopyMI->getNumOperands(); i != e; ++i) {
1005 MachineOperand &MO = CopyMI->getOperand(i);
1007 assert(MO.isImplicit() && "No explicit operands after implict operands.");
1008 // Discard VReg implicit defs.
1009 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1010 NewMI->addOperand(MO);
1015 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1016 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1017 unsigned Reg = NewMIImplDefs[i];
1018 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1019 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1020 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1023 DEBUG(dbgs() << "Remat: " << *NewMI);
1026 // The source interval can become smaller because we removed a use.
1027 LIS->shrinkToUses(&SrcInt, &DeadDefs);
1028 if (!DeadDefs.empty()) {
1029 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1030 // to describe DstReg instead.
1031 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1032 MachineInstr *UseMI = UseMO.getParent();
1033 if (UseMI->isDebugValue()) {
1034 UseMO.setReg(DstReg);
1035 DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1038 eliminateDeadDefs();
1044 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1045 // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
1046 // local variables. When we have a copy like:
1048 // %vreg1 = COPY %vreg2<undef>
1050 // We delete the copy and remove the corresponding value number from %vreg1.
1051 // Any uses of that value number are marked as <undef>.
1053 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1054 // CoalescerPair may have a new register class with adjusted subreg indices
1056 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1057 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1059 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1060 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1061 // CopyMI is undef iff SrcReg is not live before the instruction.
1062 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1063 unsigned SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1064 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1065 if ((SR.LaneMask & SrcMask) == 0)
1070 } else if (SrcLI.liveAt(Idx))
1073 DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1075 // Remove any DstReg segments starting at the instruction.
1076 LiveInterval &DstLI = LIS->getInterval(DstReg);
1077 SlotIndex RegIndex = Idx.getRegSlot();
1078 // Remove value or merge with previous one in case of a subregister def.
1079 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1080 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1081 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1083 // The affected subregister segments can be removed.
1084 unsigned DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1085 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1086 if ((SR.LaneMask & DstMask) == 0)
1089 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1090 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1091 SR.removeValNo(SVNI);
1093 DstLI.removeEmptySubRanges();
1095 LIS->removeVRegDefAt(DstLI, RegIndex);
1097 // Mark uses as undef.
1098 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1099 if (MO.isDef() /*|| MO.isUndef()*/)
1101 const MachineInstr &MI = *MO.getParent();
1102 SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
1103 unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1105 if (UseMask != ~0u && DstLI.hasSubRanges()) {
1107 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1108 if ((SR.LaneMask & UseMask) == 0)
1110 if (SR.liveAt(UseIdx)) {
1116 isLive = DstLI.liveAt(UseIdx);
1119 MO.setIsUndef(true);
1120 DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1125 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1128 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1129 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1131 SmallPtrSet<MachineInstr*, 8> Visited;
1132 for (MachineRegisterInfo::reg_instr_iterator
1133 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1135 MachineInstr *UseMI = &*(I++);
1137 // Each instruction can only be rewritten once because sub-register
1138 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1139 // the UseMI operands removes them from the SrcReg use-def chain, but when
1140 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1141 // operands mentioning the virtual register.
1142 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1145 SmallVector<unsigned,8> Ops;
1147 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1149 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1150 // because SrcReg is a sub-register.
1151 if (DstInt && !Reads && SubIdx)
1152 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1154 // Replace SrcReg with DstReg in all UseMI operands.
1155 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1156 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1158 // Adjust <undef> flags in case of sub-register joins. We don't want to
1159 // turn a full def into a read-modify-write sub-register def and vice
1161 if (SubIdx && MO.isDef())
1162 MO.setIsUndef(!Reads);
1164 // A subreg use of a partially undef (super) register may be a complete
1165 // undef use now and then has to be marked that way.
1166 if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
1167 if (!DstInt->hasSubRanges()) {
1168 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1169 unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1170 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1172 unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1173 bool IsUndef = true;
1174 SlotIndex MIIdx = UseMI->isDebugValue()
1175 ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1176 : LIS->getInstructionIndex(UseMI);
1177 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1178 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1179 if ((S.LaneMask & Mask) == 0)
1181 if (S.liveAt(UseIdx)) {
1187 MO.setIsUndef(true);
1188 // We found out some subregister use is actually reading an undefined
1189 // value. In some cases the whole vreg has become undefined at this
1190 // point so we have to potentially shrink the main range if the
1191 // use was ending a live segment there.
1192 LiveQueryResult Q = DstInt->Query(MIIdx);
1193 if (Q.valueOut() == nullptr)
1194 ShrinkMainRange = true;
1199 MO.substPhysReg(DstReg, *TRI);
1201 MO.substVirtReg(DstReg, SubIdx, *TRI);
1205 dbgs() << "\t\tupdated: ";
1206 if (!UseMI->isDebugValue())
1207 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1213 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1214 // Always join simple intervals that are defined by a single copy from a
1215 // reserved register. This doesn't increase register pressure, so it is
1216 // always beneficial.
1217 if (!MRI->isReserved(CP.getDstReg())) {
1218 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1222 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1223 if (JoinVInt.containsOneValue())
1226 DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
1230 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1233 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1235 CoalescerPair CP(*TRI);
1236 if (!CP.setRegisters(CopyMI)) {
1237 DEBUG(dbgs() << "\tNot coalescable.\n");
1241 if (CP.getNewRC()) {
1242 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1243 auto DstRC = MRI->getRegClass(CP.getDstReg());
1244 unsigned SrcIdx = CP.getSrcIdx();
1245 unsigned DstIdx = CP.getDstIdx();
1246 if (CP.isFlipped()) {
1247 std::swap(SrcIdx, DstIdx);
1248 std::swap(SrcRC, DstRC);
1250 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1252 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1257 // Dead code elimination. This really should be handled by MachineDCE, but
1258 // sometimes dead copies slip through, and we can't generate invalid live
1260 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1261 DEBUG(dbgs() << "\tCopy is dead.\n");
1262 DeadDefs.push_back(CopyMI);
1263 eliminateDeadDefs();
1267 // Eliminate undefs.
1268 if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1269 LIS->RemoveMachineInstrFromMaps(CopyMI);
1270 CopyMI->eraseFromParent();
1271 return false; // Not coalescable.
1274 // Coalesced copies are normally removed immediately, but transformations
1275 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1276 // When that happens, just join the values and remove the copy.
1277 if (CP.getSrcReg() == CP.getDstReg()) {
1278 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1279 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1280 const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1281 LiveQueryResult LRQ = LI.Query(CopyIdx);
1282 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1283 VNInfo *ReadVNI = LRQ.valueIn();
1284 assert(ReadVNI && "No value before copy and no <undef> flag.");
1285 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1286 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1288 // Process subregister liveranges.
1289 for (LiveInterval::SubRange &S : LI.subranges()) {
1290 LiveQueryResult SLRQ = S.Query(CopyIdx);
1291 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1292 VNInfo *SReadVNI = SLRQ.valueIn();
1293 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1296 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1298 LIS->RemoveMachineInstrFromMaps(CopyMI);
1299 CopyMI->eraseFromParent();
1303 // Enforce policies.
1305 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1306 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1308 if (!canJoinPhys(CP)) {
1309 // Before giving up coalescing, if definition of source is defined by
1310 // trivial computation, try rematerializing it.
1312 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1315 Again = true; // May be possible to coalesce later.
1319 // When possible, let DstReg be the larger interval.
1320 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1321 LIS->getInterval(CP.getDstReg()).size())
1325 dbgs() << "\tConsidering merging to "
1326 << TRI->getRegClassName(CP.getNewRC()) << " with ";
1327 if (CP.getDstIdx() && CP.getSrcIdx())
1328 dbgs() << PrintReg(CP.getDstReg()) << " in "
1329 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1330 << PrintReg(CP.getSrcReg()) << " in "
1331 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1333 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1334 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1339 ShrinkMainRange = false;
1341 // Okay, attempt to join these two intervals. On failure, this returns false.
1342 // Otherwise, if one of the intervals being joined is a physreg, this method
1343 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1344 // been modified, so we can use this information below to update aliases.
1345 if (!joinIntervals(CP)) {
1346 // Coalescing failed.
1348 // If definition of source is defined by trivial computation, try
1349 // rematerializing it.
1351 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1354 // If we can eliminate the copy without merging the live segments, do so
1356 if (!CP.isPartial() && !CP.isPhys()) {
1357 if (adjustCopiesBackFrom(CP, CopyMI) ||
1358 removeCopyByCommutingDef(CP, CopyMI)) {
1359 LIS->RemoveMachineInstrFromMaps(CopyMI);
1360 CopyMI->eraseFromParent();
1361 DEBUG(dbgs() << "\tTrivial!\n");
1366 // Otherwise, we are unable to join the intervals.
1367 DEBUG(dbgs() << "\tInterference!\n");
1368 Again = true; // May be possible to coalesce later.
1372 // Coalescing to a virtual register that is of a sub-register class of the
1373 // other. Make sure the resulting register is set to the right register class.
1374 if (CP.isCrossClass()) {
1376 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1379 // Removing sub-register copies can ease the register class constraints.
1380 // Make sure we attempt to inflate the register class of DstReg.
1381 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1382 InflateRegs.push_back(CP.getDstReg());
1384 // CopyMI has been erased by joinIntervals at this point. Remove it from
1385 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1386 // to the work list. This keeps ErasedInstrs from growing needlessly.
1387 ErasedInstrs.erase(CopyMI);
1389 // Rewrite all SrcReg operands to DstReg.
1390 // Also update DstReg operands to include DstIdx if it is set.
1392 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1393 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1395 // Shrink subregister ranges if necessary.
1396 if (ShrinkMask != 0) {
1397 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1398 for (LiveInterval::SubRange &S : LI.subranges()) {
1399 if ((S.LaneMask & ShrinkMask) == 0)
1401 DEBUG(dbgs() << "Shrink LaneUses (Lane "
1402 << format("%04X", S.LaneMask) << ")\n");
1403 LIS->shrinkToUses(S, LI.reg);
1406 if (ShrinkMainRange) {
1407 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1408 LIS->shrinkToUses(&LI);
1411 // SrcReg is guaranteed to be the register whose live interval that is
1413 LIS->removeInterval(CP.getSrcReg());
1415 // Update regalloc hint.
1416 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1419 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1420 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1421 dbgs() << "\tResult = ";
1423 dbgs() << PrintReg(CP.getDstReg(), TRI);
1425 dbgs() << LIS->getInterval(CP.getDstReg());
1433 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1434 unsigned DstReg = CP.getDstReg();
1435 assert(CP.isPhys() && "Must be a physreg copy");
1436 assert(MRI->isReserved(DstReg) && "Not a reserved register");
1437 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1438 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1440 assert(RHS.containsOneValue() && "Invalid join with reserved register");
1442 // Optimization for reserved registers like ESP. We can only merge with a
1443 // reserved physreg if RHS has a single value that is a copy of DstReg.
1444 // The live range of the reserved register will look like a set of dead defs
1445 // - we don't properly track the live range of reserved registers.
1447 // Deny any overlapping intervals. This depends on all the reserved
1448 // register live ranges to look like dead defs.
1449 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI)
1450 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1451 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1455 // Skip any value computations, we are not adding new values to the
1456 // reserved register. Also skip merging the live ranges, the reserved
1457 // register live range doesn't need to be accurate as long as all the
1460 // Delete the identity copy.
1461 MachineInstr *CopyMI;
1462 if (CP.isFlipped()) {
1463 CopyMI = MRI->getVRegDef(RHS.reg);
1465 if (!MRI->hasOneNonDBGUse(RHS.reg)) {
1466 DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
1470 MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
1471 CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
1472 const SlotIndex CopyRegIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
1473 const SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
1475 // We checked above that there are no interfering defs of the physical
1476 // register. However, for this case, where we intent to move up the def of
1477 // the physical register, we also need to check for interfering uses.
1478 SlotIndexes *Indexes = LIS->getSlotIndexes();
1479 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
1480 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
1481 MachineInstr *MI = LIS->getInstructionFromIndex(SI);
1482 if (MI->readsRegister(DstReg, TRI)) {
1483 DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
1488 // We're going to remove the copy which defines a physical reserved
1489 // register, so remove its valno, etc.
1490 DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
1491 << CopyRegIdx << "\n");
1493 LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1494 // Create a new dead def at the new def location.
1495 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1496 LiveRange &LR = LIS->getRegUnit(*UI);
1497 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
1501 LIS->RemoveMachineInstrFromMaps(CopyMI);
1502 CopyMI->eraseFromParent();
1504 // We don't track kills for reserved registers.
1505 MRI->clearKillFlags(CP.getSrcReg());
1510 //===----------------------------------------------------------------------===//
1511 // Interference checking and interval joining
1512 //===----------------------------------------------------------------------===//
1514 // In the easiest case, the two live ranges being joined are disjoint, and
1515 // there is no interference to consider. It is quite common, though, to have
1516 // overlapping live ranges, and we need to check if the interference can be
1519 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1520 // This means that two SSA values overlap if and only if the def of one value
1521 // is contained in the live range of the other value. As a special case, the
1522 // overlapping values can be defined at the same index.
1524 // The interference from an overlapping def can be resolved in these cases:
1526 // 1. Coalescable copies. The value is defined by a copy that would become an
1527 // identity copy after joining SrcReg and DstReg. The copy instruction will
1528 // be removed, and the value will be merged with the source value.
1530 // There can be several copies back and forth, causing many values to be
1531 // merged into one. We compute a list of ultimate values in the joined live
1532 // range as well as a mappings from the old value numbers.
1534 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1535 // predecessors have a live out value. It doesn't cause real interference,
1536 // and can be merged into the value it overlaps. Like a coalescable copy, it
1537 // can be erased after joining.
1539 // 3. Copy of external value. The overlapping def may be a copy of a value that
1540 // is already in the other register. This is like a coalescable copy, but
1541 // the live range of the source register must be trimmed after erasing the
1542 // copy instruction:
1545 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1547 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1548 // defining one lane at a time:
1550 // %dst:ssub0<def,read-undef> = FOO
1552 // %dst:ssub1<def> = COPY %src
1554 // The live range of %src overlaps the %dst value defined by FOO, but
1555 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1556 // which was undef anyway.
1558 // The value mapping is more complicated in this case. The final live range
1559 // will have different value numbers for both FOO and BAR, but there is no
1560 // simple mapping from old to new values. It may even be necessary to add
1563 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1564 // is live, but never read. This can happen because we don't compute
1565 // individual live ranges per lane.
1569 // %dst:ssub1<def> = COPY %src
1571 // This kind of interference is only resolved locally. If the clobbered
1572 // lane value escapes the block, the join is aborted.
1575 /// Track information about values in a single virtual register about to be
1576 /// joined. Objects of this class are always created in pairs - one for each
1577 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1580 /// Live range we work on.
1582 /// (Main) register we work on.
1585 /// Reg (and therefore the values in this liverange) will end up as
1586 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
1588 const unsigned SubIdx;
1589 /// The LaneMask that this liverange will occupy the coalesced register. May
1590 /// be smaller than the lanemask produced by SubIdx when merging subranges.
1591 const unsigned LaneMask;
1593 /// This is true when joining sub register ranges, false when joining main
1595 const bool SubRangeJoin;
1596 /// Whether the current LiveInterval tracks subregister liveness.
1597 const bool TrackSubRegLiveness;
1599 /// Values that will be present in the final live range.
1600 SmallVectorImpl<VNInfo*> &NewVNInfo;
1602 const CoalescerPair &CP;
1604 SlotIndexes *Indexes;
1605 const TargetRegisterInfo *TRI;
1607 /// Value number assignments. Maps value numbers in LI to entries in
1608 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
1609 SmallVector<int, 8> Assignments;
1611 /// Conflict resolution for overlapping values.
1612 enum ConflictResolution {
1613 /// No overlap, simply keep this value.
1616 /// Merge this value into OtherVNI and erase the defining instruction.
1617 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
1621 /// Merge this value into OtherVNI but keep the defining instruction.
1622 /// This is for the special case where OtherVNI is defined by the same
1626 /// Keep this value, and have it replace OtherVNI where possible. This
1627 /// complicates value mapping since OtherVNI maps to two different values
1628 /// before and after this def.
1629 /// Used when clobbering undefined or dead lanes.
1632 /// Unresolved conflict. Visit later when all values have been mapped.
1635 /// Unresolvable conflict. Abort the join.
1639 /// Per-value info for LI. The lane bit masks are all relative to the final
1640 /// joined register, so they can be compared directly between SrcReg and
1643 ConflictResolution Resolution;
1645 /// Lanes written by this def, 0 for unanalyzed values.
1646 unsigned WriteLanes;
1648 /// Lanes with defined values in this register. Other lanes are undef and
1649 /// safe to clobber.
1650 unsigned ValidLanes;
1652 /// Value in LI being redefined by this def.
1655 /// Value in the other live range that overlaps this def, if any.
1658 /// Is this value an IMPLICIT_DEF that can be erased?
1660 /// IMPLICIT_DEF values should only exist at the end of a basic block that
1661 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1662 /// safely erased if they are overlapping a live value in the other live
1665 /// Weird control flow graphs and incomplete PHI handling in
1666 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1667 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
1669 bool ErasableImplicitDef;
1671 /// True when the live range of this value will be pruned because of an
1672 /// overlapping CR_Replace value in the other live range.
1675 /// True once Pruned above has been computed.
1676 bool PrunedComputed;
1678 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1679 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1680 Pruned(false), PrunedComputed(false) {}
1682 bool isAnalyzed() const { return WriteLanes != 0; }
1685 /// One entry per value number in LI.
1686 SmallVector<Val, 8> Vals;
1688 /// Compute the bitmask of lanes actually written by DefMI.
1689 /// Set Redef if there are any partial register definitions that depend on the
1690 /// previous value of the register.
1691 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1693 /// Find the ultimate value that VNI was copied from.
1694 std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
1696 bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
1698 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1699 /// Return a conflict resolution when possible, but leave the hard cases as
1701 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1702 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1703 /// The recursion always goes upwards in the dominator tree, making loops
1705 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1707 /// Compute the value assignment for ValNo in RI.
1708 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1710 void computeAssignment(unsigned ValNo, JoinVals &Other);
1712 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
1713 /// the extent of the tainted lanes in the block.
1715 /// Multiple values in Other.LR can be affected since partial redefinitions
1716 /// can preserve previously tainted lanes.
1718 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1719 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1720 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1721 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1723 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1724 /// entry to TaintedVals.
1726 /// Returns false if the tainted lanes extend beyond the basic block.
1727 bool taintExtent(unsigned, unsigned, JoinVals&,
1728 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1730 /// Return true if MI uses any of the given Lanes from Reg.
1731 /// This does not include partial redefinitions of Reg.
1732 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
1734 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
1737 /// %dst = COPY %src
1738 /// %src = COPY %dst <-- This value to be pruned.
1739 /// %dst = COPY %src <-- This value is a copy of a pruned value.
1740 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1743 JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, unsigned LaneMask,
1744 SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
1745 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
1746 bool TrackSubRegLiveness)
1747 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
1748 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
1749 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1750 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
1753 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1754 /// Returns false if any conflicts were impossible to resolve.
1755 bool mapValues(JoinVals &Other);
1757 /// Try to resolve conflicts that require all values to be mapped.
1758 /// Returns false if any conflicts were impossible to resolve.
1759 bool resolveConflicts(JoinVals &Other);
1761 /// Prune the live range of values in Other.LR where they would conflict with
1762 /// CR_Replace values in LR. Collect end points for restoring the live range
1764 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1767 /// Removes subranges starting at copies that get removed. This sometimes
1768 /// happens when undefined subranges are copied around. These ranges contain
1769 /// no usefull information and can be removed.
1770 void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
1772 /// Erase any machine instructions that have been coalesced away.
1773 /// Add erased instructions to ErasedInstrs.
1774 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1775 /// the erased instrs.
1776 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1777 SmallVectorImpl<unsigned> &ShrinkRegs);
1779 /// Remove liverange defs at places where implicit defs will be removed.
1780 void removeImplicitDefs();
1782 /// Get the value assignments suitable for passing to LiveInterval::join.
1783 const int *getAssignments() const { return Assignments.data(); }
1785 } // end anonymous namespace
1787 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1790 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1791 if (!MO->isReg() || MO->getReg() != Reg || !MO->isDef())
1793 L |= TRI->getSubRegIndexLaneMask(
1794 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1801 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
1802 const VNInfo *VNI) const {
1803 unsigned Reg = this->Reg;
1805 while (!VNI->isPHIDef()) {
1806 SlotIndex Def = VNI->def;
1807 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1808 assert(MI && "No defining instruction");
1809 if (!MI->isFullCopy())
1810 return std::make_pair(VNI, Reg);
1811 unsigned SrcReg = MI->getOperand(1).getReg();
1812 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1813 return std::make_pair(VNI, Reg);
1815 const LiveInterval &LI = LIS->getInterval(SrcReg);
1816 const VNInfo *ValueIn;
1817 // No subrange involved.
1818 if (!SubRangeJoin || !LI.hasSubRanges()) {
1819 LiveQueryResult LRQ = LI.Query(Def);
1820 ValueIn = LRQ.valueIn();
1822 // Query subranges. Pick the first matching one.
1824 for (const LiveInterval::SubRange &S : LI.subranges()) {
1825 // Transform lanemask to a mask in the joined live interval.
1826 unsigned SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
1827 if ((SMask & LaneMask) == 0)
1829 LiveQueryResult LRQ = S.Query(Def);
1830 ValueIn = LRQ.valueIn();
1834 if (ValueIn == nullptr)
1839 return std::make_pair(VNI, Reg);
1842 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
1843 const JoinVals &Other) const {
1844 const VNInfo *Orig0;
1846 std::tie(Orig0, Reg0) = followCopyChain(Value0);
1847 if (Orig0 == Value1)
1850 const VNInfo *Orig1;
1852 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
1854 // The values are equal if they are defined at the same place and use the
1855 // same register. Note that we cannot compare VNInfos directly as some of
1856 // them might be from a copy created in mergeSubRangeInto() while the other
1857 // is from the original LiveInterval.
1858 return Orig0->def == Orig1->def && Reg0 == Reg1;
1861 JoinVals::ConflictResolution
1862 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1863 Val &V = Vals[ValNo];
1864 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1865 VNInfo *VNI = LR.getValNumInfo(ValNo);
1866 if (VNI->isUnused()) {
1871 // Get the instruction defining this value, compute the lanes written.
1872 const MachineInstr *DefMI = nullptr;
1873 if (VNI->isPHIDef()) {
1874 // Conservatively assume that all lanes in a PHI are valid.
1875 unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1876 V.ValidLanes = V.WriteLanes = Lanes;
1878 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1879 assert(DefMI != nullptr);
1881 // We don't care about the lanes when joining subregister ranges.
1882 V.WriteLanes = V.ValidLanes = 1;
1883 if (DefMI->isImplicitDef()) {
1885 V.ErasableImplicitDef = true;
1889 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1891 // If this is a read-modify-write instruction, there may be more valid
1892 // lanes than the ones written by this instruction.
1893 // This only covers partial redef operands. DefMI may have normal use
1894 // operands reading the register. They don't contribute valid lanes.
1896 // This adds ssub1 to the set of valid lanes in %src:
1898 // %src:ssub1<def> = FOO
1900 // This leaves only ssub1 valid, making any other lanes undef:
1902 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1904 // The <read-undef> flag on the def operand means that old lane values are
1907 V.RedefVNI = LR.Query(VNI->def).valueIn();
1908 assert((TrackSubRegLiveness || V.RedefVNI) &&
1909 "Instruction is reading nonexistent value");
1910 if (V.RedefVNI != nullptr) {
1911 computeAssignment(V.RedefVNI->id, Other);
1912 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1916 // An IMPLICIT_DEF writes undef values.
1917 if (DefMI->isImplicitDef()) {
1918 // We normally expect IMPLICIT_DEF values to be live only until the end
1919 // of their block. If the value is really live longer and gets pruned in
1920 // another block, this flag is cleared again.
1921 V.ErasableImplicitDef = true;
1922 V.ValidLanes &= ~V.WriteLanes;
1927 // Find the value in Other that overlaps VNI->def, if any.
1928 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1930 // It is possible that both values are defined by the same instruction, or
1931 // the values are PHIs defined in the same block. When that happens, the two
1932 // values should be merged into one, but not into any preceding value.
1933 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1934 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1935 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1937 // One value stays, the other is merged. Keep the earlier one, or the first
1939 if (OtherVNI->def < VNI->def)
1940 Other.computeAssignment(OtherVNI->id, *this);
1941 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1942 // This is an early-clobber def overlapping a live-in value in the other
1943 // register. Not mergeable.
1944 V.OtherVNI = OtherLRQ.valueIn();
1945 return CR_Impossible;
1947 V.OtherVNI = OtherVNI;
1948 Val &OtherV = Other.Vals[OtherVNI->id];
1949 // Keep this value, check for conflicts when analyzing OtherVNI.
1950 if (!OtherV.isAnalyzed())
1952 // Both sides have been analyzed now.
1953 // Allow overlapping PHI values. Any real interference would show up in a
1954 // predecessor, the PHI itself can't introduce any conflicts.
1955 if (VNI->isPHIDef())
1957 if (V.ValidLanes & OtherV.ValidLanes)
1958 // Overlapping lanes can't be resolved.
1959 return CR_Impossible;
1964 // No simultaneous def. Is Other live at the def?
1965 V.OtherVNI = OtherLRQ.valueIn();
1967 // No overlap, no conflict.
1970 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1972 // We have overlapping values, or possibly a kill of Other.
1973 // Recursively compute assignments up the dominator tree.
1974 Other.computeAssignment(V.OtherVNI->id, *this);
1975 Val &OtherV = Other.Vals[V.OtherVNI->id];
1977 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1978 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1979 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1982 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1983 // to erase the IMPLICIT_DEF instruction.
1984 if (OtherV.ErasableImplicitDef && DefMI &&
1985 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1986 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1987 << " extends into BB#" << DefMI->getParent()->getNumber()
1988 << ", keeping it.\n");
1989 OtherV.ErasableImplicitDef = false;
1992 // Allow overlapping PHI values. Any real interference would show up in a
1993 // predecessor, the PHI itself can't introduce any conflicts.
1994 if (VNI->isPHIDef())
1997 // Check for simple erasable conflicts.
1998 if (DefMI->isImplicitDef()) {
1999 // We need the def for the subregister if there is nothing else live at the
2000 // subrange at this point.
2001 if (TrackSubRegLiveness
2002 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0)
2007 // Include the non-conflict where DefMI is a coalescable copy that kills
2008 // OtherVNI. We still want the copy erased and value numbers merged.
2009 if (CP.isCoalescable(DefMI)) {
2010 // Some of the lanes copied from OtherVNI may be undef, making them undef
2012 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2016 // This may not be a real conflict if DefMI simply kills Other and defines
2018 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2021 // Handle the case where VNI and OtherVNI can be proven to be identical:
2023 // %other = COPY %ext
2024 // %this = COPY %ext <-- Erase this copy
2026 if (DefMI->isFullCopy() && !CP.isPartial()
2027 && valuesIdentical(VNI, V.OtherVNI, Other))
2030 // If the lanes written by this instruction were all undef in OtherVNI, it is
2031 // still safe to join the live ranges. This can't be done with a simple value
2032 // mapping, though - OtherVNI will map to multiple values:
2034 // 1 %dst:ssub0 = FOO <-- OtherVNI
2035 // 2 %src = BAR <-- VNI
2036 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
2038 // 5 QUUX %src<kill>
2040 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2041 // handles this complex value mapping.
2042 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
2045 // If the other live range is killed by DefMI and the live ranges are still
2046 // overlapping, it must be because we're looking at an early clobber def:
2048 // %dst<def,early-clobber> = ASM %src<kill>
2050 // In this case, it is illegal to merge the two live ranges since the early
2051 // clobber def would clobber %src before it was read.
2052 if (OtherLRQ.isKill()) {
2053 // This case where the def doesn't overlap the kill is handled above.
2054 assert(VNI->def.isEarlyClobber() &&
2055 "Only early clobber defs can overlap a kill");
2056 return CR_Impossible;
2059 // VNI is clobbering live lanes in OtherVNI, but there is still the
2060 // possibility that no instructions actually read the clobbered lanes.
2061 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2062 // Otherwise Other.RI wouldn't be live here.
2063 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
2064 return CR_Impossible;
2066 // We need to verify that no instructions are reading the clobbered lanes. To
2067 // save compile time, we'll only check that locally. Don't allow the tainted
2068 // value to escape the basic block.
2069 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2070 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2071 return CR_Impossible;
2073 // There are still some things that could go wrong besides clobbered lanes
2074 // being read, for example OtherVNI may be only partially redefined in MBB,
2075 // and some clobbered lanes could escape the block. Save this analysis for
2076 // resolveConflicts() when all values have been mapped. We need to know
2077 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2078 // that now - the recursive analyzeValue() calls must go upwards in the
2080 return CR_Unresolved;
2083 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2084 Val &V = Vals[ValNo];
2085 if (V.isAnalyzed()) {
2086 // Recursion should always move up the dominator tree, so ValNo is not
2087 // supposed to reappear before it has been assigned.
2088 assert(Assignments[ValNo] != -1 && "Bad recursion?");
2091 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2094 // Merge this ValNo into OtherVNI.
2095 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2096 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2097 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2098 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2099 << LR.getValNumInfo(ValNo)->def << " into "
2100 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2101 << V.OtherVNI->def << " --> @"
2102 << NewVNInfo[Assignments[ValNo]]->def << '\n');
2105 case CR_Unresolved: {
2106 // The other value is going to be pruned if this join is successful.
2107 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2108 Val &OtherV = Other.Vals[V.OtherVNI->id];
2109 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2111 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
2112 OtherV.ErasableImplicitDef = false;
2113 OtherV.Pruned = true;
2117 // This value number needs to go in the final joined live range.
2118 Assignments[ValNo] = NewVNInfo.size();
2119 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2124 bool JoinVals::mapValues(JoinVals &Other) {
2125 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2126 computeAssignment(i, Other);
2127 if (Vals[i].Resolution == CR_Impossible) {
2128 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2129 << '@' << LR.getValNumInfo(i)->def << '\n');
2137 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
2138 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
2139 VNInfo *VNI = LR.getValNumInfo(ValNo);
2140 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2141 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2143 // Scan Other.LR from VNI.def to MBBEnd.
2144 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2145 assert(OtherI != Other.LR.end() && "No conflict?");
2147 // OtherI is pointing to a tainted value. Abort the join if the tainted
2148 // lanes escape the block.
2149 SlotIndex End = OtherI->end;
2150 if (End >= MBBEnd) {
2151 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2152 << OtherI->valno->id << '@' << OtherI->start << '\n');
2155 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2156 << OtherI->valno->id << '@' << OtherI->start
2157 << " to " << End << '\n');
2158 // A dead def is not a problem.
2161 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2163 // Check for another def in the MBB.
2164 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2167 // Lanes written by the new def are no longer tainted.
2168 const Val &OV = Other.Vals[OtherI->valno->id];
2169 TaintedLanes &= ~OV.WriteLanes;
2172 } while (TaintedLanes);
2176 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2177 unsigned Lanes) const {
2178 if (MI->isDebugValue())
2180 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
2181 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
2183 if (!MO->readsReg())
2185 if (Lanes & TRI->getSubRegIndexLaneMask(
2186 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
2192 bool JoinVals::resolveConflicts(JoinVals &Other) {
2193 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2195 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2196 if (V.Resolution != CR_Unresolved)
2198 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2199 << '@' << LR.getValNumInfo(i)->def << '\n');
2204 assert(V.OtherVNI && "Inconsistent conflict resolution.");
2205 VNInfo *VNI = LR.getValNumInfo(i);
2206 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2208 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2209 // join, those lanes will be tainted with a wrong value. Get the extent of
2210 // the tainted lanes.
2211 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2212 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
2213 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2214 // Tainted lanes would extend beyond the basic block.
2217 assert(!TaintExtent.empty() && "There should be at least one conflict.");
2219 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2220 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2221 MachineBasicBlock::iterator MI = MBB->begin();
2222 if (!VNI->isPHIDef()) {
2223 MI = Indexes->getInstructionFromIndex(VNI->def);
2224 // No need to check the instruction defining VNI for reads.
2227 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2228 "Interference ends on VNI->def. Should have been handled earlier");
2229 MachineInstr *LastMI =
2230 Indexes->getInstructionFromIndex(TaintExtent.front().first);
2231 assert(LastMI && "Range must end at a proper instruction");
2232 unsigned TaintNum = 0;
2234 assert(MI != MBB->end() && "Bad LastMI");
2235 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2236 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2239 // LastMI is the last instruction to use the current value.
2240 if (&*MI == LastMI) {
2241 if (++TaintNum == TaintExtent.size())
2243 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2244 assert(LastMI && "Range must end at a proper instruction");
2245 TaintedLanes = TaintExtent[TaintNum].second;
2250 // The tainted lanes are unused.
2251 V.Resolution = CR_Replace;
2257 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2258 Val &V = Vals[ValNo];
2259 if (V.Pruned || V.PrunedComputed)
2262 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2265 // Follow copies up the dominator tree and check if any intermediate value
2267 V.PrunedComputed = true;
2268 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2272 void JoinVals::pruneValues(JoinVals &Other,
2273 SmallVectorImpl<SlotIndex> &EndPoints,
2274 bool changeInstrs) {
2275 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2276 SlotIndex Def = LR.getValNumInfo(i)->def;
2277 switch (Vals[i].Resolution) {
2281 // This value takes precedence over the value in Other.LR.
2282 LIS->pruneValue(Other.LR, Def, &EndPoints);
2283 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2284 // instructions are only inserted to provide a live-out value for PHI
2285 // predecessors, so the instruction should simply go away once its value
2286 // has been replaced.
2287 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2288 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2289 OtherV.Resolution == CR_Keep;
2290 if (!Def.isBlock()) {
2292 // Remove <def,read-undef> flags. This def is now a partial redef.
2293 // Also remove <def,dead> flags since the joined live range will
2294 // continue past this instruction.
2295 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
2296 MO.isValid(); ++MO) {
2297 if (MO->isReg() && MO->isDef() && MO->getReg() == Reg) {
2298 MO->setIsUndef(EraseImpDef);
2299 MO->setIsDead(false);
2303 // This value will reach instructions below, but we need to make sure
2304 // the live range also reaches the instruction at Def.
2306 EndPoints.push_back(Def);
2308 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2309 << ": " << Other.LR << '\n');
2314 if (isPrunedValue(i, Other)) {
2315 // This value is ultimately a copy of a pruned value in LR or Other.LR.
2316 // We can no longer trust the value mapping computed by
2317 // computeAssignment(), the value that was originally copied could have
2319 LIS->pruneValue(LR, Def, &EndPoints);
2320 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2321 << Def << ": " << LR << '\n');
2326 llvm_unreachable("Unresolved conflicts");
2331 void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
2333 // Look for values being erased.
2334 bool DidPrune = false;
2335 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2336 if (Vals[i].Resolution != CR_Erase)
2339 // Check subranges at the point where the copy will be removed.
2340 SlotIndex Def = LR.getValNumInfo(i)->def;
2341 for (LiveInterval::SubRange &S : LI.subranges()) {
2342 LiveQueryResult Q = S.Query(Def);
2344 // If a subrange starts at the copy then an undefined value has been
2345 // copied and we must remove that subrange value as well.
2346 VNInfo *ValueOut = Q.valueOutOrDead();
2347 if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2348 DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
2349 << " at " << Def << "\n");
2350 LIS->pruneValue(S, Def, nullptr);
2352 // Mark value number as unused.
2353 ValueOut->markUnused();
2356 // If a subrange ends at the copy, then a value was copied but only
2357 // partially used later. Shrink the subregister range apropriately.
2358 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2359 DEBUG(dbgs() << "\t\tDead uses at sublane "
2360 << format("%04X", S.LaneMask) << " at " << Def << "\n");
2361 ShrinkMask |= S.LaneMask;
2366 LI.removeEmptySubRanges();
2369 void JoinVals::removeImplicitDefs() {
2370 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2372 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
2375 VNInfo *VNI = LR.getValNumInfo(i);
2377 LR.removeValNo(VNI);
2381 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2382 SmallVectorImpl<unsigned> &ShrinkRegs) {
2383 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2384 // Get the def location before markUnused() below invalidates it.
2385 SlotIndex Def = LR.getValNumInfo(i)->def;
2386 switch (Vals[i].Resolution) {
2388 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2389 // longer. The IMPLICIT_DEF instructions are only inserted by
2390 // PHIElimination to guarantee that all PHI predecessors have a value.
2391 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2393 // Remove value number i from LR.
2394 VNInfo *VNI = LR.getValNumInfo(i);
2395 LR.removeValNo(VNI);
2396 // Note that this VNInfo is reused and still referenced in NewVNInfo,
2397 // make it appear like an unused value number.
2399 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2404 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2405 assert(MI && "No instruction to erase");
2407 unsigned Reg = MI->getOperand(1).getReg();
2408 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2409 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2410 ShrinkRegs.push_back(Reg);
2412 ErasedInstrs.insert(MI);
2413 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2414 LIS->RemoveMachineInstrFromMaps(MI);
2415 MI->eraseFromParent();
2424 bool RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2426 const CoalescerPair &CP) {
2427 SmallVector<VNInfo*, 16> NewVNInfo;
2428 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
2429 NewVNInfo, CP, LIS, TRI, true, true);
2430 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2431 NewVNInfo, CP, LIS, TRI, true, true);
2433 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2434 // We should be able to resolve all conflicts here as we could successfully do
2435 // it on the mainrange already. There is however a problem when multiple
2436 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
2438 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
2439 DEBUG(dbgs() << "*** Couldn't join subrange!\n");
2442 if (!LHSVals.resolveConflicts(RHSVals) ||
2443 !RHSVals.resolveConflicts(LHSVals)) {
2444 DEBUG(dbgs() << "*** Couldn't join subrange!\n");
2448 // The merging algorithm in LiveInterval::join() can't handle conflicting
2449 // value mappings, so we need to remove any live ranges that overlap a
2450 // CR_Replace resolution. Collect a set of end points that can be used to
2451 // restore the live range after joining.
2452 SmallVector<SlotIndex, 8> EndPoints;
2453 LHSVals.pruneValues(RHSVals, EndPoints, false);
2454 RHSVals.pruneValues(LHSVals, EndPoints, false);
2456 LHSVals.removeImplicitDefs();
2457 RHSVals.removeImplicitDefs();
2462 // Join RRange into LHS.
2463 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2466 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2467 if (EndPoints.empty())
2470 // Recompute the parts of the live range we had to remove because of
2471 // CR_Replace conflicts.
2472 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2473 << " points: " << LRange << '\n');
2474 LIS->extendToIndices(LRange, EndPoints);
2478 bool RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2479 const LiveRange &ToMerge,
2480 unsigned LaneMask, CoalescerPair &CP) {
2481 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2482 for (LiveInterval::SubRange &R : LI.subranges()) {
2483 unsigned RMask = R.LaneMask;
2484 // LaneMask of subregisters common to subrange R and ToMerge.
2485 unsigned Common = RMask & LaneMask;
2486 // There is nothing to do without common subregs.
2490 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
2491 // LaneMask of subregisters contained in the R range but not in ToMerge,
2492 // they have to split into their own subrange.
2493 unsigned LRest = RMask & ~LaneMask;
2494 LiveInterval::SubRange *CommonRange;
2497 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
2498 // Duplicate SubRange for newly merged common stuff.
2499 CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2501 // Reuse the existing range.
2502 R.LaneMask = Common;
2505 LiveRange RangeCopy(ToMerge, Allocator);
2506 if (!joinSubRegRanges(*CommonRange, RangeCopy, Common, CP))
2511 if (LaneMask != 0) {
2512 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", LaneMask));
2513 LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2518 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2519 SmallVector<VNInfo*, 16> NewVNInfo;
2520 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2521 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2522 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
2523 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS,
2524 TRI, false, TrackSubRegLiveness);
2525 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS,
2526 TRI, false, TrackSubRegLiveness);
2528 DEBUG(dbgs() << "\t\tRHS = " << RHS
2529 << "\n\t\tLHS = " << LHS
2532 // First compute NewVNInfo and the simple value mappings.
2533 // Detect impossible conflicts early.
2534 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2537 // Some conflicts can only be resolved after all values have been mapped.
2538 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2541 // All clear, the live ranges can be merged.
2542 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2543 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2545 // Transform lanemasks from the LHS to masks in the coalesced register and
2546 // create initial subranges if necessary.
2547 unsigned DstIdx = CP.getDstIdx();
2548 if (!LHS.hasSubRanges()) {
2549 unsigned Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2550 : TRI->getSubRegIndexLaneMask(DstIdx);
2551 // LHS must support subregs or we wouldn't be in this codepath.
2553 LHS.createSubRangeFrom(Allocator, Mask, LHS);
2554 } else if (DstIdx != 0) {
2555 // Transform LHS lanemasks to new register class if necessary.
2556 for (LiveInterval::SubRange &R : LHS.subranges()) {
2557 unsigned Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2561 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2562 << ' ' << LHS << '\n');
2564 // Determine lanemasks of RHS in the coalesced register and merge subranges.
2565 unsigned SrcIdx = CP.getSrcIdx();
2567 if (!RHS.hasSubRanges()) {
2568 unsigned Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
2569 : TRI->getSubRegIndexLaneMask(SrcIdx);
2570 if (!mergeSubRangeInto(LHS, RHS, Mask, CP))
2573 // Pair up subranges and merge.
2574 for (LiveInterval::SubRange &R : RHS.subranges()) {
2575 unsigned Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
2576 if (!mergeSubRangeInto(LHS, R, Mask, CP)) {
2583 // This shouldn't have happened :-(
2584 // However we are aware of at least one existing problem where we
2585 // can't merge subranges when multiple ranges end up in the
2586 // "overflow bit" 32. As a workaround we drop all subregister ranges
2587 // which means we loose some precision but are back to a well defined
2589 assert((CP.getNewRC()->getLaneMask() & 0x80000000u)
2590 && "SubRange merge should only fail when merging into bit 32.");
2591 DEBUG(dbgs() << "\tSubrange join aborted!\n");
2592 LHS.clearSubRanges();
2593 RHS.clearSubRanges();
2595 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2597 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2598 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2602 // The merging algorithm in LiveInterval::join() can't handle conflicting
2603 // value mappings, so we need to remove any live ranges that overlap a
2604 // CR_Replace resolution. Collect a set of end points that can be used to
2605 // restore the live range after joining.
2606 SmallVector<SlotIndex, 8> EndPoints;
2607 LHSVals.pruneValues(RHSVals, EndPoints, true);
2608 RHSVals.pruneValues(LHSVals, EndPoints, true);
2610 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2611 // registers to require trimming.
2612 SmallVector<unsigned, 8> ShrinkRegs;
2613 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2614 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2615 while (!ShrinkRegs.empty())
2616 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2618 // Join RHS into LHS.
2619 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2621 // Kill flags are going to be wrong if the live ranges were overlapping.
2622 // Eventually, we should simply clear all kill flags when computing live
2623 // ranges. They are reinserted after register allocation.
2624 MRI->clearKillFlags(LHS.reg);
2625 MRI->clearKillFlags(RHS.reg);
2627 if (!EndPoints.empty()) {
2628 // Recompute the parts of the live range we had to remove because of
2629 // CR_Replace conflicts.
2630 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2631 << " points: " << LHS << '\n');
2632 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2638 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2639 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2643 /// Information concerning MBB coalescing priority.
2644 struct MBBPriorityInfo {
2645 MachineBasicBlock *MBB;
2649 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2650 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2654 /// C-style comparator that sorts first based on the loop depth of the basic
2655 /// block (the unsigned), and then on the MBB number.
2657 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
2658 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2659 const MBBPriorityInfo *RHS) {
2660 // Deeper loops first
2661 if (LHS->Depth != RHS->Depth)
2662 return LHS->Depth > RHS->Depth ? -1 : 1;
2664 // Try to unsplit critical edges next.
2665 if (LHS->IsSplit != RHS->IsSplit)
2666 return LHS->IsSplit ? -1 : 1;
2668 // Prefer blocks that are more connected in the CFG. This takes care of
2669 // the most difficult copies first while intervals are short.
2670 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2671 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2673 return cl > cr ? -1 : 1;
2675 // As a last resort, sort by block number.
2676 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2679 /// \returns true if the given copy uses or defines a local live range.
2680 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2681 if (!Copy->isCopy())
2684 if (Copy->getOperand(1).isUndef())
2687 unsigned SrcReg = Copy->getOperand(1).getReg();
2688 unsigned DstReg = Copy->getOperand(0).getReg();
2689 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2690 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2693 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2694 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2697 bool RegisterCoalescer::
2698 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2699 bool Progress = false;
2700 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2703 // Skip instruction pointers that have already been erased, for example by
2704 // dead code elimination.
2705 if (ErasedInstrs.erase(CurrList[i])) {
2706 CurrList[i] = nullptr;
2710 bool Success = joinCopy(CurrList[i], Again);
2711 Progress |= Success;
2712 if (Success || !Again)
2713 CurrList[i] = nullptr;
2718 /// Check if DstReg is a terminal node.
2719 /// I.e., it does not have any affinity other than \p Copy.
2720 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
2721 const MachineRegisterInfo *MRI) {
2722 assert(Copy.isCopyLike());
2723 // Check if the destination of this copy as any other affinity.
2724 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
2725 if (&MI != &Copy && MI.isCopyLike())
2730 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
2731 assert(Copy.isCopyLike());
2732 if (!UseTerminalRule)
2734 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
2735 isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
2736 // Check if the destination of this copy has any other affinity.
2737 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
2738 // If SrcReg is a physical register, the copy won't be coalesced.
2739 // Ignoring it may have other side effect (like missing
2740 // rematerialization). So keep it.
2741 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
2742 !isTerminalReg(DstReg, Copy, MRI))
2745 // DstReg is a terminal node. Check if it inteferes with any other
2746 // copy involving SrcReg.
2747 const MachineBasicBlock *OrigBB = Copy.getParent();
2748 const LiveInterval &DstLI = LIS->getInterval(DstReg);
2749 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
2750 // Technically we should check if the weight of the new copy is
2751 // interesting compared to the other one and update the weight
2752 // of the copies accordingly. However, this would only work if
2753 // we would gather all the copies first then coalesce, whereas
2754 // right now we interleave both actions.
2755 // For now, just consider the copies that are in the same block.
2756 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
2758 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
2759 isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
2761 if (OtherReg == SrcReg)
2762 OtherReg = OtherSrcReg;
2763 // Check if OtherReg is a non-terminal.
2764 if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
2765 isTerminalReg(OtherReg, MI, MRI))
2767 // Check that OtherReg interfere with DstReg.
2768 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
2769 DEBUG(dbgs() << "Apply terminal rule for: " << PrintReg(DstReg) << '\n');
2777 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2778 DEBUG(dbgs() << MBB->getName() << ":\n");
2780 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2781 // yet, it might invalidate the iterator.
2782 const unsigned PrevSize = WorkList.size();
2783 if (JoinGlobalCopies) {
2784 SmallVector<MachineInstr*, 2> LocalTerminals;
2785 SmallVector<MachineInstr*, 2> GlobalTerminals;
2786 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2787 // are not inherently easier to resolve, but slightly preferable until we
2788 // have local live range splitting. In particular this is required by
2789 // cmp+jmp macro fusion.
2790 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2792 if (!MII->isCopyLike())
2794 bool ApplyTerminalRule = applyTerminalRule(*MII);
2795 if (isLocalCopy(&(*MII), LIS)) {
2796 if (ApplyTerminalRule)
2797 LocalTerminals.push_back(&(*MII));
2799 LocalWorkList.push_back(&(*MII));
2801 if (ApplyTerminalRule)
2802 GlobalTerminals.push_back(&(*MII));
2804 WorkList.push_back(&(*MII));
2807 // Append the copies evicted by the terminal rule at the end of the list.
2808 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
2809 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
2812 SmallVector<MachineInstr*, 2> Terminals;
2813 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2815 if (MII->isCopyLike()) {
2816 if (applyTerminalRule(*MII))
2817 Terminals.push_back(&(*MII));
2819 WorkList.push_back(MII);
2821 // Append the copies evicted by the terminal rule at the end of the list.
2822 WorkList.append(Terminals.begin(), Terminals.end());
2824 // Try coalescing the collected copies immediately, and remove the nulls.
2825 // This prevents the WorkList from getting too large since most copies are
2826 // joinable on the first attempt.
2827 MutableArrayRef<MachineInstr*>
2828 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2829 if (copyCoalesceWorkList(CurrList))
2830 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2831 (MachineInstr*)nullptr), WorkList.end());
2834 void RegisterCoalescer::coalesceLocals() {
2835 copyCoalesceWorkList(LocalWorkList);
2836 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2837 if (LocalWorkList[j])
2838 WorkList.push_back(LocalWorkList[j]);
2840 LocalWorkList.clear();
2843 void RegisterCoalescer::joinAllIntervals() {
2844 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2845 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2847 std::vector<MBBPriorityInfo> MBBs;
2848 MBBs.reserve(MF->size());
2849 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2850 MachineBasicBlock *MBB = I;
2851 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2852 JoinSplitEdges && isSplitEdge(MBB)));
2854 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2856 // Coalesce intervals in MBB priority order.
2857 unsigned CurrDepth = UINT_MAX;
2858 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2859 // Try coalescing the collected local copies for deeper loops.
2860 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2862 CurrDepth = MBBs[i].Depth;
2864 copyCoalesceInMBB(MBBs[i].MBB);
2868 // Joining intervals can allow other intervals to be joined. Iteratively join
2869 // until we make no progress.
2870 while (copyCoalesceWorkList(WorkList))
2874 void RegisterCoalescer::releaseMemory() {
2875 ErasedInstrs.clear();
2878 InflateRegs.clear();
2881 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2883 MRI = &fn.getRegInfo();
2884 TM = &fn.getTarget();
2885 const TargetSubtargetInfo &STI = fn.getSubtarget();
2886 TRI = STI.getRegisterInfo();
2887 TII = STI.getInstrInfo();
2888 LIS = &getAnalysis<LiveIntervals>();
2889 AA = &getAnalysis<AliasAnalysis>();
2890 Loops = &getAnalysis<MachineLoopInfo>();
2891 if (EnableGlobalCopies == cl::BOU_UNSET)
2892 JoinGlobalCopies = STI.enableJoinGlobalCopies();
2894 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2896 // The MachineScheduler does not currently require JoinSplitEdges. This will
2897 // either be enabled unconditionally or replaced by a more general live range
2898 // splitting optimization.
2899 JoinSplitEdges = EnableJoinSplits;
2901 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2902 << "********** Function: " << MF->getName() << '\n');
2904 if (VerifyCoalescing)
2905 MF->verify(this, "Before register coalescing");
2907 RegClassInfo.runOnMachineFunction(fn);
2909 // Join (coalesce) intervals if requested.
2913 // After deleting a lot of copies, register classes may be less constrained.
2914 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2916 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2917 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2919 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2920 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2921 unsigned Reg = InflateRegs[i];
2922 if (MRI->reg_nodbg_empty(Reg))
2924 if (MRI->recomputeRegClass(Reg)) {
2925 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2926 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2927 LiveInterval &LI = LIS->getInterval(Reg);
2928 unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2930 // If the inflated register class does not support subregisters anymore
2931 // remove the subranges.
2932 LI.clearSubRanges();
2935 // If subranges are still supported, then the same subregs should still
2937 for (LiveInterval::SubRange &S : LI.subranges()) {
2938 assert ((S.LaneMask & ~MaxMask) == 0);
2947 if (VerifyCoalescing)
2948 MF->verify(this, "After register coalescing");
2952 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {