1 //===-- TailDuplicator.cpp - Duplicate blocks into predecessors' tails ---===//
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 utility class duplicates basic blocks ending in unconditional branches
11 // into the tails of their predecessors.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/TailDuplicator.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "tailduplication"
34 STATISTIC(NumTails, "Number of tails duplicated");
35 STATISTIC(NumTailDups, "Number of tail duplicated blocks");
36 STATISTIC(NumTailDupAdded,
37 "Number of instructions added due to tail duplication");
38 STATISTIC(NumTailDupRemoved,
39 "Number of instructions removed due to tail duplication");
40 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
41 STATISTIC(NumAddedPHIs, "Number of phis added");
43 // Heuristic for tail duplication.
44 static cl::opt<unsigned> TailDuplicateSize(
46 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
50 TailDupVerify("tail-dup-verify",
51 cl::desc("Verify sanity of PHI instructions during taildup"),
52 cl::init(false), cl::Hidden);
54 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
59 void TailDuplicator::initMF(MachineFunction &MF, const MachineModuleInfo *MMIin,
60 const MachineBranchProbabilityInfo *MBPIin) {
61 TII = MF.getSubtarget().getInstrInfo();
62 TRI = MF.getSubtarget().getRegisterInfo();
63 MRI = &MF.getRegInfo();
67 assert(MBPI != nullptr && "Machine Branch Probability Info required");
69 PreRegAlloc = MRI->isSSA();
72 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
73 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
74 MachineBasicBlock *MBB = &*I;
75 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
77 MachineBasicBlock::iterator MI = MBB->begin();
78 while (MI != MBB->end()) {
81 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
84 MachineBasicBlock *PredBB = *PI;
86 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
87 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
88 if (PHIBB == PredBB) {
94 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
95 dbgs() << " missing input from predecessor BB#"
96 << PredBB->getNumber() << '\n';
97 llvm_unreachable(nullptr);
101 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
102 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
103 if (CheckExtra && !Preds.count(PHIBB)) {
104 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
106 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
108 llvm_unreachable(nullptr);
110 if (PHIBB->getNumber() < 0) {
111 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
112 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
113 llvm_unreachable(nullptr);
121 /// Tail duplicate the block and cleanup.
122 bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple,
123 MachineBasicBlock *MBB) {
124 // Save the successors list.
125 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
128 SmallVector<MachineBasicBlock *, 8> TDBBs;
129 SmallVector<MachineInstr *, 16> Copies;
130 if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies))
135 SmallVector<MachineInstr *, 8> NewPHIs;
136 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
138 // TailBB's immediate successors are now successors of those predecessors
139 // which duplicated TailBB. Add the predecessors as sources to the PHI
141 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
143 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
145 // If it is dead, remove it.
147 NumTailDupRemoved += MBB->size();
148 removeDeadBlock(MBB);
153 if (!SSAUpdateVRs.empty()) {
154 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
155 unsigned VReg = SSAUpdateVRs[i];
156 SSAUpdate.Initialize(VReg);
158 // If the original definition is still around, add it as an available
160 MachineInstr *DefMI = MRI->getVRegDef(VReg);
161 MachineBasicBlock *DefBB = nullptr;
163 DefBB = DefMI->getParent();
164 SSAUpdate.AddAvailableValue(DefBB, VReg);
167 // Add the new vregs as available values.
168 DenseMap<unsigned, AvailableValsTy>::iterator LI =
169 SSAUpdateVals.find(VReg);
170 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
171 MachineBasicBlock *SrcBB = LI->second[j].first;
172 unsigned SrcReg = LI->second[j].second;
173 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
176 // Rewrite uses that are outside of the original def's block.
177 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
178 while (UI != MRI->use_end()) {
179 MachineOperand &UseMO = *UI;
180 MachineInstr *UseMI = UseMO.getParent();
182 if (UseMI->isDebugValue()) {
183 // SSAUpdate can replace the use with an undef. That creates
184 // a debug instruction that is a kill.
185 // FIXME: Should it SSAUpdate job to delete debug instructions
186 // instead of replacing the use with undef?
187 UseMI->eraseFromParent();
190 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
192 SSAUpdate.RewriteUse(UseMO);
196 SSAUpdateVRs.clear();
197 SSAUpdateVals.clear();
200 // Eliminate some of the copies inserted by tail duplication to maintain
202 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
203 MachineInstr *Copy = Copies[i];
206 unsigned Dst = Copy->getOperand(0).getReg();
207 unsigned Src = Copy->getOperand(1).getReg();
208 if (MRI->hasOneNonDBGUse(Src) &&
209 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
210 // Copy is the only use. Do trivial copy propagation here.
211 MRI->replaceRegWith(Dst, Src);
212 Copy->eraseFromParent();
217 NumAddedPHIs += NewPHIs.size();
222 /// Look for small blocks that are unconditionally branched to and do not fall
223 /// through. Tail-duplicate their instructions into their predecessors to
224 /// eliminate (dynamic) branches.
225 bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) {
226 bool MadeChange = false;
228 if (PreRegAlloc && TailDupVerify) {
229 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
230 VerifyPHIs(MF, true);
233 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) {
234 MachineBasicBlock *MBB = &*I++;
236 if (NumTails == TailDupLimit)
239 bool IsSimple = isSimpleBB(MBB);
241 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
244 MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB);
247 if (PreRegAlloc && TailDupVerify)
248 VerifyPHIs(MF, false);
253 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
254 const MachineRegisterInfo *MRI) {
255 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
256 if (UseMI.isDebugValue())
258 if (UseMI.getParent() != BB)
264 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
265 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
266 if (MI->getOperand(i + 1).getMBB() == SrcBB)
271 // Remember which registers are used by phis in this block. This is
272 // used to determine which registers are liveout while modifying the
273 // block (which is why we need to copy the information).
274 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
275 DenseSet<unsigned> *UsedByPhi) {
276 for (const auto &MI : BB) {
279 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
280 unsigned SrcReg = MI.getOperand(i).getReg();
281 UsedByPhi->insert(SrcReg);
286 /// Add a definition and source virtual registers pair for SSA update.
287 void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
288 MachineBasicBlock *BB) {
289 DenseMap<unsigned, AvailableValsTy>::iterator LI =
290 SSAUpdateVals.find(OrigReg);
291 if (LI != SSAUpdateVals.end())
292 LI->second.push_back(std::make_pair(BB, NewReg));
294 AvailableValsTy Vals;
295 Vals.push_back(std::make_pair(BB, NewReg));
296 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
297 SSAUpdateVRs.push_back(OrigReg);
301 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
302 /// source register that's contributed by PredBB and update SSA update map.
303 void TailDuplicator::processPHI(
304 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
305 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
306 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
307 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
308 unsigned DefReg = MI->getOperand(0).getReg();
309 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
310 assert(SrcOpIdx && "Unable to find matching PHI source?");
311 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
312 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
313 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
314 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
316 // Insert a copy from source to the end of the block. The def register is the
317 // available value liveout of the block.
318 unsigned NewDef = MRI->createVirtualRegister(RC);
319 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
320 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
321 addSSAUpdateEntry(DefReg, NewDef, PredBB);
326 // Remove PredBB from the PHI node.
327 MI->RemoveOperand(SrcOpIdx + 1);
328 MI->RemoveOperand(SrcOpIdx);
329 if (MI->getNumOperands() == 1)
330 MI->eraseFromParent();
333 /// Duplicate a TailBB instruction to PredBB and update
334 /// the source operands due to earlier PHI translation.
335 void TailDuplicator::duplicateInstruction(
336 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
338 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
339 const DenseSet<unsigned> &UsedByPhi) {
340 MachineInstr *NewMI = TII->duplicate(*MI, MF);
342 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
343 MachineOperand &MO = NewMI->getOperand(i);
346 unsigned Reg = MO.getReg();
347 if (!TargetRegisterInfo::isVirtualRegister(Reg))
350 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
351 unsigned NewReg = MRI->createVirtualRegister(RC);
353 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
354 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
355 addSSAUpdateEntry(Reg, NewReg, PredBB);
357 auto VI = LocalVRMap.find(Reg);
358 if (VI != LocalVRMap.end()) {
359 // Need to make sure that the register class of the mapped register
360 // will satisfy the constraints of the class of the register being
362 auto *OrigRC = MRI->getRegClass(Reg);
363 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
364 const TargetRegisterClass *ConstrRC;
365 if (VI->second.SubReg != 0) {
366 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
369 // The actual constraining (as in "find appropriate new class")
370 // is done by getMatchingSuperRegClass, so now we only need to
371 // change the class of the mapped register.
372 MRI->setRegClass(VI->second.Reg, ConstrRC);
375 // For mapped registers that do not have sub-registers, simply
376 // restrict their class to match the original one.
377 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
381 // If the class constraining succeeded, we can simply replace
382 // the old register with the mapped one.
383 MO.setReg(VI->second.Reg);
384 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
385 // sub-register, we need to compose the sub-register indices.
386 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
389 // The direct replacement is not possible, due to failing register
390 // class constraints. An explicit COPY is necessary. Create one
391 // that can be reused
392 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
393 if (NewRC == nullptr)
395 unsigned NewReg = MRI->createVirtualRegister(NewRC);
396 BuildMI(*PredBB, MI, MI->getDebugLoc(),
397 TII->get(TargetOpcode::COPY), NewReg)
398 .addReg(VI->second.Reg, 0, VI->second.SubReg);
399 LocalVRMap.erase(VI);
400 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
402 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
403 // is equivalent to the whole register Reg. Hence, Reg:subreg
404 // is same as NewReg:subreg, so keep the sub-register index
407 // Clear any kill flags from this operand. The new register could
408 // have uses after this one, so kills are not valid here.
414 PredBB->insert(PredBB->instr_end(), NewMI);
417 /// After FromBB is tail duplicated into its predecessor blocks, the successors
418 /// have gained new predecessors. Update the PHI instructions in them
420 void TailDuplicator::updateSuccessorsPHIs(
421 MachineBasicBlock *FromBB, bool isDead,
422 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
423 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
424 for (SmallSetVector<MachineBasicBlock *, 8>::iterator SI = Succs.begin(),
427 MachineBasicBlock *SuccBB = *SI;
428 for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
432 MachineInstrBuilder MIB(*FromBB->getParent(), II);
434 for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
435 MachineOperand &MO = II->getOperand(i + 1);
436 if (MO.getMBB() == FromBB) {
443 MachineOperand &MO0 = II->getOperand(Idx);
444 unsigned Reg = MO0.getReg();
446 // Folded into the previous BB.
447 // There could be duplicate phi source entries. FIXME: Should sdisel
448 // or earlier pass fixed this?
449 for (unsigned i = II->getNumOperands() - 2; i != Idx; i -= 2) {
450 MachineOperand &MO = II->getOperand(i + 1);
451 if (MO.getMBB() == FromBB) {
452 II->RemoveOperand(i + 1);
453 II->RemoveOperand(i);
459 // If Idx is set, the operands at Idx and Idx+1 must be removed.
460 // We reuse the location to avoid expensive RemoveOperand calls.
462 DenseMap<unsigned, AvailableValsTy>::iterator LI =
463 SSAUpdateVals.find(Reg);
464 if (LI != SSAUpdateVals.end()) {
465 // This register is defined in the tail block.
466 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
467 MachineBasicBlock *SrcBB = LI->second[j].first;
468 // If we didn't duplicate a bb into a particular predecessor, we
469 // might still have added an entry to SSAUpdateVals to correcly
470 // recompute SSA. If that case, avoid adding a dummy extra argument
472 if (!SrcBB->isSuccessor(SuccBB))
475 unsigned SrcReg = LI->second[j].second;
477 II->getOperand(Idx).setReg(SrcReg);
478 II->getOperand(Idx + 1).setMBB(SrcBB);
481 MIB.addReg(SrcReg).addMBB(SrcBB);
485 // Live in tail block, must also be live in predecessors.
486 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
487 MachineBasicBlock *SrcBB = TDBBs[j];
489 II->getOperand(Idx).setReg(Reg);
490 II->getOperand(Idx + 1).setMBB(SrcBB);
493 MIB.addReg(Reg).addMBB(SrcBB);
498 II->RemoveOperand(Idx + 1);
499 II->RemoveOperand(Idx);
505 /// Determine if it is profitable to duplicate this block.
506 bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF,
508 MachineBasicBlock &TailBB) {
509 // Only duplicate blocks that end with unconditional branches.
510 if (TailBB.canFallThrough())
513 // Don't try to tail-duplicate single-block loops.
514 if (TailBB.isSuccessor(&TailBB))
517 // Set the limit on the cost to duplicate. When optimizing for size,
518 // duplicate only one, because one branch instruction can be eliminated to
519 // compensate for the duplication.
520 unsigned MaxDuplicateCount;
521 if (TailDuplicateSize.getNumOccurrences() == 0 &&
522 // FIXME: Use Function::optForSize().
523 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
524 MaxDuplicateCount = 1;
526 MaxDuplicateCount = TailDuplicateSize;
528 // If the target has hardware branch prediction that can handle indirect
529 // branches, duplicating them can often make them predictable when there
530 // are common paths through the code. The limit needs to be high enough
531 // to allow undoing the effects of tail merging and other optimizations
532 // that rearrange the predecessors of the indirect branch.
534 bool HasIndirectbr = false;
536 HasIndirectbr = TailBB.back().isIndirectBranch();
538 if (HasIndirectbr && PreRegAlloc)
539 MaxDuplicateCount = 20;
541 // Check the instructions in the block to determine whether tail-duplication
542 // is invalid or unlikely to be profitable.
543 unsigned InstrCount = 0;
544 for (MachineInstr &MI : TailBB) {
545 // Non-duplicable things shouldn't be tail-duplicated.
546 if (MI.isNotDuplicable())
549 // Convergent instructions can be duplicated only if doing so doesn't add
550 // new control dependencies, which is what we're going to do here.
551 if (MI.isConvergent())
554 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
555 // A return may expand into a lot more instructions (e.g. reload of callee
556 // saved registers) after PEI.
557 if (PreRegAlloc && MI.isReturn())
560 // Avoid duplicating calls before register allocation. Calls presents a
561 // barrier to register allocation so duplicating them may end up increasing
563 if (PreRegAlloc && MI.isCall())
566 if (!MI.isPHI() && !MI.isDebugValue())
569 if (InstrCount > MaxDuplicateCount)
573 // Check if any of the successors of TailBB has a PHI node in which the
574 // value corresponding to TailBB uses a subregister.
575 // If a phi node uses a register paired with a subregister, the actual
576 // "value type" of the phi may differ from the type of the register without
577 // any subregisters. Due to a bug, tail duplication may add a new operand
578 // without a necessary subregister, producing an invalid code. This is
579 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
580 // Disable tail duplication for this case for now, until the problem is
582 for (auto SB : TailBB.successors()) {
583 for (auto &I : *SB) {
586 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
588 MachineOperand &PU = I.getOperand(Idx);
589 if (PU.getSubReg() != 0)
594 if (HasIndirectbr && PreRegAlloc)
603 return canCompletelyDuplicateBB(TailBB);
606 /// True if this BB has only one unconditional jump.
607 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
608 if (TailBB->succ_size() != 1)
610 if (TailBB->pred_empty())
612 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
613 if (I == TailBB->end())
615 return I->isUnconditionalBranch();
618 static bool bothUsedInPHI(const MachineBasicBlock &A,
619 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
620 for (MachineBasicBlock *BB : A.successors())
621 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
627 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
628 for (MachineBasicBlock *PredBB : BB.predecessors()) {
629 if (PredBB->succ_size() > 1)
632 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
633 SmallVector<MachineOperand, 4> PredCond;
634 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
637 if (!PredCond.empty())
643 bool TailDuplicator::duplicateSimpleBB(
644 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
645 const DenseSet<unsigned> &UsedByPhi,
646 SmallVectorImpl<MachineInstr *> &Copies) {
647 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
649 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
651 bool Changed = false;
652 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
655 MachineBasicBlock *PredBB = *PI;
657 if (PredBB->hasEHPadSuccessor())
660 if (bothUsedInPHI(*PredBB, Succs))
663 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
664 SmallVector<MachineOperand, 4> PredCond;
665 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
669 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
670 << "From simple Succ: " << *TailBB);
672 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
673 MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
675 // Make PredFBB explicit.
676 if (PredCond.empty())
679 // Make fall through explicit.
686 if (PredFBB == TailBB)
688 if (PredTBB == TailBB)
691 // Make the branch unconditional if possible
692 if (PredTBB == PredFBB) {
697 // Avoid adding fall through branches.
698 if (PredFBB == NextBB)
700 if (PredTBB == NextBB && PredFBB == nullptr)
703 TII->RemoveBranch(*PredBB);
705 if (!PredBB->isSuccessor(NewTarget))
706 PredBB->replaceSuccessor(TailBB, NewTarget);
708 PredBB->removeSuccessor(TailBB, true);
709 assert(PredBB->succ_size() <= 1);
713 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
715 TDBBs.push_back(PredBB);
720 /// If it is profitable, duplicate TailBB's contents in each
721 /// of its predecessors.
722 bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple,
723 MachineBasicBlock *TailBB,
724 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
725 SmallVectorImpl<MachineInstr *> &Copies) {
726 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
728 DenseSet<unsigned> UsedByPhi;
729 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
732 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
734 // Iterate through all the unique predecessors and tail-duplicate this
735 // block into them, if possible. Copying the list ahead of time also
736 // avoids trouble with the predecessor list reallocating.
737 bool Changed = false;
738 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
740 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
743 MachineBasicBlock *PredBB = *PI;
745 assert(TailBB != PredBB &&
746 "Single-block loop should have been rejected earlier!");
747 // EH edges are ignored by AnalyzeBranch.
748 if (PredBB->succ_size() > 1)
751 MachineBasicBlock *PredTBB, *PredFBB;
752 SmallVector<MachineOperand, 4> PredCond;
753 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
755 if (!PredCond.empty())
757 // Don't duplicate into a fall-through predecessor (at least for now).
758 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
761 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
762 << "From Succ: " << *TailBB);
764 TDBBs.push_back(PredBB);
766 // Remove PredBB's unconditional branch.
767 TII->RemoveBranch(*PredBB);
769 // Clone the contents of TailBB into PredBB.
770 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
771 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
772 // Use instr_iterator here to properly handle bundles, e.g.
773 // ARM Thumb2 IT block.
774 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
775 while (I != TailBB->instr_end()) {
776 MachineInstr *MI = &*I;
779 // Replace the uses of the def of the PHI with the register coming
781 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
783 // Replace def of virtual registers with new registers, and update
784 // uses with PHI source register or the new registers.
785 duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
788 appendCopies(PredBB, CopyInfos, Copies);
791 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
793 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
796 PredBB->removeSuccessor(PredBB->succ_begin());
797 assert(PredBB->succ_empty() &&
798 "TailDuplicate called on block with multiple successors!");
799 for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
800 E = TailBB->succ_end();
802 PredBB->addSuccessor(*I, MBPI->getEdgeProbability(TailBB, I));
808 // If TailBB was duplicated into all its predecessors except for the prior
809 // block, which falls through unconditionally, move the contents of this
810 // block into the prior block.
811 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
812 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
813 SmallVector<MachineOperand, 4> PriorCond;
814 // This has to check PrevBB->succ_size() because EH edges are ignored by
816 if (PrevBB->succ_size() == 1 &&
817 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
818 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
819 !TailBB->hasAddressTaken()) {
820 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
821 << "From MBB: " << *TailBB);
823 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
824 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
825 MachineBasicBlock::iterator I = TailBB->begin();
826 // Process PHI instructions first.
827 while (I != TailBB->end() && I->isPHI()) {
828 // Replace the uses of the def of the PHI with the register coming
830 MachineInstr *MI = &*I++;
831 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
834 // Now copy the non-PHI instructions.
835 while (I != TailBB->end()) {
836 // Replace def of virtual registers with new registers, and update
837 // uses with PHI source register or the new registers.
838 MachineInstr *MI = &*I++;
839 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
840 duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
841 MI->eraseFromParent();
843 appendCopies(PrevBB, CopyInfos, Copies);
845 // No PHIs to worry about, just splice the instructions over.
846 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
848 PrevBB->removeSuccessor(PrevBB->succ_begin());
849 assert(PrevBB->succ_empty());
850 PrevBB->transferSuccessors(TailBB);
851 TDBBs.push_back(PrevBB);
855 // If this is after register allocation, there are no phis to fix.
859 // If we made no changes so far, we are safe.
863 // Handle the nasty case in that we duplicated a block that is part of a loop
864 // into some but not all of its predecessors. For example:
868 // if we duplicate 2 into 1 but not into 3, we end up with
869 // 12 -> 3 <-> 2 -> rest |
872 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
873 // with a phi in 3 (which now dominates 2).
874 // What we do here is introduce a copy in 3 of the register defined by the
875 // phi, just like when we are duplicating 2 into 3, but we don't copy any
876 // real instructions or remove the 3 -> 2 edge from the phi in 2.
877 for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
880 MachineBasicBlock *PredBB = *PI;
881 if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
885 if (PredBB->succ_size() != 1)
888 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
889 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
890 MachineBasicBlock::iterator I = TailBB->begin();
891 // Process PHI instructions first.
892 while (I != TailBB->end() && I->isPHI()) {
893 // Replace the uses of the def of the PHI with the register coming
895 MachineInstr *MI = &*I++;
896 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
898 appendCopies(PredBB, CopyInfos, Copies);
904 /// At the end of the block \p MBB generate COPY instructions between registers
905 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
906 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
907 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
908 SmallVectorImpl<MachineInstr*> &Copies) {
909 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
910 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
911 for (auto &CI : CopyInfos) {
912 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
913 .addReg(CI.second.Reg, 0, CI.second.SubReg);
918 /// Remove the specified dead machine basic block from the function, updating
920 void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
921 assert(MBB->pred_empty() && "MBB must be dead!");
922 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
924 // Remove all successors.
925 while (!MBB->succ_empty())
926 MBB->removeSuccessor(MBB->succ_end() - 1);
929 MBB->eraseFromParent();
932 } // End llvm namespace