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