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"
52 STATISTIC(numJoins , "Number of interval joins performed");
53 STATISTIC(numCrossRCs , "Number of cross class joins performed");
54 STATISTIC(numCommutes , "Number of instruction commuting performed");
55 STATISTIC(numExtends , "Number of copies extended");
56 STATISTIC(NumReMats , "Number of instructions re-materialized");
57 STATISTIC(NumInflated , "Number of register classes inflated");
58 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
59 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
62 EnableJoining("join-liveintervals",
63 cl::desc("Coalesce copies (default=true)"),
66 // Temporary flag to test critical edge unsplitting.
68 EnableJoinSplits("join-splitedges",
69 cl::desc("Coalesce copies on split edges (default=false)"),
70 cl::init(false), cl::Hidden);
73 VerifyCoalescing("verify-coalescing",
74 cl::desc("Verify machine instrs before and after register coalescing"),
78 class RegisterCoalescer : public MachineFunctionPass,
79 private LiveRangeEdit::Delegate {
81 MachineRegisterInfo* MRI;
82 const TargetMachine* TM;
83 const TargetRegisterInfo* TRI;
84 const TargetInstrInfo* TII;
86 LiveDebugVariables *LDV;
87 const MachineLoopInfo* Loops;
89 RegisterClassInfo RegClassInfo;
91 /// WorkList - Copy instructions yet to be coalesced.
92 SmallVector<MachineInstr*, 8> WorkList;
94 /// ErasedInstrs - Set of instruction pointers that have been erased, and
95 /// that may be present in WorkList.
96 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
98 /// Dead instructions that are about to be deleted.
99 SmallVector<MachineInstr*, 8> DeadDefs;
101 /// Virtual registers to be considered for register class inflation.
102 SmallVector<unsigned, 8> InflateRegs;
104 /// Recursively eliminate dead defs in DeadDefs.
105 void eliminateDeadDefs();
107 /// LiveRangeEdit callback.
108 void LRE_WillEraseInstruction(MachineInstr *MI);
110 /// joinAllIntervals - join compatible live intervals
111 void joinAllIntervals();
113 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
114 /// copies that cannot yet be coalesced into WorkList.
115 void copyCoalesceInMBB(MachineBasicBlock *MBB);
117 /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
118 /// position From. Return true if any progress was made.
119 bool copyCoalesceWorkList(unsigned From = 0);
121 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
122 /// which are the src/dst of the copy instruction CopyMI. This returns
123 /// true if the copy was successfully coalesced away. If it is not
124 /// currently possible to coalesce this interval, but it may be possible if
125 /// other things get coalesced, then it returns true by reference in
127 bool joinCopy(MachineInstr *TheCopy, bool &Again);
129 /// joinIntervals - Attempt to join these two intervals. On failure, this
130 /// returns false. The output "SrcInt" will not have been modified, so we
131 /// can use this information below to update aliases.
132 bool joinIntervals(CoalescerPair &CP);
134 /// Attempt joining two virtual registers. Return true on success.
135 bool joinVirtRegs(CoalescerPair &CP);
137 /// Attempt joining with a reserved physreg.
138 bool joinReservedPhysReg(CoalescerPair &CP);
140 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
141 /// the source value number is defined by a copy from the destination reg
142 /// see if we can merge these two destination reg valno# into a single
143 /// value number, eliminating a copy.
144 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
146 /// hasOtherReachingDefs - Return true if there are definitions of IntB
147 /// other than BValNo val# that can reach uses of AValno val# of IntA.
148 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
149 VNInfo *AValNo, VNInfo *BValNo);
151 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
152 /// If the source value number is defined by a commutable instruction and
153 /// its other operand is coalesced to the copy dest register, see if we
154 /// can transform the copy into a noop by commuting the definition.
155 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
157 /// reMaterializeTrivialDef - If the source of a copy is defined by a
158 /// trivial computation, replace the copy by rematerialize the definition.
159 bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
160 MachineInstr *CopyMI);
162 /// canJoinPhys - Return true if a physreg copy should be joined.
163 bool canJoinPhys(CoalescerPair &CP);
165 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
166 /// update the subregister number if it is not zero. If DstReg is a
167 /// physical register and the existing subregister number of the def / use
168 /// being updated is not zero, make sure to set it to the correct physical
170 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
172 /// eliminateUndefCopy - Handle copies of undef values.
173 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
176 static char ID; // Class identification, replacement for typeinfo
177 RegisterCoalescer() : MachineFunctionPass(ID) {
178 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
181 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
183 virtual void releaseMemory();
185 /// runOnMachineFunction - pass entry point
186 virtual bool runOnMachineFunction(MachineFunction&);
188 /// print - Implement the dump method.
189 virtual void print(raw_ostream &O, const Module* = 0) const;
191 } /// end anonymous namespace
193 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
195 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
196 "Simple Register Coalescing", false, false)
197 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
198 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
199 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
200 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
201 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
202 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
203 "Simple Register Coalescing", false, false)
205 char RegisterCoalescer::ID = 0;
207 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
208 unsigned &Src, unsigned &Dst,
209 unsigned &SrcSub, unsigned &DstSub) {
211 Dst = MI->getOperand(0).getReg();
212 DstSub = MI->getOperand(0).getSubReg();
213 Src = MI->getOperand(1).getReg();
214 SrcSub = MI->getOperand(1).getSubReg();
215 } else if (MI->isSubregToReg()) {
216 Dst = MI->getOperand(0).getReg();
217 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
218 MI->getOperand(3).getImm());
219 Src = MI->getOperand(2).getReg();
220 SrcSub = MI->getOperand(2).getSubReg();
226 // Return true if this block should be vacated by the coalescer to eliminate
227 // branches. The important cases to handle in the coalescer are critical edges
228 // split during phi elimination which contain only copies. Simple blocks that
229 // contain non-branches should also be vacated, but this can be handled by an
230 // earlier pass similar to early if-conversion.
231 static bool isSplitEdge(const MachineBasicBlock *MBB) {
232 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
235 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
237 if (MII->isCopyLike())
239 if (MII->isUnconditionalBranch())
246 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
250 Flipped = CrossClass = false;
252 unsigned Src, Dst, SrcSub, DstSub;
253 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
255 Partial = SrcSub || DstSub;
257 // If one register is a physreg, it must be Dst.
258 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
259 if (TargetRegisterInfo::isPhysicalRegister(Dst))
262 std::swap(SrcSub, DstSub);
266 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
268 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
269 // Eliminate DstSub on a physreg.
271 Dst = TRI.getSubReg(Dst, DstSub);
272 if (!Dst) return false;
276 // Eliminate SrcSub by picking a corresponding Dst superregister.
278 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
279 if (!Dst) return false;
281 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
285 // Both registers are virtual.
286 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
287 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
289 // Both registers have subreg indices.
290 if (SrcSub && DstSub) {
291 // Copies between different sub-registers are never coalescable.
292 if (Src == Dst && SrcSub != DstSub)
295 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
300 // SrcReg will be merged with a sub-register of DstReg.
302 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
304 // DstReg will be merged with a sub-register of SrcReg.
306 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
308 // This is a straight copy without sub-registers.
309 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
312 // The combined constraint may be impossible to satisfy.
316 // Prefer SrcReg to be a sub-register of DstReg.
317 // FIXME: Coalescer should support subregs symmetrically.
318 if (DstIdx && !SrcIdx) {
320 std::swap(SrcIdx, DstIdx);
324 CrossClass = NewRC != DstRC || NewRC != SrcRC;
326 // Check our invariants
327 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
328 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
329 "Cannot have a physical SubIdx");
335 bool CoalescerPair::flip() {
336 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
338 std::swap(SrcReg, DstReg);
339 std::swap(SrcIdx, DstIdx);
344 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
347 unsigned Src, Dst, SrcSub, DstSub;
348 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
351 // Find the virtual register that is SrcReg.
354 std::swap(SrcSub, DstSub);
355 } else if (Src != SrcReg) {
359 // Now check that Dst matches DstReg.
360 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
361 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
363 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
364 // DstSub could be set for a physreg from INSERT_SUBREG.
366 Dst = TRI.getSubReg(Dst, DstSub);
369 return DstReg == Dst;
370 // This is a partial register copy. Check that the parts match.
371 return TRI.getSubReg(DstReg, SrcSub) == Dst;
373 // DstReg is virtual.
376 // Registers match, do the subregisters line up?
377 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
378 TRI.composeSubRegIndices(DstIdx, DstSub);
382 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
383 AU.setPreservesCFG();
384 AU.addRequired<AliasAnalysis>();
385 AU.addRequired<LiveIntervals>();
386 AU.addPreserved<LiveIntervals>();
387 AU.addRequired<LiveDebugVariables>();
388 AU.addPreserved<LiveDebugVariables>();
389 AU.addPreserved<SlotIndexes>();
390 AU.addRequired<MachineLoopInfo>();
391 AU.addPreserved<MachineLoopInfo>();
392 AU.addPreservedID(MachineDominatorsID);
393 MachineFunctionPass::getAnalysisUsage(AU);
396 void RegisterCoalescer::eliminateDeadDefs() {
397 SmallVector<LiveInterval*, 8> NewRegs;
398 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
401 // Callback from eliminateDeadDefs().
402 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
403 // MI may be in WorkList. Make sure we don't visit it.
404 ErasedInstrs.insert(MI);
407 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
408 /// being the source and IntB being the dest, thus this defines a value number
409 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
410 /// see if we can merge these two pieces of B into a single value number,
411 /// eliminating a copy. For example:
415 /// B1 = A3 <- this copy
417 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
418 /// value number to be replaced with B0 (which simplifies the B liveinterval).
420 /// This returns true if an interval was modified.
422 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
423 MachineInstr *CopyMI) {
424 assert(!CP.isPartial() && "This doesn't work for partial copies.");
425 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
428 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
430 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
431 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
433 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
434 // the example above.
435 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
436 if (BLR == IntB.end()) return false;
437 VNInfo *BValNo = BLR->valno;
439 // Get the location that B is defined at. Two options: either this value has
440 // an unknown definition point or it is defined at CopyIdx. If unknown, we
442 if (BValNo->def != CopyIdx) return false;
444 // AValNo is the value number in A that defines the copy, A3 in the example.
445 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
446 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
447 // The live range might not exist after fun with physreg coalescing.
448 if (ALR == IntA.end()) return false;
449 VNInfo *AValNo = ALR->valno;
451 // If AValNo is defined as a copy from IntB, we can potentially process this.
452 // Get the instruction that defines this value number.
453 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
454 // Don't allow any partial copies, even if isCoalescable() allows them.
455 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
458 // Get the LiveRange in IntB that this value number starts with.
459 LiveInterval::iterator ValLR =
460 IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
461 if (ValLR == IntB.end())
464 // Make sure that the end of the live range is inside the same block as
466 MachineInstr *ValLREndInst =
467 LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
468 if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
471 // Okay, we now know that ValLR ends in the same block that the CopyMI
472 // live-range starts. If there are no intervening live ranges between them in
473 // IntB, we can merge them.
474 if (ValLR+1 != BLR) return false;
476 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
478 SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
479 // We are about to delete CopyMI, so need to remove it as the 'instruction
480 // that defines this value #'. Update the valnum with the new defining
482 BValNo->def = FillerStart;
484 // Okay, we can merge them. We need to insert a new liverange:
485 // [ValLR.end, BLR.begin) of either value number, then we merge the
486 // two value numbers.
487 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
489 // Okay, merge "B1" into the same value number as "B0".
490 if (BValNo != ValLR->valno)
491 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
492 DEBUG(dbgs() << " result = " << IntB << '\n');
494 // If the source instruction was killing the source register before the
495 // merge, unset the isKill marker given the live range has been extended.
496 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
498 ValLREndInst->getOperand(UIdx).setIsKill(false);
501 // Rewrite the copy. If the copy instruction was killing the destination
502 // register before the merge, find the last use and trim the live range. That
503 // will also add the isKill marker.
504 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
505 if (ALR->end == CopyIdx)
506 LIS->shrinkToUses(&IntA);
512 /// hasOtherReachingDefs - Return true if there are definitions of IntB
513 /// other than BValNo val# that can reach uses of AValno val# of IntA.
514 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
518 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
520 if (LIS->hasPHIKill(IntA, AValNo))
523 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
525 if (AI->valno != AValNo) continue;
526 LiveInterval::Ranges::iterator BI =
527 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
528 if (BI != IntB.ranges.begin())
530 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
531 if (BI->valno == BValNo)
533 if (BI->start <= AI->start && BI->end > AI->start)
535 if (BI->start > AI->start && BI->start < AI->end)
542 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
543 /// IntA being the source and IntB being the dest, thus this defines a value
544 /// number in IntB. If the source value number (in IntA) is defined by a
545 /// commutable instruction and its other operand is coalesced to the copy dest
546 /// register, see if we can transform the copy into a noop by commuting the
547 /// definition. For example,
549 /// A3 = op A2 B0<kill>
551 /// B1 = A3 <- this copy
553 /// = op A3 <- more uses
557 /// B2 = op B0 A2<kill>
559 /// B1 = B2 <- now an identify copy
561 /// = op B2 <- more uses
563 /// This returns true if an interval was modified.
565 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
566 MachineInstr *CopyMI) {
567 assert (!CP.isPhys());
569 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
572 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
574 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
576 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
577 // the example above.
578 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
579 if (!BValNo || BValNo->def != CopyIdx)
582 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
584 // AValNo is the value number in A that defines the copy, A3 in the example.
585 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
586 assert(AValNo && "COPY source not live");
587 if (AValNo->isPHIDef() || AValNo->isUnused())
589 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
592 if (!DefMI->isCommutable())
594 // If DefMI is a two-address instruction then commuting it will change the
595 // destination register.
596 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
597 assert(DefIdx != -1);
599 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
601 unsigned Op1, Op2, NewDstIdx;
602 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
606 else if (Op2 == UseOpIdx)
611 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
612 unsigned NewReg = NewDstMO.getReg();
613 if (NewReg != IntB.reg || !LiveRangeQuery(IntB, AValNo->def).isKill())
616 // Make sure there are no other definitions of IntB that would reach the
617 // uses which the new definition can reach.
618 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
621 // If some of the uses of IntA.reg is already coalesced away, return false.
622 // It's not possible to determine whether it's safe to perform the coalescing.
623 for (MachineRegisterInfo::use_nodbg_iterator UI =
624 MRI->use_nodbg_begin(IntA.reg),
625 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
626 MachineInstr *UseMI = &*UI;
627 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
628 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
629 if (ULR == IntA.end() || ULR->valno != AValNo)
631 // If this use is tied to a def, we can't rewrite the register.
632 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
636 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
639 // At this point we have decided that it is legal to do this
640 // transformation. Start by commuting the instruction.
641 MachineBasicBlock *MBB = DefMI->getParent();
642 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
645 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
646 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
647 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
649 if (NewMI != DefMI) {
650 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
651 MachineBasicBlock::iterator Pos = DefMI;
652 MBB->insert(Pos, NewMI);
655 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
656 NewMI->getOperand(OpIdx).setIsKill();
658 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
667 // Update uses of IntA of the specific Val# with IntB.
668 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
669 UE = MRI->use_end(); UI != UE;) {
670 MachineOperand &UseMO = UI.getOperand();
671 MachineInstr *UseMI = &*UI;
673 if (UseMI->isDebugValue()) {
674 // FIXME These don't have an instruction index. Not clear we have enough
675 // info to decide whether to do this replacement or not. For now do it.
676 UseMO.setReg(NewReg);
679 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
680 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
681 if (ULR == IntA.end() || ULR->valno != AValNo)
683 // Kill flags are no longer accurate. They are recomputed after RA.
684 UseMO.setIsKill(false);
685 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
686 UseMO.substPhysReg(NewReg, *TRI);
688 UseMO.setReg(NewReg);
691 if (!UseMI->isCopy())
693 if (UseMI->getOperand(0).getReg() != IntB.reg ||
694 UseMI->getOperand(0).getSubReg())
697 // This copy will become a noop. If it's defining a new val#, merge it into
699 SlotIndex DefIdx = UseIdx.getRegSlot();
700 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
703 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
704 assert(DVNI->def == DefIdx);
705 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
706 ErasedInstrs.insert(UseMI);
707 LIS->RemoveMachineInstrFromMaps(UseMI);
708 UseMI->eraseFromParent();
711 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
713 VNInfo *ValNo = BValNo;
714 ValNo->def = AValNo->def;
715 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
717 if (AI->valno != AValNo) continue;
718 IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
720 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
722 IntA.removeValNo(AValNo);
723 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
728 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
729 /// computation, replace the copy by rematerialize the definition.
730 bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
732 MachineInstr *CopyMI) {
733 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
734 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
735 assert(SrcLR != SrcInt.end() && "Live range not found!");
736 VNInfo *ValNo = SrcLR->valno;
737 if (ValNo->isPHIDef() || ValNo->isUnused())
739 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
742 assert(DefMI && "Defining instruction disappeared");
743 if (!DefMI->isAsCheapAsAMove())
745 if (!TII->isTriviallyReMaterializable(DefMI, AA))
747 bool SawStore = false;
748 if (!DefMI->isSafeToMove(TII, AA, SawStore))
750 const MCInstrDesc &MCID = DefMI->getDesc();
751 if (MCID.getNumDefs() != 1)
753 if (!DefMI->isImplicitDef()) {
754 // Make sure the copy destination register class fits the instruction
755 // definition register class. The mismatch can happen as a result of earlier
756 // extract_subreg, insert_subreg, subreg_to_reg coalescing.
757 const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
758 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
759 if (MRI->getRegClass(DstReg) != RC)
761 } else if (!RC->contains(DstReg))
765 MachineBasicBlock *MBB = CopyMI->getParent();
766 MachineBasicBlock::iterator MII =
767 llvm::next(MachineBasicBlock::iterator(CopyMI));
768 TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
769 MachineInstr *NewMI = prior(MII);
771 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
772 // We need to remember these so we can add intervals once we insert
773 // NewMI into SlotIndexes.
774 SmallVector<unsigned, 4> NewMIImplDefs;
775 for (unsigned i = NewMI->getDesc().getNumOperands(),
776 e = NewMI->getNumOperands(); i != e; ++i) {
777 MachineOperand &MO = NewMI->getOperand(i);
779 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
780 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
781 NewMIImplDefs.push_back(MO.getReg());
785 // CopyMI may have implicit operands, transfer them over to the newly
786 // rematerialized instruction. And update implicit def interval valnos.
787 for (unsigned i = CopyMI->getDesc().getNumOperands(),
788 e = CopyMI->getNumOperands(); i != e; ++i) {
789 MachineOperand &MO = CopyMI->getOperand(i);
791 assert(MO.isImplicit() && "No explicit operands after implict operands.");
792 // Discard VReg implicit defs.
793 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
794 NewMI->addOperand(MO);
799 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
801 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
802 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
803 unsigned Reg = NewMIImplDefs[i];
804 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
805 if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
806 LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
809 CopyMI->eraseFromParent();
810 ErasedInstrs.insert(CopyMI);
811 DEBUG(dbgs() << "Remat: " << *NewMI);
814 // The source interval can become smaller because we removed a use.
815 LIS->shrinkToUses(&SrcInt, &DeadDefs);
816 if (!DeadDefs.empty())
822 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
823 /// values, it only removes local variables. When we have a copy like:
825 /// %vreg1 = COPY %vreg2<undef>
827 /// We delete the copy and remove the corresponding value number from %vreg1.
828 /// Any uses of that value number are marked as <undef>.
829 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
830 const CoalescerPair &CP) {
831 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
832 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
833 if (SrcInt->liveAt(Idx))
835 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
836 if (DstInt->liveAt(Idx))
839 // No intervals are live-in to CopyMI - it is undef.
844 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
845 assert(DeadVNI && "No value defined in DstInt");
846 DstInt->removeValNo(DeadVNI);
848 // Find new undef uses.
849 for (MachineRegisterInfo::reg_nodbg_iterator
850 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
852 MachineOperand &MO = I.getOperand();
853 if (MO.isDef() || MO.isUndef())
855 MachineInstr *MI = MO.getParent();
856 SlotIndex Idx = LIS->getInstructionIndex(MI);
857 if (DstInt->liveAt(Idx))
860 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
865 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
866 /// update the subregister number if it is not zero. If DstReg is a
867 /// physical register and the existing subregister number of the def / use
868 /// being updated is not zero, make sure to set it to the correct physical
870 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
873 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
874 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
876 // Update LiveDebugVariables.
877 LDV->renameRegister(SrcReg, DstReg, SubIdx);
879 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
880 MachineInstr *UseMI = I.skipInstruction();) {
881 SmallVector<unsigned,8> Ops;
883 tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
885 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
886 // because SrcReg is a sub-register.
887 if (DstInt && !Reads && SubIdx)
888 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
890 // Replace SrcReg with DstReg in all UseMI operands.
891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
892 MachineOperand &MO = UseMI->getOperand(Ops[i]);
894 // Adjust <undef> flags in case of sub-register joins. We don't want to
895 // turn a full def into a read-modify-write sub-register def and vice
897 if (SubIdx && MO.isDef())
898 MO.setIsUndef(!Reads);
901 MO.substPhysReg(DstReg, *TRI);
903 MO.substVirtReg(DstReg, SubIdx, *TRI);
907 dbgs() << "\t\tupdated: ";
908 if (!UseMI->isDebugValue())
909 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
915 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
916 bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
917 /// Always join simple intervals that are defined by a single copy from a
918 /// reserved register. This doesn't increase register pressure, so it is
919 /// always beneficial.
920 if (!MRI->isReserved(CP.getDstReg())) {
921 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
925 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
926 if (CP.isFlipped() && JoinVInt.containsOneValue())
929 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
933 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
934 /// which are the src/dst of the copy instruction CopyMI. This returns true
935 /// if the copy was successfully coalesced away. If it is not currently
936 /// possible to coalesce this interval, but it may be possible if other
937 /// things get coalesced, then it returns true by reference in 'Again'.
938 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
941 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
943 CoalescerPair CP(*TRI);
944 if (!CP.setRegisters(CopyMI)) {
945 DEBUG(dbgs() << "\tNot coalescable.\n");
949 // Dead code elimination. This really should be handled by MachineDCE, but
950 // sometimes dead copies slip through, and we can't generate invalid live
952 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
953 DEBUG(dbgs() << "\tCopy is dead.\n");
954 DeadDefs.push_back(CopyMI);
960 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
961 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
962 LIS->RemoveMachineInstrFromMaps(CopyMI);
963 CopyMI->eraseFromParent();
964 return false; // Not coalescable.
967 // Coalesced copies are normally removed immediately, but transformations
968 // like removeCopyByCommutingDef() can inadvertently create identity copies.
969 // When that happens, just join the values and remove the copy.
970 if (CP.getSrcReg() == CP.getDstReg()) {
971 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
972 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
973 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
974 if (VNInfo *DefVNI = LRQ.valueDefined()) {
975 VNInfo *ReadVNI = LRQ.valueIn();
976 assert(ReadVNI && "No value before copy and no <undef> flag.");
977 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
978 LI.MergeValueNumberInto(DefVNI, ReadVNI);
979 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
981 LIS->RemoveMachineInstrFromMaps(CopyMI);
982 CopyMI->eraseFromParent();
988 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
989 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
991 if (!canJoinPhys(CP)) {
992 // Before giving up coalescing, if definition of source is defined by
993 // trivial computation, try rematerializing it.
994 if (!CP.isFlipped() &&
995 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
996 CP.getDstReg(), CopyMI))
1002 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1004 if (CP.getDstIdx() && CP.getSrcIdx())
1005 dbgs() << PrintReg(CP.getDstReg()) << " in "
1006 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1007 << PrintReg(CP.getSrcReg()) << " in "
1008 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1010 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1011 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1014 // When possible, let DstReg be the larger interval.
1015 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1016 LIS->getInterval(CP.getDstReg()).ranges.size())
1020 // Okay, attempt to join these two intervals. On failure, this returns false.
1021 // Otherwise, if one of the intervals being joined is a physreg, this method
1022 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1023 // been modified, so we can use this information below to update aliases.
1024 if (!joinIntervals(CP)) {
1025 // Coalescing failed.
1027 // If definition of source is defined by trivial computation, try
1028 // rematerializing it.
1029 if (!CP.isFlipped() &&
1030 reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1031 CP.getDstReg(), CopyMI))
1034 // If we can eliminate the copy without merging the live ranges, do so now.
1035 if (!CP.isPartial() && !CP.isPhys()) {
1036 if (adjustCopiesBackFrom(CP, CopyMI) ||
1037 removeCopyByCommutingDef(CP, CopyMI)) {
1038 LIS->RemoveMachineInstrFromMaps(CopyMI);
1039 CopyMI->eraseFromParent();
1040 DEBUG(dbgs() << "\tTrivial!\n");
1045 // Otherwise, we are unable to join the intervals.
1046 DEBUG(dbgs() << "\tInterference!\n");
1047 Again = true; // May be possible to coalesce later.
1051 // Coalescing to a virtual register that is of a sub-register class of the
1052 // other. Make sure the resulting register is set to the right register class.
1053 if (CP.isCrossClass()) {
1055 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1058 // Removing sub-register copies can ease the register class constraints.
1059 // Make sure we attempt to inflate the register class of DstReg.
1060 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1061 InflateRegs.push_back(CP.getDstReg());
1063 // CopyMI has been erased by joinIntervals at this point. Remove it from
1064 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1065 // to the work list. This keeps ErasedInstrs from growing needlessly.
1066 ErasedInstrs.erase(CopyMI);
1068 // Rewrite all SrcReg operands to DstReg.
1069 // Also update DstReg operands to include DstIdx if it is set.
1071 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1072 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1074 // SrcReg is guaranteed to be the register whose live interval that is
1076 LIS->removeInterval(CP.getSrcReg());
1078 // Update regalloc hint.
1079 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1082 dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1084 dbgs() << LIS->getInterval(CP.getDstReg());
1092 /// Attempt joining with a reserved physreg.
1093 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1094 assert(CP.isPhys() && "Must be a physreg copy");
1095 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1096 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1097 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1100 assert(CP.isFlipped() && RHS.containsOneValue() &&
1101 "Invalid join with reserved register");
1103 // Optimization for reserved registers like ESP. We can only merge with a
1104 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1105 // The live range of the reserved register will look like a set of dead defs
1106 // - we don't properly track the live range of reserved registers.
1108 // Deny any overlapping intervals. This depends on all the reserved
1109 // register live ranges to look like dead defs.
1110 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1111 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1112 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1116 // Skip any value computations, we are not adding new values to the
1117 // reserved register. Also skip merging the live ranges, the reserved
1118 // register live range doesn't need to be accurate as long as all the
1121 // Delete the identity copy.
1122 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1123 LIS->RemoveMachineInstrFromMaps(CopyMI);
1124 CopyMI->eraseFromParent();
1126 // We don't track kills for reserved registers.
1127 MRI->clearKillFlags(CP.getSrcReg());
1132 //===----------------------------------------------------------------------===//
1133 // Interference checking and interval joining
1134 //===----------------------------------------------------------------------===//
1136 // In the easiest case, the two live ranges being joined are disjoint, and
1137 // there is no interference to consider. It is quite common, though, to have
1138 // overlapping live ranges, and we need to check if the interference can be
1141 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1142 // This means that two SSA values overlap if and only if the def of one value
1143 // is contained in the live range of the other value. As a special case, the
1144 // overlapping values can be defined at the same index.
1146 // The interference from an overlapping def can be resolved in these cases:
1148 // 1. Coalescable copies. The value is defined by a copy that would become an
1149 // identity copy after joining SrcReg and DstReg. The copy instruction will
1150 // be removed, and the value will be merged with the source value.
1152 // There can be several copies back and forth, causing many values to be
1153 // merged into one. We compute a list of ultimate values in the joined live
1154 // range as well as a mappings from the old value numbers.
1156 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1157 // predecessors have a live out value. It doesn't cause real interference,
1158 // and can be merged into the value it overlaps. Like a coalescable copy, it
1159 // can be erased after joining.
1161 // 3. Copy of external value. The overlapping def may be a copy of a value that
1162 // is already in the other register. This is like a coalescable copy, but
1163 // the live range of the source register must be trimmed after erasing the
1164 // copy instruction:
1167 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1169 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1170 // defining one lane at a time:
1172 // %dst:ssub0<def,read-undef> = FOO
1174 // %dst:ssub1<def> = COPY %src
1176 // The live range of %src overlaps the %dst value defined by FOO, but
1177 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1178 // which was undef anyway.
1180 // The value mapping is more complicated in this case. The final live range
1181 // will have different value numbers for both FOO and BAR, but there is no
1182 // simple mapping from old to new values. It may even be necessary to add
1185 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1186 // is live, but never read. This can happen because we don't compute
1187 // individual live ranges per lane.
1191 // %dst:ssub1<def> = COPY %src
1193 // This kind of interference is only resolved locally. If the clobbered
1194 // lane value escapes the block, the join is aborted.
1197 /// Track information about values in a single virtual register about to be
1198 /// joined. Objects of this class are always created in pairs - one for each
1199 /// side of the CoalescerPair.
1203 // Location of this register in the final joined register.
1204 // Either CP.DstIdx or CP.SrcIdx.
1207 // Values that will be present in the final live range.
1208 SmallVectorImpl<VNInfo*> &NewVNInfo;
1210 const CoalescerPair &CP;
1212 SlotIndexes *Indexes;
1213 const TargetRegisterInfo *TRI;
1215 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1216 // This is suitable for passing to LiveInterval::join().
1217 SmallVector<int, 8> Assignments;
1219 // Conflict resolution for overlapping values.
1220 enum ConflictResolution {
1221 // No overlap, simply keep this value.
1224 // Merge this value into OtherVNI and erase the defining instruction.
1225 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1229 // Merge this value into OtherVNI but keep the defining instruction.
1230 // This is for the special case where OtherVNI is defined by the same
1234 // Keep this value, and have it replace OtherVNI where possible. This
1235 // complicates value mapping since OtherVNI maps to two different values
1236 // before and after this def.
1237 // Used when clobbering undefined or dead lanes.
1240 // Unresolved conflict. Visit later when all values have been mapped.
1243 // Unresolvable conflict. Abort the join.
1247 // Per-value info for LI. The lane bit masks are all relative to the final
1248 // joined register, so they can be compared directly between SrcReg and
1251 ConflictResolution Resolution;
1253 // Lanes written by this def, 0 for unanalyzed values.
1254 unsigned WriteLanes;
1256 // Lanes with defined values in this register. Other lanes are undef and
1258 unsigned ValidLanes;
1260 // Value in LI being redefined by this def.
1263 // Value in the other live range that overlaps this def, if any.
1266 // Is this value an IMPLICIT_DEF?
1269 // True when the live range of this value will be pruned because of an
1270 // overlapping CR_Replace value in the other live range.
1273 // True once Pruned above has been computed.
1274 bool PrunedComputed;
1276 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1277 RedefVNI(0), OtherVNI(0), IsImplicitDef(false), Pruned(false),
1278 PrunedComputed(false) {}
1280 bool isAnalyzed() const { return WriteLanes != 0; }
1283 // One entry per value number in LI.
1284 SmallVector<Val, 8> Vals;
1286 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1287 VNInfo *stripCopies(VNInfo *VNI);
1288 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1289 void computeAssignment(unsigned ValNo, JoinVals &Other);
1290 bool taintExtent(unsigned, unsigned, JoinVals&,
1291 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1292 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1293 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1296 JoinVals(LiveInterval &li, unsigned subIdx,
1297 SmallVectorImpl<VNInfo*> &newVNInfo,
1298 const CoalescerPair &cp,
1300 const TargetRegisterInfo *tri)
1301 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1302 Indexes(LIS->getSlotIndexes()), TRI(tri),
1303 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1306 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1307 /// Returns false if any conflicts were impossible to resolve.
1308 bool mapValues(JoinVals &Other);
1310 /// Try to resolve conflicts that require all values to be mapped.
1311 /// Returns false if any conflicts were impossible to resolve.
1312 bool resolveConflicts(JoinVals &Other);
1314 /// Prune the live range of values in Other.LI where they would conflict with
1315 /// CR_Replace values in LI. Collect end points for restoring the live range
1317 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1319 /// Erase any machine instructions that have been coalesced away.
1320 /// Add erased instructions to ErasedInstrs.
1321 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1322 /// the erased instrs.
1323 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1324 SmallVectorImpl<unsigned> &ShrinkRegs);
1326 /// Get the value assignments suitable for passing to LiveInterval::join.
1327 const int *getAssignments() const { return Assignments.data(); }
1329 } // end anonymous namespace
1331 /// Compute the bitmask of lanes actually written by DefMI.
1332 /// Set Redef if there are any partial register definitions that depend on the
1333 /// previous value of the register.
1334 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1336 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1337 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1339 L |= TRI->getSubRegIndexLaneMask(
1340 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1347 /// Find the ultimate value that VNI was copied from.
1348 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1349 while (!VNI->isPHIDef()) {
1350 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1351 assert(MI && "No defining instruction");
1352 if (!MI->isFullCopy())
1354 unsigned Reg = MI->getOperand(1).getReg();
1355 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1357 LiveRangeQuery LRQ(LIS->getInterval(Reg), VNI->def);
1360 VNI = LRQ.valueIn();
1365 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1366 /// Return a conflict resolution when possible, but leave the hard cases as
1368 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1369 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1370 /// The recursion always goes upwards in the dominator tree, making loops
1372 JoinVals::ConflictResolution
1373 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1374 Val &V = Vals[ValNo];
1375 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1376 VNInfo *VNI = LI.getValNumInfo(ValNo);
1377 if (VNI->isUnused()) {
1382 // Get the instruction defining this value, compute the lanes written.
1383 const MachineInstr *DefMI = 0;
1384 if (VNI->isPHIDef()) {
1385 // Conservatively assume that all lanes in a PHI are valid.
1386 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1388 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1390 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1392 // If this is a read-modify-write instruction, there may be more valid
1393 // lanes than the ones written by this instruction.
1394 // This only covers partial redef operands. DefMI may have normal use
1395 // operands reading the register. They don't contribute valid lanes.
1397 // This adds ssub1 to the set of valid lanes in %src:
1399 // %src:ssub1<def> = FOO
1401 // This leaves only ssub1 valid, making any other lanes undef:
1403 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1405 // The <read-undef> flag on the def operand means that old lane values are
1408 V.RedefVNI = LiveRangeQuery(LI, VNI->def).valueIn();
1409 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1410 computeAssignment(V.RedefVNI->id, Other);
1411 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1414 // An IMPLICIT_DEF writes undef values.
1415 if (DefMI->isImplicitDef()) {
1416 V.IsImplicitDef = true;
1417 V.ValidLanes &= ~V.WriteLanes;
1421 // Find the value in Other that overlaps VNI->def, if any.
1422 LiveRangeQuery OtherLRQ(Other.LI, VNI->def);
1424 // It is possible that both values are defined by the same instruction, or
1425 // the values are PHIs defined in the same block. When that happens, the two
1426 // values should be merged into one, but not into any preceding value.
1427 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1428 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1429 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1431 // One value stays, the other is merged. Keep the earlier one, or the first
1433 if (OtherVNI->def < VNI->def)
1434 Other.computeAssignment(OtherVNI->id, *this);
1435 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1436 // This is an early-clobber def overlapping a live-in value in the other
1437 // register. Not mergeable.
1438 V.OtherVNI = OtherLRQ.valueIn();
1439 return CR_Impossible;
1441 V.OtherVNI = OtherVNI;
1442 Val &OtherV = Other.Vals[OtherVNI->id];
1443 // Keep this value, check for conflicts when analyzing OtherVNI.
1444 if (!OtherV.isAnalyzed())
1446 // Both sides have been analyzed now.
1447 // Allow overlapping PHI values. Any real interference would show up in a
1448 // predecessor, the PHI itself can't introduce any conflicts.
1449 if (VNI->isPHIDef())
1451 if (V.ValidLanes & OtherV.ValidLanes)
1452 // Overlapping lanes can't be resolved.
1453 return CR_Impossible;
1458 // No simultaneous def. Is Other live at the def?
1459 V.OtherVNI = OtherLRQ.valueIn();
1461 // No overlap, no conflict.
1464 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1466 // We have overlapping values, or possibly a kill of Other.
1467 // Recursively compute assignments up the dominator tree.
1468 Other.computeAssignment(V.OtherVNI->id, *this);
1469 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1471 // Allow overlapping PHI values. Any real interference would show up in a
1472 // predecessor, the PHI itself can't introduce any conflicts.
1473 if (VNI->isPHIDef())
1476 // Check for simple erasable conflicts.
1477 if (DefMI->isImplicitDef())
1480 // Include the non-conflict where DefMI is a coalescable copy that kills
1481 // OtherVNI. We still want the copy erased and value numbers merged.
1482 if (CP.isCoalescable(DefMI)) {
1483 // Some of the lanes copied from OtherVNI may be undef, making them undef
1485 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1489 // This may not be a real conflict if DefMI simply kills Other and defines
1491 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1494 // Handle the case where VNI and OtherVNI can be proven to be identical:
1496 // %other = COPY %ext
1497 // %this = COPY %ext <-- Erase this copy
1499 if (DefMI->isFullCopy() && !CP.isPartial() &&
1500 stripCopies(VNI) == stripCopies(V.OtherVNI))
1503 // If the lanes written by this instruction were all undef in OtherVNI, it is
1504 // still safe to join the live ranges. This can't be done with a simple value
1505 // mapping, though - OtherVNI will map to multiple values:
1507 // 1 %dst:ssub0 = FOO <-- OtherVNI
1508 // 2 %src = BAR <-- VNI
1509 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1511 // 5 QUUX %src<kill>
1513 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1514 // handles this complex value mapping.
1515 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1518 // If the other live range is killed by DefMI and the live ranges are still
1519 // overlapping, it must be because we're looking at an early clobber def:
1521 // %dst<def,early-clobber> = ASM %src<kill>
1523 // In this case, it is illegal to merge the two live ranges since the early
1524 // clobber def would clobber %src before it was read.
1525 if (OtherLRQ.isKill()) {
1526 // This case where the def doesn't overlap the kill is handled above.
1527 assert(VNI->def.isEarlyClobber() &&
1528 "Only early clobber defs can overlap a kill");
1529 return CR_Impossible;
1532 // VNI is clobbering live lanes in OtherVNI, but there is still the
1533 // possibility that no instructions actually read the clobbered lanes.
1534 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1535 // Otherwise Other.LI wouldn't be live here.
1536 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1537 return CR_Impossible;
1539 // We need to verify that no instructions are reading the clobbered lanes. To
1540 // save compile time, we'll only check that locally. Don't allow the tainted
1541 // value to escape the basic block.
1542 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1543 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1544 return CR_Impossible;
1546 // There are still some things that could go wrong besides clobbered lanes
1547 // being read, for example OtherVNI may be only partially redefined in MBB,
1548 // and some clobbered lanes could escape the block. Save this analysis for
1549 // resolveConflicts() when all values have been mapped. We need to know
1550 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1551 // that now - the recursive analyzeValue() calls must go upwards in the
1553 return CR_Unresolved;
1556 /// Compute the value assignment for ValNo in LI.
1557 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1559 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1560 Val &V = Vals[ValNo];
1561 if (V.isAnalyzed()) {
1562 // Recursion should always move up the dominator tree, so ValNo is not
1563 // supposed to reappear before it has been assigned.
1564 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1567 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1570 // Merge this ValNo into OtherVNI.
1571 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1572 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1573 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1574 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1575 << LI.getValNumInfo(ValNo)->def << " into "
1576 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1577 << V.OtherVNI->def << " --> @"
1578 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1582 // The other value is going to be pruned if this join is successful.
1583 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1584 Other.Vals[V.OtherVNI->id].Pruned = true;
1587 // This value number needs to go in the final joined live range.
1588 Assignments[ValNo] = NewVNInfo.size();
1589 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1594 bool JoinVals::mapValues(JoinVals &Other) {
1595 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1596 computeAssignment(i, Other);
1597 if (Vals[i].Resolution == CR_Impossible) {
1598 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1599 << '@' << LI.getValNumInfo(i)->def << '\n');
1606 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1607 /// the extent of the tainted lanes in the block.
1609 /// Multiple values in Other.LI can be affected since partial redefinitions can
1610 /// preserve previously tainted lanes.
1612 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1613 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1614 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1615 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1617 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1618 /// entry to TaintedVals.
1620 /// Returns false if the tainted lanes extend beyond the basic block.
1622 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1623 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1624 VNInfo *VNI = LI.getValNumInfo(ValNo);
1625 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1626 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1628 // Scan Other.LI from VNI.def to MBBEnd.
1629 LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1630 assert(OtherI != Other.LI.end() && "No conflict?");
1632 // OtherI is pointing to a tainted value. Abort the join if the tainted
1633 // lanes escape the block.
1634 SlotIndex End = OtherI->end;
1635 if (End >= MBBEnd) {
1636 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1637 << OtherI->valno->id << '@' << OtherI->start << '\n');
1640 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1641 << OtherI->valno->id << '@' << OtherI->start
1642 << " to " << End << '\n');
1643 // A dead def is not a problem.
1646 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1648 // Check for another def in the MBB.
1649 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1652 // Lanes written by the new def are no longer tainted.
1653 const Val &OV = Other.Vals[OtherI->valno->id];
1654 TaintedLanes &= ~OV.WriteLanes;
1657 } while (TaintedLanes);
1661 /// Return true if MI uses any of the given Lanes from Reg.
1662 /// This does not include partial redefinitions of Reg.
1663 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1665 if (MI->isDebugValue())
1667 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1668 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1670 if (!MO->readsReg())
1672 if (Lanes & TRI->getSubRegIndexLaneMask(
1673 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1679 bool JoinVals::resolveConflicts(JoinVals &Other) {
1680 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1682 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1683 if (V.Resolution != CR_Unresolved)
1685 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1686 << '@' << LI.getValNumInfo(i)->def << '\n');
1688 assert(V.OtherVNI && "Inconsistent conflict resolution.");
1689 VNInfo *VNI = LI.getValNumInfo(i);
1690 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1692 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1693 // join, those lanes will be tainted with a wrong value. Get the extent of
1694 // the tainted lanes.
1695 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1696 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1697 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1698 // Tainted lanes would extend beyond the basic block.
1701 assert(!TaintExtent.empty() && "There should be at least one conflict.");
1703 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1704 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1705 MachineBasicBlock::iterator MI = MBB->begin();
1706 if (!VNI->isPHIDef()) {
1707 MI = Indexes->getInstructionFromIndex(VNI->def);
1708 // No need to check the instruction defining VNI for reads.
1711 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1712 "Interference ends on VNI->def. Should have been handled earlier");
1713 MachineInstr *LastMI =
1714 Indexes->getInstructionFromIndex(TaintExtent.front().first);
1715 assert(LastMI && "Range must end at a proper instruction");
1716 unsigned TaintNum = 0;
1718 assert(MI != MBB->end() && "Bad LastMI");
1719 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1720 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1723 // LastMI is the last instruction to use the current value.
1724 if (&*MI == LastMI) {
1725 if (++TaintNum == TaintExtent.size())
1727 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1728 assert(LastMI && "Range must end at a proper instruction");
1729 TaintedLanes = TaintExtent[TaintNum].second;
1734 // The tainted lanes are unused.
1735 V.Resolution = CR_Replace;
1741 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1745 // %src = COPY %dst <-- This value to be pruned.
1746 // %dst = COPY %src <-- This value is a copy of a pruned value.
1748 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1749 Val &V = Vals[ValNo];
1750 if (V.Pruned || V.PrunedComputed)
1753 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1756 // Follow copies up the dominator tree and check if any intermediate value
1758 V.PrunedComputed = true;
1759 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1763 void JoinVals::pruneValues(JoinVals &Other,
1764 SmallVectorImpl<SlotIndex> &EndPoints) {
1765 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1766 SlotIndex Def = LI.getValNumInfo(i)->def;
1767 switch (Vals[i].Resolution) {
1771 // This value takes precedence over the value in Other.LI.
1772 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1773 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1774 // instructions are only inserted to provide a live-out value for PHI
1775 // predecessors, so the instruction should simply go away once its value
1776 // has been replaced.
1777 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1778 bool EraseImpDef = OtherV.IsImplicitDef && OtherV.Resolution == CR_Keep;
1779 if (!Def.isBlock()) {
1780 // Remove <def,read-undef> flags. This def is now a partial redef.
1781 // Also remove <def,dead> flags since the joined live range will
1782 // continue past this instruction.
1783 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1785 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1786 MO->setIsUndef(EraseImpDef);
1787 MO->setIsDead(false);
1789 // This value will reach instructions below, but we need to make sure
1790 // the live range also reaches the instruction at Def.
1792 EndPoints.push_back(Def);
1794 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1795 << ": " << Other.LI << '\n');
1800 if (isPrunedValue(i, Other)) {
1801 // This value is ultimately a copy of a pruned value in LI or Other.LI.
1802 // We can no longer trust the value mapping computed by
1803 // computeAssignment(), the value that was originally copied could have
1805 LIS->pruneValue(&LI, Def, &EndPoints);
1806 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1807 << Def << ": " << LI << '\n');
1812 llvm_unreachable("Unresolved conflicts");
1817 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1818 SmallVectorImpl<unsigned> &ShrinkRegs) {
1819 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1820 // Get the def location before markUnused() below invalidates it.
1821 SlotIndex Def = LI.getValNumInfo(i)->def;
1822 switch (Vals[i].Resolution) {
1824 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1825 // longer. The IMPLICIT_DEF instructions are only inserted by
1826 // PHIElimination to guarantee that all PHI predecessors have a value.
1827 if (!Vals[i].IsImplicitDef || !Vals[i].Pruned)
1829 // Remove value number i from LI. Note that this VNInfo is still present
1830 // in NewVNInfo, so it will appear as an unused value number in the final
1832 LI.getValNumInfo(i)->markUnused();
1833 LI.removeValNo(LI.getValNumInfo(i));
1834 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1838 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1839 assert(MI && "No instruction to erase");
1841 unsigned Reg = MI->getOperand(1).getReg();
1842 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1843 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1844 ShrinkRegs.push_back(Reg);
1846 ErasedInstrs.insert(MI);
1847 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1848 LIS->RemoveMachineInstrFromMaps(MI);
1849 MI->eraseFromParent();
1858 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1859 SmallVector<VNInfo*, 16> NewVNInfo;
1860 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1861 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1862 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1863 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1865 DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1866 << "\n\t\tLHS = " << PrintReg(CP.getDstReg()) << ' ' << LHS
1869 // First compute NewVNInfo and the simple value mappings.
1870 // Detect impossible conflicts early.
1871 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1874 // Some conflicts can only be resolved after all values have been mapped.
1875 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1878 // All clear, the live ranges can be merged.
1880 // The merging algorithm in LiveInterval::join() can't handle conflicting
1881 // value mappings, so we need to remove any live ranges that overlap a
1882 // CR_Replace resolution. Collect a set of end points that can be used to
1883 // restore the live range after joining.
1884 SmallVector<SlotIndex, 8> EndPoints;
1885 LHSVals.pruneValues(RHSVals, EndPoints);
1886 RHSVals.pruneValues(LHSVals, EndPoints);
1888 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1889 // registers to require trimming.
1890 SmallVector<unsigned, 8> ShrinkRegs;
1891 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1892 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1893 while (!ShrinkRegs.empty())
1894 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1896 // Join RHS into LHS.
1897 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo,
1900 // Kill flags are going to be wrong if the live ranges were overlapping.
1901 // Eventually, we should simply clear all kill flags when computing live
1902 // ranges. They are reinserted after register allocation.
1903 MRI->clearKillFlags(LHS.reg);
1904 MRI->clearKillFlags(RHS.reg);
1906 if (EndPoints.empty())
1909 // Recompute the parts of the live range we had to remove because of
1910 // CR_Replace conflicts.
1911 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
1912 << " points: " << LHS << '\n');
1913 LIS->extendToIndices(&LHS, EndPoints);
1917 /// joinIntervals - Attempt to join these two intervals. On failure, this
1919 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1920 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
1924 // Information concerning MBB coalescing priority.
1925 struct MBBPriorityInfo {
1926 MachineBasicBlock *MBB;
1930 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
1931 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
1934 // MBBPriorityCompare - Comparison predicate that sorts first based on the
1935 // loop depth of the basic block (the unsigned), and then on the MBB number.
1936 struct MBBPriorityCompare {
1937 bool operator()(const MBBPriorityInfo &LHS,
1938 const MBBPriorityInfo &RHS) const {
1939 // Deeper loops first
1940 if (LHS.Depth != RHS.Depth)
1941 return LHS.Depth > RHS.Depth;
1943 // Try to unsplit critical edges next.
1944 if (EnableJoinSplits && LHS.IsSplit != RHS.IsSplit)
1947 // Prefer blocks that are more connected in the CFG. This takes care of
1948 // the most difficult copies first while intervals are short.
1949 unsigned cl = LHS.MBB->pred_size() + LHS.MBB->succ_size();
1950 unsigned cr = RHS.MBB->pred_size() + RHS.MBB->succ_size();
1954 // As a last resort, sort by block number.
1955 return LHS.MBB->getNumber() < RHS.MBB->getNumber();
1960 // Try joining WorkList copies starting from index From.
1961 // Null out any successful joins.
1962 bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1963 assert(From <= WorkList.size() && "Out of range");
1964 bool Progress = false;
1965 for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1968 // Skip instruction pointers that have already been erased, for example by
1969 // dead code elimination.
1970 if (ErasedInstrs.erase(WorkList[i])) {
1975 bool Success = joinCopy(WorkList[i], Again);
1976 Progress |= Success;
1977 if (Success || !Again)
1984 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1985 DEBUG(dbgs() << MBB->getName() << ":\n");
1987 // Collect all copy-like instructions in MBB. Don't start coalescing anything
1988 // yet, it might invalidate the iterator.
1989 const unsigned PrevSize = WorkList.size();
1990 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1992 if (MII->isCopyLike())
1993 WorkList.push_back(MII);
1995 // Try coalescing the collected copies immediately, and remove the nulls.
1996 // This prevents the WorkList from getting too large since most copies are
1997 // joinable on the first attempt.
1998 if (copyCoalesceWorkList(PrevSize))
1999 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2000 (MachineInstr*)0), WorkList.end());
2003 void RegisterCoalescer::joinAllIntervals() {
2004 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2005 assert(WorkList.empty() && "Old data still around.");
2007 if (Loops->empty()) {
2008 // If there are no loops in the function, join intervals in function order.
2009 for (MachineFunction::iterator I = MF->begin(), E = MF->end();
2011 copyCoalesceInMBB(I);
2013 // Otherwise, join intervals in inner loops before other intervals.
2014 // Unfortunately we can't just iterate over loop hierarchy here because
2015 // there may be more MBB's than BB's. Collect MBB's for sorting.
2017 // Join intervals in the function prolog first. We want to join physical
2018 // registers with virtual registers before the intervals got too long.
2019 std::vector<MBBPriorityInfo> MBBs;
2020 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2021 MachineBasicBlock *MBB = I;
2022 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2025 std::sort(MBBs.begin(), MBBs.end(), MBBPriorityCompare());
2027 // Finally, join intervals in loop nest order.
2028 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2029 copyCoalesceInMBB(MBBs[i].MBB);
2032 // Joining intervals can allow other intervals to be joined. Iteratively join
2033 // until we make no progress.
2034 while (copyCoalesceWorkList())
2038 void RegisterCoalescer::releaseMemory() {
2039 ErasedInstrs.clear();
2042 InflateRegs.clear();
2045 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2047 MRI = &fn.getRegInfo();
2048 TM = &fn.getTarget();
2049 TRI = TM->getRegisterInfo();
2050 TII = TM->getInstrInfo();
2051 LIS = &getAnalysis<LiveIntervals>();
2052 LDV = &getAnalysis<LiveDebugVariables>();
2053 AA = &getAnalysis<AliasAnalysis>();
2054 Loops = &getAnalysis<MachineLoopInfo>();
2056 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2057 << "********** Function: " << MF->getName() << '\n');
2059 if (VerifyCoalescing)
2060 MF->verify(this, "Before register coalescing");
2062 RegClassInfo.runOnMachineFunction(fn);
2064 // Join (coalesce) intervals if requested.
2068 // After deleting a lot of copies, register classes may be less constrained.
2069 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2071 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2072 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2074 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2075 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2076 unsigned Reg = InflateRegs[i];
2077 if (MRI->reg_nodbg_empty(Reg))
2079 if (MRI->recomputeRegClass(Reg, *TM)) {
2080 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2081 << MRI->getRegClass(Reg)->getName() << '\n');
2088 if (VerifyCoalescing)
2089 MF->verify(this, "After register coalescing");
2093 /// print - Implement the dump method.
2094 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {