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 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "VirtRegMap.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/LiveRangeEdit.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include "llvm/Target/TargetSubtargetInfo.h"
53 STATISTIC(numJoins , "Number of interval joins performed");
54 STATISTIC(numCrossRCs , "Number of cross class joins performed");
55 STATISTIC(numCommutes , "Number of instruction commuting performed");
56 STATISTIC(numExtends , "Number of copies extended");
57 STATISTIC(NumReMats , "Number of instructions re-materialized");
58 STATISTIC(NumInflated , "Number of register classes inflated");
59 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
60 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
63 EnableJoining("join-liveintervals",
64 cl::desc("Coalesce copies (default=true)"),
67 // Temporary flag to test critical edge unsplitting.
68 static cl::opt<cl::boolOrDefault>
69 EnableJoinSplits("join-splitedges",
70 cl::desc("Coalesce copies on split edges (default=subtarget)"),
71 cl::init(cl::BOU_UNSET), cl::Hidden);
73 // Temporary flag to test global copy optimization.
74 static cl::opt<cl::boolOrDefault>
75 EnableGlobalCopies("join-globalcopies",
76 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
77 cl::init(cl::BOU_UNSET), cl::Hidden);
80 VerifyCoalescing("verify-coalescing",
81 cl::desc("Verify machine instrs before and after register coalescing"),
85 class RegisterCoalescer : public MachineFunctionPass,
86 private LiveRangeEdit::Delegate {
88 MachineRegisterInfo* MRI;
89 const TargetMachine* TM;
90 const TargetRegisterInfo* TRI;
91 const TargetInstrInfo* TII;
93 LiveDebugVariables *LDV;
94 const MachineLoopInfo* Loops;
96 RegisterClassInfo RegClassInfo;
98 /// \brief True if the coalescer should aggressively coalesce global copies
99 /// in favor of keeping local copies.
100 bool JoinGlobalCopies;
102 /// \brief True if the coalescer should aggressively coalesce fall-thru
103 /// blocks exclusively containing copies.
106 /// WorkList - Copy instructions yet to be coalesced.
107 SmallVector<MachineInstr*, 8> WorkList;
108 SmallVector<MachineInstr*, 8> LocalWorkList;
110 /// ErasedInstrs - Set of instruction pointers that have been erased, and
111 /// that may be present in WorkList.
112 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
114 /// Dead instructions that are about to be deleted.
115 SmallVector<MachineInstr*, 8> DeadDefs;
117 /// Virtual registers to be considered for register class inflation.
118 SmallVector<unsigned, 8> InflateRegs;
120 /// Recursively eliminate dead defs in DeadDefs.
121 void eliminateDeadDefs();
123 /// LiveRangeEdit callback.
124 void LRE_WillEraseInstruction(MachineInstr *MI);
126 /// coalesceLocals - coalesce the LocalWorkList.
127 void coalesceLocals();
129 /// joinAllIntervals - join compatible live intervals
130 void joinAllIntervals();
132 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
133 /// copies that cannot yet be coalesced into WorkList.
134 void copyCoalesceInMBB(MachineBasicBlock *MBB);
136 /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
137 /// true if any progress was made.
138 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
140 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
141 /// which are the src/dst of the copy instruction CopyMI. This returns
142 /// true if the copy was successfully coalesced away. If it is not
143 /// currently possible to coalesce this interval, but it may be possible if
144 /// other things get coalesced, then it returns true by reference in
146 bool joinCopy(MachineInstr *TheCopy, bool &Again);
148 /// joinIntervals - Attempt to join these two intervals. On failure, this
149 /// returns false. The output "SrcInt" will not have been modified, so we
150 /// can use this information below to update aliases.
151 bool joinIntervals(CoalescerPair &CP);
153 /// Attempt joining two virtual registers. Return true on success.
154 bool joinVirtRegs(CoalescerPair &CP);
156 /// Attempt joining with a reserved physreg.
157 bool joinReservedPhysReg(CoalescerPair &CP);
159 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
160 /// the source value number is defined by a copy from the destination reg
161 /// see if we can merge these two destination reg valno# into a single
162 /// value number, eliminating a copy.
163 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
165 /// hasOtherReachingDefs - Return true if there are definitions of IntB
166 /// other than BValNo val# that can reach uses of AValno val# of IntA.
167 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
168 VNInfo *AValNo, VNInfo *BValNo);
170 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
171 /// If the source value number is defined by a commutable instruction and
172 /// its other operand is coalesced to the copy dest register, see if we
173 /// can transform the copy into a noop by commuting the definition.
174 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
176 /// reMaterializeTrivialDef - If the source of a copy is defined by a
177 /// trivial computation, replace the copy by rematerialize the definition.
178 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
179 MachineInstr *CopyMI);
181 /// canJoinPhys - Return true if a physreg copy should be joined.
182 bool canJoinPhys(CoalescerPair &CP);
184 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
185 /// update the subregister number if it is not zero. If DstReg is a
186 /// physical register and the existing subregister number of the def / use
187 /// being updated is not zero, make sure to set it to the correct physical
189 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
191 /// eliminateUndefCopy - Handle copies of undef values.
192 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
195 static char ID; // Class identification, replacement for typeinfo
196 RegisterCoalescer() : MachineFunctionPass(ID) {
197 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
200 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
202 virtual void releaseMemory();
204 /// runOnMachineFunction - pass entry point
205 virtual bool runOnMachineFunction(MachineFunction&);
207 /// print - Implement the dump method.
208 virtual void print(raw_ostream &O, const Module* = 0) const;
210 } /// end anonymous namespace
212 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
214 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
215 "Simple Register Coalescing", false, false)
216 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
217 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
218 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
219 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
220 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
221 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
222 "Simple Register Coalescing", false, false)
224 char RegisterCoalescer::ID = 0;
226 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
227 unsigned &Src, unsigned &Dst,
228 unsigned &SrcSub, unsigned &DstSub) {
230 Dst = MI->getOperand(0).getReg();
231 DstSub = MI->getOperand(0).getSubReg();
232 Src = MI->getOperand(1).getReg();
233 SrcSub = MI->getOperand(1).getSubReg();
234 } else if (MI->isSubregToReg()) {
235 Dst = MI->getOperand(0).getReg();
236 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
237 MI->getOperand(3).getImm());
238 Src = MI->getOperand(2).getReg();
239 SrcSub = MI->getOperand(2).getSubReg();
245 // Return true if this block should be vacated by the coalescer to eliminate
246 // branches. The important cases to handle in the coalescer are critical edges
247 // split during phi elimination which contain only copies. Simple blocks that
248 // contain non-branches should also be vacated, but this can be handled by an
249 // earlier pass similar to early if-conversion.
250 static bool isSplitEdge(const MachineBasicBlock *MBB) {
251 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
254 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
256 if (!MII->isCopyLike() && !MII->isUnconditionalBranch())
262 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
266 Flipped = CrossClass = false;
268 unsigned Src, Dst, SrcSub, DstSub;
269 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
271 Partial = SrcSub || DstSub;
273 // If one register is a physreg, it must be Dst.
274 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
275 if (TargetRegisterInfo::isPhysicalRegister(Dst))
278 std::swap(SrcSub, DstSub);
282 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
284 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
285 // Eliminate DstSub on a physreg.
287 Dst = TRI.getSubReg(Dst, DstSub);
288 if (!Dst) return false;
292 // Eliminate SrcSub by picking a corresponding Dst superregister.
294 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
295 if (!Dst) return false;
297 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
301 // Both registers are virtual.
302 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
303 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
305 // Both registers have subreg indices.
306 if (SrcSub && DstSub) {
307 // Copies between different sub-registers are never coalescable.
308 if (Src == Dst && SrcSub != DstSub)
311 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
316 // SrcReg will be merged with a sub-register of DstReg.
318 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
320 // DstReg will be merged with a sub-register of SrcReg.
322 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
324 // This is a straight copy without sub-registers.
325 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
328 // The combined constraint may be impossible to satisfy.
332 // Prefer SrcReg to be a sub-register of DstReg.
333 // FIXME: Coalescer should support subregs symmetrically.
334 if (DstIdx && !SrcIdx) {
336 std::swap(SrcIdx, DstIdx);
340 CrossClass = NewRC != DstRC || NewRC != SrcRC;
342 // Check our invariants
343 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
344 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
345 "Cannot have a physical SubIdx");
351 bool CoalescerPair::flip() {
352 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
354 std::swap(SrcReg, DstReg);
355 std::swap(SrcIdx, DstIdx);
360 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
363 unsigned Src, Dst, SrcSub, DstSub;
364 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
367 // Find the virtual register that is SrcReg.
370 std::swap(SrcSub, DstSub);
371 } else if (Src != SrcReg) {
375 // Now check that Dst matches DstReg.
376 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
377 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
379 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
380 // DstSub could be set for a physreg from INSERT_SUBREG.
382 Dst = TRI.getSubReg(Dst, DstSub);
385 return DstReg == Dst;
386 // This is a partial register copy. Check that the parts match.
387 return TRI.getSubReg(DstReg, SrcSub) == Dst;
389 // DstReg is virtual.
392 // Registers match, do the subregisters line up?
393 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
394 TRI.composeSubRegIndices(DstIdx, DstSub);
398 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
399 AU.setPreservesCFG();
400 AU.addRequired<AliasAnalysis>();
401 AU.addRequired<LiveIntervals>();
402 AU.addPreserved<LiveIntervals>();
403 AU.addRequired<LiveDebugVariables>();
404 AU.addPreserved<LiveDebugVariables>();
405 AU.addPreserved<SlotIndexes>();
406 AU.addRequired<MachineLoopInfo>();
407 AU.addPreserved<MachineLoopInfo>();
408 AU.addPreservedID(MachineDominatorsID);
409 MachineFunctionPass::getAnalysisUsage(AU);
412 void RegisterCoalescer::eliminateDeadDefs() {
413 SmallVector<LiveInterval*, 8> NewRegs;
414 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
417 // Callback from eliminateDeadDefs().
418 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
419 // MI may be in WorkList. Make sure we don't visit it.
420 ErasedInstrs.insert(MI);
423 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
424 /// being the source and IntB being the dest, thus this defines a value number
425 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
426 /// see if we can merge these two pieces of B into a single value number,
427 /// eliminating a copy. For example:
431 /// B1 = A3 <- this copy
433 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
434 /// value number to be replaced with B0 (which simplifies the B liveinterval).
436 /// This returns true if an interval was modified.
438 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
439 MachineInstr *CopyMI) {
440 assert(!CP.isPartial() && "This doesn't work for partial copies.");
441 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
444 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
446 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
447 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
449 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
450 // the example above.
451 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
452 if (BLR == IntB.end()) return false;
453 VNInfo *BValNo = BLR->valno;
455 // Get the location that B is defined at. Two options: either this value has
456 // an unknown definition point or it is defined at CopyIdx. If unknown, we
458 if (BValNo->def != CopyIdx) return false;
460 // AValNo is the value number in A that defines the copy, A3 in the example.
461 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
462 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
463 // The live range might not exist after fun with physreg coalescing.
464 if (ALR == IntA.end()) return false;
465 VNInfo *AValNo = ALR->valno;
467 // If AValNo is defined as a copy from IntB, we can potentially process this.
468 // Get the instruction that defines this value number.
469 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
470 // Don't allow any partial copies, even if isCoalescable() allows them.
471 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
474 // Get the LiveRange in IntB that this value number starts with.
475 LiveInterval::iterator ValLR =
476 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
477 if (ValLR == IntB.end())
480 // Make sure that the end of the live range is inside the same block as
482 MachineInstr *ValLREndInst =
483 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
484 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
487 // Okay, we now know that ValLR ends in the same block that the CopyMI
488 // live-range starts. If there are no intervening live ranges between them in
489 // IntB, we can merge them.
490 if (ValLR+1 != BLR) return false;
492 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
494 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
495 // We are about to delete CopyMI, so need to remove it as the 'instruction
496 // that defines this value #'. Update the valnum with the new defining
498 BValNo->def = FillerStart;
500 // Okay, we can merge them. We need to insert a new liverange:
501 // [ValLR.end, BLR.begin) of either value number, then we merge the
502 // two value numbers.
503 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
505 // Okay, merge "B1" into the same value number as "B0".
506 if (BValNo != ValLR->valno)
507 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
508 DEBUG(dbgs() << " result = " << IntB << '\n');
510 // If the source instruction was killing the source register before the
511 // merge, unset the isKill marker given the live range has been extended.
512 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
514 ValLREndInst->getOperand(UIdx).setIsKill(false);
517 // Rewrite the copy. If the copy instruction was killing the destination
518 // register before the merge, find the last use and trim the live range. That
519 // will also add the isKill marker.
520 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
521 if (ALR->end == CopyIdx)
522 LIS->shrinkToUses(&IntA);
528 /// hasOtherReachingDefs - Return true if there are definitions of IntB
529 /// other than BValNo val# that can reach uses of AValno val# of IntA.
530 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
534 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
536 if (LIS->hasPHIKill(IntA, AValNo))
539 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
541 if (AI->valno != AValNo) continue;
542 LiveInterval::Ranges::iterator BI =
543 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
544 if (BI != IntB.ranges.begin())
546 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
547 if (BI->valno == BValNo)
549 if (BI->start <= AI->start && BI->end > AI->start)
551 if (BI->start > AI->start && BI->start < AI->end)
558 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
559 /// IntA being the source and IntB being the dest, thus this defines a value
560 /// number in IntB. If the source value number (in IntA) is defined by a
561 /// commutable instruction and its other operand is coalesced to the copy dest
562 /// register, see if we can transform the copy into a noop by commuting the
563 /// definition. For example,
565 /// A3 = op A2 B0<kill>
567 /// B1 = A3 <- this copy
569 /// = op A3 <- more uses
573 /// B2 = op B0 A2<kill>
575 /// B1 = B2 <- now an identify copy
577 /// = op B2 <- more uses
579 /// This returns true if an interval was modified.
581 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
582 MachineInstr *CopyMI) {
583 assert (!CP.isPhys());
585 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
588 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
590 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
592 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
593 // the example above.
594 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
595 if (!BValNo || BValNo->def != CopyIdx)
598 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
600 // AValNo is the value number in A that defines the copy, A3 in the example.
601 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
602 assert(AValNo && "COPY source not live");
603 if (AValNo->isPHIDef() || AValNo->isUnused())
605 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
608 if (!DefMI->isCommutable())
610 // If DefMI is a two-address instruction then commuting it will change the
611 // destination register.
612 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
613 assert(DefIdx != -1);
615 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
617 unsigned Op1, Op2, NewDstIdx;
618 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
622 else if (Op2 == UseOpIdx)
627 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
628 unsigned NewReg = NewDstMO.getReg();
629 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
632 // Make sure there are no other definitions of IntB that would reach the
633 // uses which the new definition can reach.
634 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
637 // If some of the uses of IntA.reg is already coalesced away, return false.
638 // It's not possible to determine whether it's safe to perform the coalescing.
639 for (MachineRegisterInfo::use_nodbg_iterator UI =
640 MRI->use_nodbg_begin(IntA.reg),
641 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
642 MachineInstr *UseMI = &*UI;
643 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
644 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
645 if (ULR == IntA.end() || ULR->valno != AValNo)
647 // If this use is tied to a def, we can't rewrite the register.
648 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
652 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
655 // At this point we have decided that it is legal to do this
656 // transformation. Start by commuting the instruction.
657 MachineBasicBlock *MBB = DefMI->getParent();
658 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
661 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
662 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
663 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
665 if (NewMI != DefMI) {
666 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
667 MachineBasicBlock::iterator Pos = DefMI;
668 MBB->insert(Pos, NewMI);
671 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
672 NewMI->getOperand(OpIdx).setIsKill();
674 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
683 // Update uses of IntA of the specific Val# with IntB.
684 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
685 UE = MRI->use_end(); UI != UE;) {
686 MachineOperand &UseMO = UI.getOperand();
687 MachineInstr *UseMI = &*UI;
689 if (UseMI->isDebugValue()) {
690 // FIXME These don't have an instruction index. Not clear we have enough
691 // info to decide whether to do this replacement or not. For now do it.
692 UseMO.setReg(NewReg);
695 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
696 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
697 if (ULR == IntA.end() || ULR->valno != AValNo)
699 // Kill flags are no longer accurate. They are recomputed after RA.
700 UseMO.setIsKill(false);
701 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
702 UseMO.substPhysReg(NewReg, *TRI);
704 UseMO.setReg(NewReg);
707 if (!UseMI->isCopy())
709 if (UseMI->getOperand(0).getReg() != IntB.reg ||
710 UseMI->getOperand(0).getSubReg())
713 // This copy will become a noop. If it's defining a new val#, merge it into
715 SlotIndex DefIdx = UseIdx.getRegSlot();
716 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
719 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
720 assert(DVNI->def == DefIdx);
721 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
722 ErasedInstrs.insert(UseMI);
723 LIS->RemoveMachineInstrFromMaps(UseMI);
724 UseMI->eraseFromParent();
727 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
729 VNInfo *ValNo = BValNo;
730 ValNo->def = AValNo->def;
731 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
733 if (AI->valno != AValNo) continue;
734 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
736 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
738 IntA.removeValNo(AValNo);
739 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
744 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
745 /// computation, replace the copy by rematerialize the definition.
746 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
748 MachineInstr *CopyMI) {
749 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
750 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
751 assert(SrcLR != SrcInt.end() && "Live range not found!");
752 VNInfo *ValNo = SrcLR->valno;
753 if (ValNo->isPHIDef() || ValNo->isUnused())
755 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
758 assert(DefMI && "Defining instruction disappeared");
759 if (!DefMI->isAsCheapAsAMove())
761 if (!TII->isTriviallyReMaterializable(DefMI, AA))
763 bool SawStore = false;
764 if (!DefMI->isSafeToMove(TII, AA, SawStore))
766 const MCInstrDesc &MCID = DefMI->getDesc();
767 if (MCID.getNumDefs() != 1)
769 if (!DefMI->isImplicitDef()) {
770 // Make sure the copy destination register class fits the instruction
771 // definition register class. The mismatch can happen as a result of earlier
772 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
773 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
774 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
775 if (MRI->getRegClass(DstReg) != RC)
777 } else if (!RC->contains(DstReg))
781 MachineBasicBlock *MBB = CopyMI->getParent();
782 MachineBasicBlock::iterator MII =
783 llvm::next(MachineBasicBlock::iterator(CopyMI));
784 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
785 MachineInstr *NewMI = prior(MII);
787 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
788 // We need to remember these so we can add intervals once we insert
789 // NewMI into SlotIndexes.
790 SmallVector<unsigned, 4> NewMIImplDefs;
791 for (unsigned i = NewMI->getDesc().getNumOperands(),
792 e = NewMI->getNumOperands(); i != e; ++i) {
793 MachineOperand &MO = NewMI->getOperand(i);
795 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
796 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
797 NewMIImplDefs.push_back(MO.getReg());
801 // CopyMI may have implicit operands, transfer them over to the newly
802 // rematerialized instruction. And update implicit def interval valnos.
803 for (unsigned i = CopyMI->getDesc().getNumOperands(),
804 e = CopyMI->getNumOperands(); i != e; ++i) {
805 MachineOperand &MO = CopyMI->getOperand(i);
807 assert(MO.isImplicit() && "No explicit operands after implict operands.");
808 // Discard VReg implicit defs.
809 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
810 NewMI->addOperand(MO);
815 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
817 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
818 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
819 unsigned Reg = NewMIImplDefs[i];
820 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
821 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
822 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
825 CopyMI->eraseFromParent();
826 ErasedInstrs.insert(CopyMI);
827 DEBUG(dbgs() << "Remat: " << *NewMI);
830 // The source interval can become smaller because we removed a use.
831 LIS->shrinkToUses(&SrcInt, &DeadDefs);
832 if (!DeadDefs.empty())
838 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
839 /// values, it only removes local variables. When we have a copy like:
841 /// %vreg1 = COPY %vreg2<undef>
843 /// We delete the copy and remove the corresponding value number from %vreg1.
844 /// Any uses of that value number are marked as <undef>.
845 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
846 const CoalescerPair &CP) {
847 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
848 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
849 if (SrcInt->liveAt(Idx))
851 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
852 if (DstInt->liveAt(Idx))
855 // No intervals are live-in to CopyMI - it is undef.
860 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
861 assert(DeadVNI && "No value defined in DstInt");
862 DstInt->removeValNo(DeadVNI);
864 // Find new undef uses.
865 for (MachineRegisterInfo::reg_nodbg_iterator
866 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
868 MachineOperand &MO = I.getOperand();
869 if (MO.isDef() || MO.isUndef())
871 MachineInstr *MI = MO.getParent();
872 SlotIndex Idx = LIS->getInstructionIndex(MI);
873 if (DstInt->liveAt(Idx))
876 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
881 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
882 /// update the subregister number if it is not zero. If DstReg is a
883 /// physical register and the existing subregister number of the def / use
884 /// being updated is not zero, make sure to set it to the correct physical
886 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
889 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
890 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
892 // Update LiveDebugVariables.
893 LDV->renameRegister(SrcReg, DstReg, SubIdx);
895 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
896 MachineInstr *UseMI = I.skipInstruction();) {
897 SmallVector<unsigned,8> Ops;
899 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
901 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
902 // because SrcReg is a sub-register.
903 if (DstInt && !Reads && SubIdx)
904 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
906 // Replace SrcReg with DstReg in all UseMI operands.
907 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
908 MachineOperand &MO = UseMI->getOperand(Ops[i]);
910 // Adjust <undef> flags in case of sub-register joins. We don't want to
911 // turn a full def into a read-modify-write sub-register def and vice
913 if (SubIdx && MO.isDef())
914 MO.setIsUndef(!Reads);
917 MO.substPhysReg(DstReg, *TRI);
919 MO.substVirtReg(DstReg, SubIdx, *TRI);
923 dbgs() << "\t\tupdated: ";
924 if (!UseMI->isDebugValue())
925 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
931 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
932 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
933 /// Always join simple intervals that are defined by a single copy from a
934 /// reserved register. This doesn't increase register pressure, so it is
935 /// always beneficial.
936 if (!MRI->isReserved(CP.getDstReg())) {
937 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
941 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
942 if (CP.isFlipped() && JoinVInt.containsOneValue())
945 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
949 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
950 /// which are the src/dst of the copy instruction CopyMI. This returns true
951 /// if the copy was successfully coalesced away. If it is not currently
952 /// possible to coalesce this interval, but it may be possible if other
953 /// things get coalesced, then it returns true by reference in 'Again'.
954 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
957 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
959 CoalescerPair CP(*TRI);
960 if (!CP.setRegisters(CopyMI)) {
961 DEBUG(dbgs() << "\tNot coalescable.\n");
965 // Dead code elimination. This really should be handled by MachineDCE, but
966 // sometimes dead copies slip through, and we can't generate invalid live
968 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
969 DEBUG(dbgs() << "\tCopy is dead.\n");
970 DeadDefs.push_back(CopyMI);
976 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
977 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
978 LIS->RemoveMachineInstrFromMaps(CopyMI);
979 CopyMI->eraseFromParent();
980 return false; // Not coalescable.
983 // Coalesced copies are normally removed immediately, but transformations
984 // like removeCopyByCommutingDef() can inadvertently create identity copies.
985 // When that happens, just join the values and remove the copy.
986 if (CP.getSrcReg() == CP.getDstReg()) {
987 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
988 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
989 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
990 if (VNInfo *DefVNI = LRQ.valueDefined()) {
991 VNInfo *ReadVNI = LRQ.valueIn();
992 assert(ReadVNI && "No value before copy and no <undef> flag.");
993 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
994 LI.MergeValueNumberInto(DefVNI, ReadVNI);
995 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
997 LIS->RemoveMachineInstrFromMaps(CopyMI);
998 CopyMI->eraseFromParent();
1002 // Enforce policies.
1004 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1005 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1007 if (!canJoinPhys(CP)) {
1008 // Before giving up coalescing, if definition of source is defined by
1009 // trivial computation, try rematerializing it.
1010 if (!CP.isFlipped() &&
1011 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1012 CP.getDstReg(), CopyMI))
1018 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1020 if (CP.getDstIdx() && CP.getSrcIdx())
1021 dbgs() << PrintReg(CP.getDstReg()) << " in "
1022 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1023 << PrintReg(CP.getSrcReg()) << " in "
1024 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1026 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1027 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1030 // When possible, let DstReg be the larger interval.
1031 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1032 LIS->getInterval(CP.getDstReg()).ranges.size())
1036 // Okay, attempt to join these two intervals. On failure, this returns false.
1037 // Otherwise, if one of the intervals being joined is a physreg, this method
1038 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1039 // been modified, so we can use this information below to update aliases.
1040 if (!joinIntervals(CP)) {
1041 // Coalescing failed.
1043 // If definition of source is defined by trivial computation, try
1044 // rematerializing it.
1045 if (!CP.isFlipped() &&
1046 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1047 CP.getDstReg(), CopyMI))
1050 // If we can eliminate the copy without merging the live ranges, do so now.
1051 if (!CP.isPartial() && !CP.isPhys()) {
1052 if (adjustCopiesBackFrom(CP, CopyMI) ||
1053 removeCopyByCommutingDef(CP, CopyMI)) {
1054 LIS->RemoveMachineInstrFromMaps(CopyMI);
1055 CopyMI->eraseFromParent();
1056 DEBUG(dbgs() << "\tTrivial!\n");
1061 // Otherwise, we are unable to join the intervals.
1062 DEBUG(dbgs() << "\tInterference!\n");
1063 Again = true; // May be possible to coalesce later.
1067 // Coalescing to a virtual register that is of a sub-register class of the
1068 // other. Make sure the resulting register is set to the right register class.
1069 if (CP.isCrossClass()) {
1071 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1074 // Removing sub-register copies can ease the register class constraints.
1075 // Make sure we attempt to inflate the register class of DstReg.
1076 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1077 InflateRegs.push_back(CP.getDstReg());
1079 // CopyMI has been erased by joinIntervals at this point. Remove it from
1080 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1081 // to the work list. This keeps ErasedInstrs from growing needlessly.
1082 ErasedInstrs.erase(CopyMI);
1084 // Rewrite all SrcReg operands to DstReg.
1085 // Also update DstReg operands to include DstIdx if it is set.
1087 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1088 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1090 // SrcReg is guaranteed to be the register whose live interval that is
1092 LIS->removeInterval(CP.getSrcReg());
1094 // Update regalloc hint.
1095 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1098 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1100 dbgs() << LIS->getInterval(CP.getDstReg());
1108 /// Attempt joining with a reserved physreg.
1109 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1110 assert(CP.isPhys() && "Must be a physreg copy");
1111 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1112 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1113 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1116 assert(CP.isFlipped() && RHS.containsOneValue() &&
1117 "Invalid join with reserved register");
1119 // Optimization for reserved registers like ESP. We can only merge with a
1120 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1121 // The live range of the reserved register will look like a set of dead defs
1122 // - we don't properly track the live range of reserved registers.
1124 // Deny any overlapping intervals. This depends on all the reserved
1125 // register live ranges to look like dead defs.
1126 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1127 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1128 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1132 // Skip any value computations, we are not adding new values to the
1133 // reserved register. Also skip merging the live ranges, the reserved
1134 // register live range doesn't need to be accurate as long as all the
1137 // Delete the identity copy.
1138 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1139 LIS->RemoveMachineInstrFromMaps(CopyMI);
1140 CopyMI->eraseFromParent();
1142 // We don't track kills for reserved registers.
1143 MRI->clearKillFlags(CP.getSrcReg());
1148 //===----------------------------------------------------------------------===//
1149 // Interference checking and interval joining
1150 //===----------------------------------------------------------------------===//
1152 // In the easiest case, the two live ranges being joined are disjoint, and
1153 // there is no interference to consider. It is quite common, though, to have
1154 // overlapping live ranges, and we need to check if the interference can be
1157 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1158 // This means that two SSA values overlap if and only if the def of one value
1159 // is contained in the live range of the other value. As a special case, the
1160 // overlapping values can be defined at the same index.
1162 // The interference from an overlapping def can be resolved in these cases:
1164 // 1. Coalescable copies. The value is defined by a copy that would become an
1165 // identity copy after joining SrcReg and DstReg. The copy instruction will
1166 // be removed, and the value will be merged with the source value.
1168 // There can be several copies back and forth, causing many values to be
1169 // merged into one. We compute a list of ultimate values in the joined live
1170 // range as well as a mappings from the old value numbers.
1172 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1173 // predecessors have a live out value. It doesn't cause real interference,
1174 // and can be merged into the value it overlaps. Like a coalescable copy, it
1175 // can be erased after joining.
1177 // 3. Copy of external value. The overlapping def may be a copy of a value that
1178 // is already in the other register. This is like a coalescable copy, but
1179 // the live range of the source register must be trimmed after erasing the
1180 // copy instruction:
1183 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1185 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1186 // defining one lane at a time:
1188 // %dst:ssub0<def,read-undef> = FOO
1190 // %dst:ssub1<def> = COPY %src
1192 // The live range of %src overlaps the %dst value defined by FOO, but
1193 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1194 // which was undef anyway.
1196 // The value mapping is more complicated in this case. The final live range
1197 // will have different value numbers for both FOO and BAR, but there is no
1198 // simple mapping from old to new values. It may even be necessary to add
1201 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1202 // is live, but never read. This can happen because we don't compute
1203 // individual live ranges per lane.
1207 // %dst:ssub1<def> = COPY %src
1209 // This kind of interference is only resolved locally. If the clobbered
1210 // lane value escapes the block, the join is aborted.
1213 /// Track information about values in a single virtual register about to be
1214 /// joined. Objects of this class are always created in pairs - one for each
1215 /// side of the CoalescerPair.
1219 // Location of this register in the final joined register.
1220 // Either CP.DstIdx or CP.SrcIdx.
1223 // Values that will be present in the final live range.
1224 SmallVectorImpl<VNInfo*> &NewVNInfo;
1226 const CoalescerPair &CP;
1228 SlotIndexes *Indexes;
1229 const TargetRegisterInfo *TRI;
1231 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1232 // This is suitable for passing to LiveInterval::join().
1233 SmallVector<int, 8> Assignments;
1235 // Conflict resolution for overlapping values.
1236 enum ConflictResolution {
1237 // No overlap, simply keep this value.
1240 // Merge this value into OtherVNI and erase the defining instruction.
1241 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1245 // Merge this value into OtherVNI but keep the defining instruction.
1246 // This is for the special case where OtherVNI is defined by the same
1250 // Keep this value, and have it replace OtherVNI where possible. This
1251 // complicates value mapping since OtherVNI maps to two different values
1252 // before and after this def.
1253 // Used when clobbering undefined or dead lanes.
1256 // Unresolved conflict. Visit later when all values have been mapped.
1259 // Unresolvable conflict. Abort the join.
1263 // Per-value info for LI. The lane bit masks are all relative to the final
1264 // joined register, so they can be compared directly between SrcReg and
1267 ConflictResolution Resolution;
1269 // Lanes written by this def, 0 for unanalyzed values.
1270 unsigned WriteLanes;
1272 // Lanes with defined values in this register. Other lanes are undef and
1274 unsigned ValidLanes;
1276 // Value in LI being redefined by this def.
1279 // Value in the other live range that overlaps this def, if any.
1282 // Is this value an IMPLICIT_DEF?
1285 // True when the live range of this value will be pruned because of an
1286 // overlapping CR_Replace value in the other live range.
1289 // True once Pruned above has been computed.
1290 bool PrunedComputed;
1292 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1293 RedefVNI(0), OtherVNI(0), IsImplicitDef(false), Pruned(false),
1294 PrunedComputed(false) {}
1296 bool isAnalyzed() const { return WriteLanes != 0; }
1299 // One entry per value number in LI.
1300 SmallVector<Val, 8> Vals;
1302 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1303 VNInfo *stripCopies(VNInfo *VNI);
1304 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1305 void computeAssignment(unsigned ValNo, JoinVals &Other);
1306 bool taintExtent(unsigned, unsigned, JoinVals&,
1307 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1308 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1309 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1312 JoinVals(LiveInterval &li, unsigned subIdx,
1313 SmallVectorImpl<VNInfo*> &newVNInfo,
1314 const CoalescerPair &cp,
1316 const TargetRegisterInfo *tri)
1317 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1318 Indexes(LIS->getSlotIndexes()), TRI(tri),
1319 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1322 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1323 /// Returns false if any conflicts were impossible to resolve.
1324 bool mapValues(JoinVals &Other);
1326 /// Try to resolve conflicts that require all values to be mapped.
1327 /// Returns false if any conflicts were impossible to resolve.
1328 bool resolveConflicts(JoinVals &Other);
1330 /// Prune the live range of values in Other.LI where they would conflict with
1331 /// CR_Replace values in LI. Collect end points for restoring the live range
1333 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1335 /// Erase any machine instructions that have been coalesced away.
1336 /// Add erased instructions to ErasedInstrs.
1337 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1338 /// the erased instrs.
1339 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1340 SmallVectorImpl<unsigned> &ShrinkRegs);
1342 /// Get the value assignments suitable for passing to LiveInterval::join.
1343 const int *getAssignments() const { return Assignments.data(); }
1345 } // end anonymous namespace
1347 /// Compute the bitmask of lanes actually written by DefMI.
1348 /// Set Redef if there are any partial register definitions that depend on the
1349 /// previous value of the register.
1350 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1352 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1353 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1355 L |= TRI->getSubRegIndexLaneMask(
1356 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1363 /// Find the ultimate value that VNI was copied from.
1364 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1365 while (!VNI->isPHIDef()) {
1366 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1367 assert(MI && "No defining instruction");
1368 if (!MI->isFullCopy())
1370 unsigned Reg = MI->getOperand(1).getReg();
1371 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1373 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1376 VNI = LRQ.valueIn();
1381 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1382 /// Return a conflict resolution when possible, but leave the hard cases as
1384 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1385 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1386 /// The recursion always goes upwards in the dominator tree, making loops
1388 JoinVals::ConflictResolution
1389 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1390 Val &V = Vals[ValNo];
1391 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1392 VNInfo *VNI = LI.getValNumInfo(ValNo);
1393 if (VNI->isUnused()) {
1398 // Get the instruction defining this value, compute the lanes written.
1399 const MachineInstr *DefMI = 0;
1400 if (VNI->isPHIDef()) {
1401 // Conservatively assume that all lanes in a PHI are valid.
1402 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1404 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1406 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1408 // If this is a read-modify-write instruction, there may be more valid
1409 // lanes than the ones written by this instruction.
1410 // This only covers partial redef operands. DefMI may have normal use
1411 // operands reading the register. They don't contribute valid lanes.
1413 // This adds ssub1 to the set of valid lanes in %src:
1415 // %src:ssub1<def> = FOO
1417 // This leaves only ssub1 valid, making any other lanes undef:
1419 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1421 // The <read-undef> flag on the def operand means that old lane values are
1424 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1425 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1426 computeAssignment(V.RedefVNI->id, Other);
1427 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1430 // An IMPLICIT_DEF writes undef values.
1431 if (DefMI->isImplicitDef()) {
1432 V.IsImplicitDef = true;
1433 V.ValidLanes &= ~V.WriteLanes;
1437 // Find the value in Other that overlaps VNI->def, if any.
1438 LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1440 // It is possible that both values are defined by the same instruction, or
1441 // the values are PHIs defined in the same block. When that happens, the two
1442 // values should be merged into one, but not into any preceding value.
1443 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1444 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1445 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1447 // One value stays, the other is merged. Keep the earlier one, or the first
1449 if (OtherVNI->def < VNI->def)
1450 Other.computeAssignment(OtherVNI->id, *this);
1451 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1452 // This is an early-clobber def overlapping a live-in value in the other
1453 // register. Not mergeable.
1454 V.OtherVNI = OtherLRQ.valueIn();
1455 return CR_Impossible;
1457 V.OtherVNI = OtherVNI;
1458 Val &OtherV = Other.Vals[OtherVNI->id];
1459 // Keep this value, check for conflicts when analyzing OtherVNI.
1460 if (!OtherV.isAnalyzed())
1462 // Both sides have been analyzed now.
1463 // Allow overlapping PHI values. Any real interference would show up in a
1464 // predecessor, the PHI itself can't introduce any conflicts.
1465 if (VNI->isPHIDef())
1467 if (V.ValidLanes & OtherV.ValidLanes)
1468 // Overlapping lanes can't be resolved.
1469 return CR_Impossible;
1474 // No simultaneous def. Is Other live at the def?
1475 V.OtherVNI = OtherLRQ.valueIn();
1477 // No overlap, no conflict.
1480 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1482 // We have overlapping values, or possibly a kill of Other.
1483 // Recursively compute assignments up the dominator tree.
1484 Other.computeAssignment(V.OtherVNI->id, *this);
1485 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1487 // Allow overlapping PHI values. Any real interference would show up in a
1488 // predecessor, the PHI itself can't introduce any conflicts.
1489 if (VNI->isPHIDef())
1492 // Check for simple erasable conflicts.
1493 if (DefMI->isImplicitDef())
1496 // Include the non-conflict where DefMI is a coalescable copy that kills
1497 // OtherVNI. We still want the copy erased and value numbers merged.
1498 if (CP.isCoalescable(DefMI)) {
1499 // Some of the lanes copied from OtherVNI may be undef, making them undef
1501 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1505 // This may not be a real conflict if DefMI simply kills Other and defines
1507 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1510 // Handle the case where VNI and OtherVNI can be proven to be identical:
1512 // %other = COPY %ext
1513 // %this = COPY %ext <-- Erase this copy
1515 if (DefMI->isFullCopy() && !CP.isPartial() &&
1516 stripCopies(VNI) == stripCopies(V.OtherVNI))
1519 // If the lanes written by this instruction were all undef in OtherVNI, it is
1520 // still safe to join the live ranges. This can't be done with a simple value
1521 // mapping, though - OtherVNI will map to multiple values:
1523 // 1 %dst:ssub0 = FOO <-- OtherVNI
1524 // 2 %src = BAR <-- VNI
1525 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1527 // 5 QUUX %src<kill>
1529 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1530 // handles this complex value mapping.
1531 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1534 // If the other live range is killed by DefMI and the live ranges are still
1535 // overlapping, it must be because we're looking at an early clobber def:
1537 // %dst<def,early-clobber> = ASM %src<kill>
1539 // In this case, it is illegal to merge the two live ranges since the early
1540 // clobber def would clobber %src before it was read.
1541 if (OtherLRQ.isKill()) {
1542 // This case where the def doesn't overlap the kill is handled above.
1543 assert(VNI->def.isEarlyClobber() &&
1544 "Only early clobber defs can overlap a kill");
1545 return CR_Impossible;
1548 // VNI is clobbering live lanes in OtherVNI, but there is still the
1549 // possibility that no instructions actually read the clobbered lanes.
1550 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1551 // Otherwise Other.LI wouldn't be live here.
1552 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1553 return CR_Impossible;
1555 // We need to verify that no instructions are reading the clobbered lanes. To
1556 // save compile time, we'll only check that locally. Don't allow the tainted
1557 // value to escape the basic block.
1558 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1559 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1560 return CR_Impossible;
1562 // There are still some things that could go wrong besides clobbered lanes
1563 // being read, for example OtherVNI may be only partially redefined in MBB,
1564 // and some clobbered lanes could escape the block. Save this analysis for
1565 // resolveConflicts() when all values have been mapped. We need to know
1566 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1567 // that now - the recursive analyzeValue() calls must go upwards in the
1569 return CR_Unresolved;
1572 /// Compute the value assignment for ValNo in LI.
1573 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1575 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1576 Val &V = Vals[ValNo];
1577 if (V.isAnalyzed()) {
1578 // Recursion should always move up the dominator tree, so ValNo is not
1579 // supposed to reappear before it has been assigned.
1580 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1583 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1586 // Merge this ValNo into OtherVNI.
1587 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1588 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1589 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1590 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1591 << LI.getValNumInfo(ValNo)->def << " into "
1592 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1593 << V.OtherVNI->def << " --> @"
1594 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1598 // The other value is going to be pruned if this join is successful.
1599 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1600 Other.Vals[V.OtherVNI->id].Pruned = true;
1603 // This value number needs to go in the final joined live range.
1604 Assignments[ValNo] = NewVNInfo.size();
1605 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1610 bool JoinVals::mapValues(JoinVals &Other) {
1611 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1612 computeAssignment(i, Other);
1613 if (Vals[i].Resolution == CR_Impossible) {
1614 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1615 << '@' << LI.getValNumInfo(i)->def << '\n');
1622 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1623 /// the extent of the tainted lanes in the block.
1625 /// Multiple values in Other.LI can be affected since partial redefinitions can
1626 /// preserve previously tainted lanes.
1628 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1629 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1630 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1631 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1633 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1634 /// entry to TaintedVals.
1636 /// Returns false if the tainted lanes extend beyond the basic block.
1638 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1639 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1640 VNInfo *VNI = LI.getValNumInfo(ValNo);
1641 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1642 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1644 // Scan Other.LI from VNI.def to MBBEnd.
1645 LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1646 assert(OtherI != Other.LI.end() && "No conflict?");
1648 // OtherI is pointing to a tainted value. Abort the join if the tainted
1649 // lanes escape the block.
1650 SlotIndex End = OtherI->end;
1651 if (End >= MBBEnd) {
1652 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1653 << OtherI->valno->id << '@' << OtherI->start << '\n');
1656 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1657 << OtherI->valno->id << '@' << OtherI->start
1658 << " to " << End << '\n');
1659 // A dead def is not a problem.
1662 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1664 // Check for another def in the MBB.
1665 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1668 // Lanes written by the new def are no longer tainted.
1669 const Val &OV = Other.Vals[OtherI->valno->id];
1670 TaintedLanes &= ~OV.WriteLanes;
1673 } while (TaintedLanes);
1677 /// Return true if MI uses any of the given Lanes from Reg.
1678 /// This does not include partial redefinitions of Reg.
1679 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1681 if (MI->isDebugValue())
1683 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1684 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1686 if (!MO->readsReg())
1688 if (Lanes & TRI->getSubRegIndexLaneMask(
1689 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1695 bool JoinVals::resolveConflicts(JoinVals &Other) {
1696 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1698 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1699 if (V.Resolution != CR_Unresolved)
1701 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1702 << '@' << LI.getValNumInfo(i)->def << '\n');
1704 assert(V.OtherVNI && "Inconsistent conflict resolution.");
1705 VNInfo *VNI = LI.getValNumInfo(i);
1706 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1708 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1709 // join, those lanes will be tainted with a wrong value. Get the extent of
1710 // the tainted lanes.
1711 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1712 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1713 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1714 // Tainted lanes would extend beyond the basic block.
1717 assert(!TaintExtent.empty() && "There should be at least one conflict.");
1719 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1720 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1721 MachineBasicBlock::iterator MI = MBB->begin();
1722 if (!VNI->isPHIDef()) {
1723 MI = Indexes->getInstructionFromIndex(VNI->def);
1724 // No need to check the instruction defining VNI for reads.
1727 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1728 "Interference ends on VNI->def. Should have been handled earlier");
1729 MachineInstr *LastMI =
1730 Indexes->getInstructionFromIndex(TaintExtent.front().first);
1731 assert(LastMI && "Range must end at a proper instruction");
1732 unsigned TaintNum = 0;
1734 assert(MI != MBB->end() && "Bad LastMI");
1735 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1736 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1739 // LastMI is the last instruction to use the current value.
1740 if (&*MI == LastMI) {
1741 if (++TaintNum == TaintExtent.size())
1743 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1744 assert(LastMI && "Range must end at a proper instruction");
1745 TaintedLanes = TaintExtent[TaintNum].second;
1750 // The tainted lanes are unused.
1751 V.Resolution = CR_Replace;
1757 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1761 // %src = COPY %dst <-- This value to be pruned.
1762 // %dst = COPY %src <-- This value is a copy of a pruned value.
1764 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1765 Val &V = Vals[ValNo];
1766 if (V.Pruned || V.PrunedComputed)
1769 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1772 // Follow copies up the dominator tree and check if any intermediate value
1774 V.PrunedComputed = true;
1775 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1779 void JoinVals::pruneValues(JoinVals &Other,
1780 SmallVectorImpl<SlotIndex> &EndPoints) {
1781 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1782 SlotIndex Def = LI.getValNumInfo(i)->def;
1783 switch (Vals[i].Resolution) {
1787 // This value takes precedence over the value in Other.LI.
1788 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1789 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1790 // instructions are only inserted to provide a live-out value for PHI
1791 // predecessors, so the instruction should simply go away once its value
1792 // has been replaced.
1793 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1794 bool EraseImpDef = OtherV.IsImplicitDef && OtherV.Resolution == CR_Keep;
1795 if (!Def.isBlock()) {
1796 // Remove <def,read-undef> flags. This def is now a partial redef.
1797 // Also remove <def,dead> flags since the joined live range will
1798 // continue past this instruction.
1799 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1801 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1802 MO->setIsUndef(EraseImpDef);
1803 MO->setIsDead(false);
1805 // This value will reach instructions below, but we need to make sure
1806 // the live range also reaches the instruction at Def.
1808 EndPoints.push_back(Def);
1810 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1811 << ": " << Other.LI << '\n');
1816 if (isPrunedValue(i, Other)) {
1817 // This value is ultimately a copy of a pruned value in LI or Other.LI.
1818 // We can no longer trust the value mapping computed by
1819 // computeAssignment(), the value that was originally copied could have
1821 LIS->pruneValue(&LI, Def, &EndPoints);
1822 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1823 << Def << ": " << LI << '\n');
1828 llvm_unreachable("Unresolved conflicts");
1833 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1834 SmallVectorImpl<unsigned> &ShrinkRegs) {
1835 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1836 // Get the def location before markUnused() below invalidates it.
1837 SlotIndex Def = LI.getValNumInfo(i)->def;
1838 switch (Vals[i].Resolution) {
1840 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1841 // longer. The IMPLICIT_DEF instructions are only inserted by
1842 // PHIElimination to guarantee that all PHI predecessors have a value.
1843 if (!Vals[i].IsImplicitDef || !Vals[i].Pruned)
1845 // Remove value number i from LI. Note that this VNInfo is still present
1846 // in NewVNInfo, so it will appear as an unused value number in the final
1848 LI.getValNumInfo(i)->markUnused();
1849 LI.removeValNo(LI.getValNumInfo(i));
1850 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1854 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1855 assert(MI && "No instruction to erase");
1857 unsigned Reg = MI->getOperand(1).getReg();
1858 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1859 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1860 ShrinkRegs.push_back(Reg);
1862 ErasedInstrs.insert(MI);
1863 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1864 LIS->RemoveMachineInstrFromMaps(MI);
1865 MI->eraseFromParent();
1874 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1875 SmallVector<VNInfo*, 16> NewVNInfo;
1876 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1877 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1878 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1879 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1881 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1882 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1885 // First compute NewVNInfo and the simple value mappings.
1886 // Detect impossible conflicts early.
1887 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1890 // Some conflicts can only be resolved after all values have been mapped.
1891 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1894 // All clear, the live ranges can be merged.
1896 // The merging algorithm in LiveInterval::join() can't handle conflicting
1897 // value mappings, so we need to remove any live ranges that overlap a
1898 // CR_Replace resolution. Collect a set of end points that can be used to
1899 // restore the live range after joining.
1900 SmallVector<SlotIndex, 8> EndPoints;
1901 LHSVals.pruneValues(RHSVals, EndPoints);
1902 RHSVals.pruneValues(LHSVals, EndPoints);
1904 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1905 // registers to require trimming.
1906 SmallVector<unsigned, 8> ShrinkRegs;
1907 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1908 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1909 while (!ShrinkRegs.empty())
1910 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1912 // Join RHS into LHS.
1913 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1916 // Kill flags are going to be wrong if the live ranges were overlapping.
1917 // Eventually, we should simply clear all kill flags when computing live
1918 // ranges. They are reinserted after register allocation.
1919 MRI->clearKillFlags(LHS.reg);
1920 MRI->clearKillFlags(RHS.reg);
1922 if (EndPoints.empty())
1925 // Recompute the parts of the live range we had to remove because of
1926 // CR_Replace conflicts.
1927 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1928 << " points: " << LHS << '\n');
1929 LIS->extendToIndices(&LHS, EndPoints);
1933 /// joinIntervals - Attempt to join these two intervals. On failure, this
1935 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1936 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
1940 // Information concerning MBB coalescing priority.
1941 struct MBBPriorityInfo {
1942 MachineBasicBlock *MBB;
1946 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
1947 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
1950 // MBBPriorityCompare - Comparison predicate that sorts first based on the
1951 // loop depth of the basic block (the unsigned), and then on the MBB number.
1953 // EnableGlobalCopies assumes that the primary sort key is loop depth.
1954 struct MBBPriorityCompare {
1955 bool JoinSplitEdges;
1957 MBBPriorityCompare(bool joinsplits): JoinSplitEdges(joinsplits) {}
1959 bool operator()(const MBBPriorityInfo &LHS,
1960 const MBBPriorityInfo &RHS) const {
1961 // Deeper loops first
1962 if (LHS.Depth != RHS.Depth)
1963 return LHS.Depth > RHS.Depth;
1965 // Try to unsplit critical edges next.
1966 if (JoinSplitEdges && LHS.IsSplit != RHS.IsSplit)
1969 // Prefer blocks that are more connected in the CFG. This takes care of
1970 // the most difficult copies first while intervals are short.
1971 unsigned cl = LHS.MBB->pred_size() + LHS.MBB->succ_size();
1972 unsigned cr = RHS.MBB->pred_size() + RHS.MBB->succ_size();
1976 // As a last resort, sort by block number.
1977 return LHS.MBB->getNumber() < RHS.MBB->getNumber();
1982 /// \returns true if the given copy uses or defines a local live range.
1983 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
1984 if (!Copy->isCopy())
1987 unsigned SrcReg = Copy->getOperand(1).getReg();
1988 unsigned DstReg = Copy->getOperand(0).getReg();
1989 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
1990 || TargetRegisterInfo::isPhysicalRegister(DstReg))
1993 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
1994 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
1997 // Try joining WorkList copies starting from index From.
1998 // Null out any successful joins.
1999 bool RegisterCoalescer::
2000 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2001 bool Progress = false;
2002 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2005 // Skip instruction pointers that have already been erased, for example by
2006 // dead code elimination.
2007 if (ErasedInstrs.erase(CurrList[i])) {
2012 bool Success = joinCopy(CurrList[i], Again);
2013 Progress |= Success;
2014 if (Success || !Again)
2021 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2022 DEBUG(dbgs() << MBB->getName() << ":\n");
2024 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2025 // yet, it might invalidate the iterator.
2026 const unsigned PrevSize = WorkList.size();
2027 if (JoinGlobalCopies) {
2028 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2029 // are not inherently easier to resolve, but slightly preferable until we
2030 // have local live range splitting. In particular this is required by
2031 // cmp+jmp macro fusion.
2032 for (MachineBasicBlock::reverse_iterator
2033 MII = MBB->rbegin(), E = MBB->rend(); MII != E; ++MII) {
2034 if (!MII->isCopyLike())
2036 if (isLocalCopy(&(*MII), LIS))
2037 LocalWorkList.push_back(&(*MII));
2039 WorkList.push_back(&(*MII));
2043 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2045 if (MII->isCopyLike())
2046 WorkList.push_back(MII);
2048 // Try coalescing the collected copies immediately, and remove the nulls.
2049 // This prevents the WorkList from getting too large since most copies are
2050 // joinable on the first attempt.
2051 MutableArrayRef<MachineInstr*>
2052 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2053 if (copyCoalesceWorkList(CurrList))
2054 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2055 (MachineInstr*)0), WorkList.end());
2058 void RegisterCoalescer::coalesceLocals() {
2059 copyCoalesceWorkList(LocalWorkList);
2060 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2061 if (LocalWorkList[j])
2062 WorkList.push_back(LocalWorkList[j]);
2064 LocalWorkList.clear();
2067 void RegisterCoalescer::joinAllIntervals() {
2068 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2069 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2071 std::vector<MBBPriorityInfo> MBBs;
2072 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2073 MachineBasicBlock *MBB = I;
2074 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2077 std::sort(MBBs.begin(), MBBs.end(), MBBPriorityCompare(JoinSplitEdges));
2079 // Coalesce intervals in MBB priority order.
2080 unsigned CurrDepth = UINT_MAX;
2081 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2082 // Try coalescing the collected local copies for deeper loops.
2083 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth)
2085 copyCoalesceInMBB(MBBs[i].MBB);
2089 // Joining intervals can allow other intervals to be joined. Iteratively join
2090 // until we make no progress.
2091 while (copyCoalesceWorkList(WorkList))
2095 void RegisterCoalescer::releaseMemory() {
2096 ErasedInstrs.clear();
2099 InflateRegs.clear();
2102 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2104 MRI = &fn.getRegInfo();
2105 TM = &fn.getTarget();
2106 TRI = TM->getRegisterInfo();
2107 TII = TM->getInstrInfo();
2108 LIS = &getAnalysis<LiveIntervals>();
2109 LDV = &getAnalysis<LiveDebugVariables>();
2110 AA = &getAnalysis<AliasAnalysis>();
2111 Loops = &getAnalysis<MachineLoopInfo>();
2113 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2114 if (EnableGlobalCopies == cl::BOU_UNSET)
2115 JoinGlobalCopies = ST.enableMachineScheduler();
2117 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2119 if (EnableJoinSplits == cl::BOU_UNSET)
2120 JoinSplitEdges = ST.enableMachineScheduler();
2122 JoinSplitEdges = (EnableJoinSplits == cl::BOU_TRUE);
2124 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2125 << "********** Function: " << MF->getName() << '\n');
2127 if (VerifyCoalescing)
2128 MF->verify(this, "Before register coalescing");
2130 RegClassInfo.runOnMachineFunction(fn);
2132 // Join (coalesce) intervals if requested.
2136 // After deleting a lot of copies, register classes may be less constrained.
2137 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2139 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2140 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2142 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2143 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2144 unsigned Reg = InflateRegs[i];
2145 if (MRI->reg_nodbg_empty(Reg))
2147 if (MRI->recomputeRegClass(Reg, *TM)) {
2148 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2149 << MRI->getRegClass(Reg)->getName() << '\n');
2156 if (VerifyCoalescing)
2157 MF->verify(this, "After register coalescing");
2161 /// print - Implement the dump method.
2162 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {