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