1 //===-- TailDuplicator.cpp - Duplicate blocks into predecessors' tails ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility class duplicates basic blocks ending in unconditional branches
11 // into the tails of their predecessors.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "tailduplication"
33 
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");
42 
43 // Heuristic for tail duplication.
44 static cl::opt<unsigned> TailDuplicateSize(
45     "tail-dup-size",
46     cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
47     cl::Hidden);
48 
49 static cl::opt<bool>
50     TailDupVerify("tail-dup-verify",
51                   cl::desc("Verify sanity of PHI instructions during taildup"),
52                   cl::init(false), cl::Hidden);
53 
54 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
55                                       cl::Hidden);
56 
57 namespace llvm {
58 
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();
64   MMI = MMIin;
65   MBPI = MBPIin;
66 
67   assert(MBPI != nullptr && "Machine Branch Probability Info required");
68 
69   PreRegAlloc = MRI->isSSA();
70   RS.reset();
71 
72   if (MRI->tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF))
73     RS.reset(new RegScavenger());
74 }
75 
76 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
77   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
78     MachineBasicBlock *MBB = &*I;
79     SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
80                                                  MBB->pred_end());
81     MachineBasicBlock::iterator MI = MBB->begin();
82     while (MI != MBB->end()) {
83       if (!MI->isPHI())
84         break;
85       for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
86                                                             PE = Preds.end();
87            PI != PE; ++PI) {
88         MachineBasicBlock *PredBB = *PI;
89         bool Found = false;
90         for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
91           MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
92           if (PHIBB == PredBB) {
93             Found = true;
94             break;
95           }
96         }
97         if (!Found) {
98           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
99           dbgs() << "  missing input from predecessor BB#"
100                  << PredBB->getNumber() << '\n';
101           llvm_unreachable(nullptr);
102         }
103       }
104 
105       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
106         MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
107         if (CheckExtra && !Preds.count(PHIBB)) {
108           dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
109                  << *MI;
110           dbgs() << "  extra input from predecessor BB#" << PHIBB->getNumber()
111                  << '\n';
112           llvm_unreachable(nullptr);
113         }
114         if (PHIBB->getNumber() < 0) {
115           dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
116           dbgs() << "  non-existing BB#" << PHIBB->getNumber() << '\n';
117           llvm_unreachable(nullptr);
118         }
119       }
120       ++MI;
121     }
122   }
123 }
124 
125 /// Tail duplicate the block and cleanup.
126 bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple,
127                                             MachineBasicBlock *MBB) {
128   // Save the successors list.
129   SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
130                                                MBB->succ_end());
131 
132   SmallVector<MachineBasicBlock *, 8> TDBBs;
133   SmallVector<MachineInstr *, 16> Copies;
134   if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies))
135     return false;
136 
137   ++NumTails;
138 
139   SmallVector<MachineInstr *, 8> NewPHIs;
140   MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
141 
142   // TailBB's immediate successors are now successors of those predecessors
143   // which duplicated TailBB. Add the predecessors as sources to the PHI
144   // instructions.
145   bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
146   if (PreRegAlloc)
147     updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
148 
149   // If it is dead, remove it.
150   if (isDead) {
151     NumTailDupRemoved += MBB->size();
152     removeDeadBlock(MBB);
153     ++NumDeadBlocks;
154   }
155 
156   // Update SSA form.
157   if (!SSAUpdateVRs.empty()) {
158     for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
159       unsigned VReg = SSAUpdateVRs[i];
160       SSAUpdate.Initialize(VReg);
161 
162       // If the original definition is still around, add it as an available
163       // value.
164       MachineInstr *DefMI = MRI->getVRegDef(VReg);
165       MachineBasicBlock *DefBB = nullptr;
166       if (DefMI) {
167         DefBB = DefMI->getParent();
168         SSAUpdate.AddAvailableValue(DefBB, VReg);
169       }
170 
171       // Add the new vregs as available values.
172       DenseMap<unsigned, AvailableValsTy>::iterator LI =
173           SSAUpdateVals.find(VReg);
174       for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
175         MachineBasicBlock *SrcBB = LI->second[j].first;
176         unsigned SrcReg = LI->second[j].second;
177         SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
178       }
179 
180       // Rewrite uses that are outside of the original def's block.
181       MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
182       while (UI != MRI->use_end()) {
183         MachineOperand &UseMO = *UI;
184         MachineInstr *UseMI = UseMO.getParent();
185         ++UI;
186         if (UseMI->isDebugValue()) {
187           // SSAUpdate can replace the use with an undef. That creates
188           // a debug instruction that is a kill.
189           // FIXME: Should it SSAUpdate job to delete debug instructions
190           // instead of replacing the use with undef?
191           UseMI->eraseFromParent();
192           continue;
193         }
194         if (UseMI->getParent() == DefBB && !UseMI->isPHI())
195           continue;
196         SSAUpdate.RewriteUse(UseMO);
197       }
198     }
199 
200     SSAUpdateVRs.clear();
201     SSAUpdateVals.clear();
202   }
203 
204   // Eliminate some of the copies inserted by tail duplication to maintain
205   // SSA form.
206   for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
207     MachineInstr *Copy = Copies[i];
208     if (!Copy->isCopy())
209       continue;
210     unsigned Dst = Copy->getOperand(0).getReg();
211     unsigned Src = Copy->getOperand(1).getReg();
212     if (MRI->hasOneNonDBGUse(Src) &&
213         MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
214       // Copy is the only use. Do trivial copy propagation here.
215       MRI->replaceRegWith(Dst, Src);
216       Copy->eraseFromParent();
217     }
218   }
219 
220   if (NewPHIs.size())
221     NumAddedPHIs += NewPHIs.size();
222 
223   return true;
224 }
225 
226 /// Look for small blocks that are unconditionally branched to and do not fall
227 /// through. Tail-duplicate their instructions into their predecessors to
228 /// eliminate (dynamic) branches.
229 bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) {
230   bool MadeChange = false;
231 
232   if (PreRegAlloc && TailDupVerify) {
233     DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
234     VerifyPHIs(MF, true);
235   }
236 
237   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) {
238     MachineBasicBlock *MBB = &*I++;
239 
240     if (NumTails == TailDupLimit)
241       break;
242 
243     bool IsSimple = isSimpleBB(MBB);
244 
245     if (!shouldTailDuplicate(MF, IsSimple, *MBB))
246       continue;
247 
248     MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB);
249   }
250 
251   if (PreRegAlloc && TailDupVerify)
252     VerifyPHIs(MF, false);
253 
254   return MadeChange;
255 }
256 
257 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
258                          const MachineRegisterInfo *MRI) {
259   for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
260     if (UseMI.isDebugValue())
261       continue;
262     if (UseMI.getParent() != BB)
263       return true;
264   }
265   return false;
266 }
267 
268 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
269   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
270     if (MI->getOperand(i + 1).getMBB() == SrcBB)
271       return i;
272   return 0;
273 }
274 
275 // Remember which registers are used by phis in this block. This is
276 // used to determine which registers are liveout while modifying the
277 // block (which is why we need to copy the information).
278 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
279                               DenseSet<unsigned> *UsedByPhi) {
280   for (const auto &MI : BB) {
281     if (!MI.isPHI())
282       break;
283     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
284       unsigned SrcReg = MI.getOperand(i).getReg();
285       UsedByPhi->insert(SrcReg);
286     }
287   }
288 }
289 
290 /// Add a definition and source virtual registers pair for SSA update.
291 void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
292                                        MachineBasicBlock *BB) {
293   DenseMap<unsigned, AvailableValsTy>::iterator LI =
294       SSAUpdateVals.find(OrigReg);
295   if (LI != SSAUpdateVals.end())
296     LI->second.push_back(std::make_pair(BB, NewReg));
297   else {
298     AvailableValsTy Vals;
299     Vals.push_back(std::make_pair(BB, NewReg));
300     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
301     SSAUpdateVRs.push_back(OrigReg);
302   }
303 }
304 
305 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
306 /// source register that's contributed by PredBB and update SSA update map.
307 void TailDuplicator::processPHI(
308     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
309     DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
310     SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
311     const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
312   unsigned DefReg = MI->getOperand(0).getReg();
313   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
314   assert(SrcOpIdx && "Unable to find matching PHI source?");
315   unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
316   unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
317   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
318   LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
319 
320   // Insert a copy from source to the end of the block. The def register is the
321   // available value liveout of the block.
322   unsigned NewDef = MRI->createVirtualRegister(RC);
323   Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
324   if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
325     addSSAUpdateEntry(DefReg, NewDef, PredBB);
326 
327   if (!Remove)
328     return;
329 
330   // Remove PredBB from the PHI node.
331   MI->RemoveOperand(SrcOpIdx + 1);
332   MI->RemoveOperand(SrcOpIdx);
333   if (MI->getNumOperands() == 1)
334     MI->eraseFromParent();
335 }
336 
337 /// Duplicate a TailBB instruction to PredBB and update
338 /// the source operands due to earlier PHI translation.
339 void TailDuplicator::duplicateInstruction(
340     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
341     MachineFunction &MF,
342     DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
343     const DenseSet<unsigned> &UsedByPhi) {
344   MachineInstr *NewMI = TII->duplicate(MI, MF);
345   if (PreRegAlloc) {
346     for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
347       MachineOperand &MO = NewMI->getOperand(i);
348       if (!MO.isReg())
349         continue;
350       unsigned Reg = MO.getReg();
351       if (!TargetRegisterInfo::isVirtualRegister(Reg))
352         continue;
353       if (MO.isDef()) {
354         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
355         unsigned NewReg = MRI->createVirtualRegister(RC);
356         MO.setReg(NewReg);
357         LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
358         if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
359           addSSAUpdateEntry(Reg, NewReg, PredBB);
360       } else {
361         auto VI = LocalVRMap.find(Reg);
362         if (VI != LocalVRMap.end()) {
363           // Need to make sure that the register class of the mapped register
364           // will satisfy the constraints of the class of the register being
365           // replaced.
366           auto *OrigRC = MRI->getRegClass(Reg);
367           auto *MappedRC = MRI->getRegClass(VI->second.Reg);
368           const TargetRegisterClass *ConstrRC;
369           if (VI->second.SubReg != 0) {
370             ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
371                                                      VI->second.SubReg);
372             if (ConstrRC) {
373               // The actual constraining (as in "find appropriate new class")
374               // is done by getMatchingSuperRegClass, so now we only need to
375               // change the class of the mapped register.
376               MRI->setRegClass(VI->second.Reg, ConstrRC);
377             }
378           } else {
379             // For mapped registers that do not have sub-registers, simply
380             // restrict their class to match the original one.
381             ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
382           }
383 
384           if (ConstrRC) {
385             // If the class constraining succeeded, we can simply replace
386             // the old register with the mapped one.
387             MO.setReg(VI->second.Reg);
388             // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
389             // sub-register, we need to compose the sub-register indices.
390             MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
391                                                    VI->second.SubReg));
392           } else {
393             // The direct replacement is not possible, due to failing register
394             // class constraints. An explicit COPY is necessary. Create one
395             // that can be reused
396             auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
397             if (NewRC == nullptr)
398               NewRC = OrigRC;
399             unsigned NewReg = MRI->createVirtualRegister(NewRC);
400             BuildMI(*PredBB, MI, MI->getDebugLoc(),
401                     TII->get(TargetOpcode::COPY), NewReg)
402                 .addReg(VI->second.Reg, 0, VI->second.SubReg);
403             LocalVRMap.erase(VI);
404             LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
405             MO.setReg(NewReg);
406             // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
407             // is equivalent to the whole register Reg. Hence, Reg:subreg
408             // is same as NewReg:subreg, so keep the sub-register index
409             // unchanged.
410           }
411           // Clear any kill flags from this operand.  The new register could
412           // have uses after this one, so kills are not valid here.
413           MO.setIsKill(false);
414         }
415       }
416     }
417   }
418   PredBB->insert(PredBB->instr_end(), NewMI);
419 }
420 
421 /// After FromBB is tail duplicated into its predecessor blocks, the successors
422 /// have gained new predecessors. Update the PHI instructions in them
423 /// accordingly.
424 void TailDuplicator::updateSuccessorsPHIs(
425     MachineBasicBlock *FromBB, bool isDead,
426     SmallVectorImpl<MachineBasicBlock *> &TDBBs,
427     SmallSetVector<MachineBasicBlock *, 8> &Succs) {
428   for (SmallSetVector<MachineBasicBlock *, 8>::iterator SI = Succs.begin(),
429                                                         SE = Succs.end();
430        SI != SE; ++SI) {
431     MachineBasicBlock *SuccBB = *SI;
432     for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end();
433          II != EE; ++II) {
434       if (!II->isPHI())
435         break;
436       MachineInstrBuilder MIB(*FromBB->getParent(), II);
437       unsigned Idx = 0;
438       for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) {
439         MachineOperand &MO = II->getOperand(i + 1);
440         if (MO.getMBB() == FromBB) {
441           Idx = i;
442           break;
443         }
444       }
445 
446       assert(Idx != 0);
447       MachineOperand &MO0 = II->getOperand(Idx);
448       unsigned Reg = MO0.getReg();
449       if (isDead) {
450         // Folded into the previous BB.
451         // There could be duplicate phi source entries. FIXME: Should sdisel
452         // or earlier pass fixed this?
453         for (unsigned i = II->getNumOperands() - 2; i != Idx; i -= 2) {
454           MachineOperand &MO = II->getOperand(i + 1);
455           if (MO.getMBB() == FromBB) {
456             II->RemoveOperand(i + 1);
457             II->RemoveOperand(i);
458           }
459         }
460       } else
461         Idx = 0;
462 
463       // If Idx is set, the operands at Idx and Idx+1 must be removed.
464       // We reuse the location to avoid expensive RemoveOperand calls.
465 
466       DenseMap<unsigned, AvailableValsTy>::iterator LI =
467           SSAUpdateVals.find(Reg);
468       if (LI != SSAUpdateVals.end()) {
469         // This register is defined in the tail block.
470         for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
471           MachineBasicBlock *SrcBB = LI->second[j].first;
472           // If we didn't duplicate a bb into a particular predecessor, we
473           // might still have added an entry to SSAUpdateVals to correcly
474           // recompute SSA. If that case, avoid adding a dummy extra argument
475           // this PHI.
476           if (!SrcBB->isSuccessor(SuccBB))
477             continue;
478 
479           unsigned SrcReg = LI->second[j].second;
480           if (Idx != 0) {
481             II->getOperand(Idx).setReg(SrcReg);
482             II->getOperand(Idx + 1).setMBB(SrcBB);
483             Idx = 0;
484           } else {
485             MIB.addReg(SrcReg).addMBB(SrcBB);
486           }
487         }
488       } else {
489         // Live in tail block, must also be live in predecessors.
490         for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
491           MachineBasicBlock *SrcBB = TDBBs[j];
492           if (Idx != 0) {
493             II->getOperand(Idx).setReg(Reg);
494             II->getOperand(Idx + 1).setMBB(SrcBB);
495             Idx = 0;
496           } else {
497             MIB.addReg(Reg).addMBB(SrcBB);
498           }
499         }
500       }
501       if (Idx != 0) {
502         II->RemoveOperand(Idx + 1);
503         II->RemoveOperand(Idx);
504       }
505     }
506   }
507 }
508 
509 /// Determine if it is profitable to duplicate this block.
510 bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF,
511                                          bool IsSimple,
512                                          MachineBasicBlock &TailBB) {
513   // Only duplicate blocks that end with unconditional branches.
514   if (TailBB.canFallThrough())
515     return false;
516 
517   // Don't try to tail-duplicate single-block loops.
518   if (TailBB.isSuccessor(&TailBB))
519     return false;
520 
521   // Set the limit on the cost to duplicate. When optimizing for size,
522   // duplicate only one, because one branch instruction can be eliminated to
523   // compensate for the duplication.
524   unsigned MaxDuplicateCount;
525   if (TailDuplicateSize.getNumOccurrences() == 0 &&
526       // FIXME: Use Function::optForSize().
527       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
528     MaxDuplicateCount = 1;
529   else
530     MaxDuplicateCount = TailDuplicateSize;
531 
532   // If the target has hardware branch prediction that can handle indirect
533   // branches, duplicating them can often make them predictable when there
534   // are common paths through the code.  The limit needs to be high enough
535   // to allow undoing the effects of tail merging and other optimizations
536   // that rearrange the predecessors of the indirect branch.
537 
538   bool HasIndirectbr = false;
539   if (!TailBB.empty())
540     HasIndirectbr = TailBB.back().isIndirectBranch();
541 
542   if (HasIndirectbr && PreRegAlloc)
543     MaxDuplicateCount = 20;
544 
545   // Check the instructions in the block to determine whether tail-duplication
546   // is invalid or unlikely to be profitable.
547   unsigned InstrCount = 0;
548   for (MachineInstr &MI : TailBB) {
549     // Non-duplicable things shouldn't be tail-duplicated.
550     if (MI.isNotDuplicable())
551       return false;
552 
553     // Convergent instructions can be duplicated only if doing so doesn't add
554     // new control dependencies, which is what we're going to do here.
555     if (MI.isConvergent())
556       return false;
557 
558     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
559     // A return may expand into a lot more instructions (e.g. reload of callee
560     // saved registers) after PEI.
561     if (PreRegAlloc && MI.isReturn())
562       return false;
563 
564     // Avoid duplicating calls before register allocation. Calls presents a
565     // barrier to register allocation so duplicating them may end up increasing
566     // spills.
567     if (PreRegAlloc && MI.isCall())
568       return false;
569 
570     if (!MI.isPHI() && !MI.isDebugValue())
571       InstrCount += 1;
572 
573     if (InstrCount > MaxDuplicateCount)
574       return false;
575   }
576 
577   // Check if any of the successors of TailBB has a PHI node in which the
578   // value corresponding to TailBB uses a subregister.
579   // If a phi node uses a register paired with a subregister, the actual
580   // "value type" of the phi may differ from the type of the register without
581   // any subregisters. Due to a bug, tail duplication may add a new operand
582   // without a necessary subregister, producing an invalid code. This is
583   // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
584   // Disable tail duplication for this case for now, until the problem is
585   // fixed.
586   for (auto SB : TailBB.successors()) {
587     for (auto &I : *SB) {
588       if (!I.isPHI())
589         break;
590       unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
591       assert(Idx != 0);
592       MachineOperand &PU = I.getOperand(Idx);
593       if (PU.getSubReg() != 0)
594         return false;
595     }
596   }
597 
598   if (HasIndirectbr && PreRegAlloc)
599     return true;
600 
601   if (IsSimple)
602     return true;
603 
604   if (!PreRegAlloc)
605     return true;
606 
607   return canCompletelyDuplicateBB(TailBB);
608 }
609 
610 /// True if this BB has only one unconditional jump.
611 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
612   if (TailBB->succ_size() != 1)
613     return false;
614   if (TailBB->pred_empty())
615     return false;
616   MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
617   if (I == TailBB->end())
618     return true;
619   return I->isUnconditionalBranch();
620 }
621 
622 static bool bothUsedInPHI(const MachineBasicBlock &A,
623                           const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
624   for (MachineBasicBlock *BB : A.successors())
625     if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
626       return true;
627 
628   return false;
629 }
630 
631 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
632   for (MachineBasicBlock *PredBB : BB.predecessors()) {
633     if (PredBB->succ_size() > 1)
634       return false;
635 
636     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
637     SmallVector<MachineOperand, 4> PredCond;
638     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
639       return false;
640 
641     if (!PredCond.empty())
642       return false;
643   }
644   return true;
645 }
646 
647 bool TailDuplicator::duplicateSimpleBB(
648     MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
649     const DenseSet<unsigned> &UsedByPhi,
650     SmallVectorImpl<MachineInstr *> &Copies) {
651   SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
652                                             TailBB->succ_end());
653   SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
654                                             TailBB->pred_end());
655   bool Changed = false;
656   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
657                                                         PE = Preds.end();
658        PI != PE; ++PI) {
659     MachineBasicBlock *PredBB = *PI;
660 
661     if (PredBB->hasEHPadSuccessor())
662       continue;
663 
664     if (bothUsedInPHI(*PredBB, Succs))
665       continue;
666 
667     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
668     SmallVector<MachineOperand, 4> PredCond;
669     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
670       continue;
671 
672     Changed = true;
673     DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
674                  << "From simple Succ: " << *TailBB);
675 
676     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
677     MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
678 
679     // Make PredFBB explicit.
680     if (PredCond.empty())
681       PredFBB = PredTBB;
682 
683     // Make fall through explicit.
684     if (!PredTBB)
685       PredTBB = NextBB;
686     if (!PredFBB)
687       PredFBB = NextBB;
688 
689     // Redirect
690     if (PredFBB == TailBB)
691       PredFBB = NewTarget;
692     if (PredTBB == TailBB)
693       PredTBB = NewTarget;
694 
695     // Make the branch unconditional if possible
696     if (PredTBB == PredFBB) {
697       PredCond.clear();
698       PredFBB = nullptr;
699     }
700 
701     // Avoid adding fall through branches.
702     if (PredFBB == NextBB)
703       PredFBB = nullptr;
704     if (PredTBB == NextBB && PredFBB == nullptr)
705       PredTBB = nullptr;
706 
707     TII->RemoveBranch(*PredBB);
708 
709     if (!PredBB->isSuccessor(NewTarget))
710       PredBB->replaceSuccessor(TailBB, NewTarget);
711     else {
712       PredBB->removeSuccessor(TailBB, true);
713       assert(PredBB->succ_size() <= 1);
714     }
715 
716     if (PredTBB)
717       TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
718 
719     TDBBs.push_back(PredBB);
720   }
721   return Changed;
722 }
723 
724 /// If it is profitable, duplicate TailBB's contents in each
725 /// of its predecessors.
726 bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple,
727                                    MachineBasicBlock *TailBB,
728                                    SmallVectorImpl<MachineBasicBlock *> &TDBBs,
729                                    SmallVectorImpl<MachineInstr *> &Copies) {
730   DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
731 
732   DenseSet<unsigned> UsedByPhi;
733   getRegsUsedByPHIs(*TailBB, &UsedByPhi);
734 
735   if (IsSimple)
736     return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
737 
738   // Iterate through all the unique predecessors and tail-duplicate this
739   // block into them, if possible. Copying the list ahead of time also
740   // avoids trouble with the predecessor list reallocating.
741   bool Changed = false;
742   SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
743                                                TailBB->pred_end());
744   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
745                                                         PE = Preds.end();
746        PI != PE; ++PI) {
747     MachineBasicBlock *PredBB = *PI;
748 
749     assert(TailBB != PredBB &&
750            "Single-block loop should have been rejected earlier!");
751     // EH edges are ignored by AnalyzeBranch.
752     if (PredBB->succ_size() > 1)
753       continue;
754 
755     MachineBasicBlock *PredTBB, *PredFBB;
756     SmallVector<MachineOperand, 4> PredCond;
757     if (TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
758       continue;
759     if (!PredCond.empty())
760       continue;
761     // Don't duplicate into a fall-through predecessor (at least for now).
762     if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
763       continue;
764 
765     DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
766                  << "From Succ: " << *TailBB);
767 
768     TDBBs.push_back(PredBB);
769 
770     // Remove PredBB's unconditional branch.
771     TII->RemoveBranch(*PredBB);
772 
773     if (RS && !TailBB->livein_empty()) {
774       // Update PredBB livein.
775       RS->enterBasicBlock(*PredBB);
776       if (!PredBB->empty())
777         RS->forward(std::prev(PredBB->end()));
778       for (const auto &LI : TailBB->liveins()) {
779         if (!RS->isRegUsed(LI.PhysReg, false))
780           // If a register is previously livein to the tail but it's not live
781           // at the end of predecessor BB, then it should be added to its
782           // livein list.
783           PredBB->addLiveIn(LI);
784       }
785     }
786 
787     // Clone the contents of TailBB into PredBB.
788     DenseMap<unsigned, RegSubRegPair> LocalVRMap;
789     SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
790     // Use instr_iterator here to properly handle bundles, e.g.
791     // ARM Thumb2 IT block.
792     MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
793     while (I != TailBB->instr_end()) {
794       MachineInstr *MI = &*I;
795       ++I;
796       if (MI->isPHI()) {
797         // Replace the uses of the def of the PHI with the register coming
798         // from PredBB.
799         processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
800       } else {
801         // Replace def of virtual registers with new registers, and update
802         // uses with PHI source register or the new registers.
803         duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
804       }
805     }
806     appendCopies(PredBB, CopyInfos, Copies);
807 
808     // Simplify
809     TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
810 
811     NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
812 
813     // Update the CFG.
814     PredBB->removeSuccessor(PredBB->succ_begin());
815     assert(PredBB->succ_empty() &&
816            "TailDuplicate called on block with multiple successors!");
817     for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(),
818                                           E = TailBB->succ_end();
819          I != E; ++I)
820       PredBB->addSuccessor(*I, MBPI->getEdgeProbability(TailBB, I));
821 
822     Changed = true;
823     ++NumTailDups;
824   }
825 
826   // If TailBB was duplicated into all its predecessors except for the prior
827   // block, which falls through unconditionally, move the contents of this
828   // block into the prior block.
829   MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
830   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
831   SmallVector<MachineOperand, 4> PriorCond;
832   // This has to check PrevBB->succ_size() because EH edges are ignored by
833   // AnalyzeBranch.
834   if (PrevBB->succ_size() == 1 &&
835       !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
836       PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
837       !TailBB->hasAddressTaken()) {
838     DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
839                  << "From MBB: " << *TailBB);
840     if (PreRegAlloc) {
841       DenseMap<unsigned, RegSubRegPair> LocalVRMap;
842       SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
843       MachineBasicBlock::iterator I = TailBB->begin();
844       // Process PHI instructions first.
845       while (I != TailBB->end() && I->isPHI()) {
846         // Replace the uses of the def of the PHI with the register coming
847         // from PredBB.
848         MachineInstr *MI = &*I++;
849         processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
850       }
851 
852       // Now copy the non-PHI instructions.
853       while (I != TailBB->end()) {
854         // Replace def of virtual registers with new registers, and update
855         // uses with PHI source register or the new registers.
856         MachineInstr *MI = &*I++;
857         assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
858         duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
859         MI->eraseFromParent();
860       }
861       appendCopies(PrevBB, CopyInfos, Copies);
862     } else {
863       // No PHIs to worry about, just splice the instructions over.
864       PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
865     }
866     PrevBB->removeSuccessor(PrevBB->succ_begin());
867     assert(PrevBB->succ_empty());
868     PrevBB->transferSuccessors(TailBB);
869     TDBBs.push_back(PrevBB);
870     Changed = true;
871   }
872 
873   // If this is after register allocation, there are no phis to fix.
874   if (!PreRegAlloc)
875     return Changed;
876 
877   // If we made no changes so far, we are safe.
878   if (!Changed)
879     return Changed;
880 
881   // Handle the nasty case in that we duplicated a block that is part of a loop
882   // into some but not all of its predecessors. For example:
883   //    1 -> 2 <-> 3                 |
884   //          \                      |
885   //           \---> rest            |
886   // if we duplicate 2 into 1 but not into 3, we end up with
887   // 12 -> 3 <-> 2 -> rest           |
888   //   \             /               |
889   //    \----->-----/                |
890   // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
891   // with a phi in 3 (which now dominates 2).
892   // What we do here is introduce a copy in 3 of the register defined by the
893   // phi, just like when we are duplicating 2 into 3, but we don't copy any
894   // real instructions or remove the 3 -> 2 edge from the phi in 2.
895   for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(),
896                                                         PE = Preds.end();
897        PI != PE; ++PI) {
898     MachineBasicBlock *PredBB = *PI;
899     if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end())
900       continue;
901 
902     // EH edges
903     if (PredBB->succ_size() != 1)
904       continue;
905 
906     DenseMap<unsigned, RegSubRegPair> LocalVRMap;
907     SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
908     MachineBasicBlock::iterator I = TailBB->begin();
909     // Process PHI instructions first.
910     while (I != TailBB->end() && I->isPHI()) {
911       // Replace the uses of the def of the PHI with the register coming
912       // from PredBB.
913       MachineInstr *MI = &*I++;
914       processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
915     }
916     appendCopies(PredBB, CopyInfos, Copies);
917   }
918 
919   return Changed;
920 }
921 
922 /// At the end of the block \p MBB generate COPY instructions between registers
923 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
924 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
925       SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
926       SmallVectorImpl<MachineInstr*> &Copies) {
927   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
928   const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
929   for (auto &CI : CopyInfos) {
930     auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
931                 .addReg(CI.second.Reg, 0, CI.second.SubReg);
932     Copies.push_back(C);
933   }
934 }
935 
936 /// Remove the specified dead machine basic block from the function, updating
937 /// the CFG.
938 void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
939   assert(MBB->pred_empty() && "MBB must be dead!");
940   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
941 
942   // Remove all successors.
943   while (!MBB->succ_empty())
944     MBB->removeSuccessor(MBB->succ_end() - 1);
945 
946   // Remove the block.
947   MBB->eraseFromParent();
948 }
949 
950 } // End llvm namespace
951