xref: /llvm-project/llvm/lib/CodeGen/TailDuplicator.cpp (revision 6ab26eab4f1e06f2da7b3183c55666ad57f8866e)
1 //===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility class duplicates basic blocks ending in unconditional branches
10 // into the tails of their predecessors.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TailDuplicator.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/MachineSSAUpdater.h"
30 #include "llvm/CodeGen/MachineSizeOpts.h"
31 #include "llvm/CodeGen/TargetInstrInfo.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/CodeGen/TargetSubtargetInfo.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <iterator>
44 #include <utility>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "tailduplication"
49 
50 STATISTIC(NumTails, "Number of tails duplicated");
51 STATISTIC(NumTailDups, "Number of tail duplicated blocks");
52 STATISTIC(NumTailDupAdded,
53           "Number of instructions added due to tail duplication");
54 STATISTIC(NumTailDupRemoved,
55           "Number of instructions removed due to tail duplication");
56 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
57 STATISTIC(NumAddedPHIs, "Number of phis added");
58 
59 // Heuristic for tail duplication.
60 static cl::opt<unsigned> TailDuplicateSize(
61     "tail-dup-size",
62     cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
63     cl::Hidden);
64 
65 static cl::opt<unsigned> TailDupIndirectBranchSize(
66     "tail-dup-indirect-size",
67     cl::desc("Maximum instructions to consider tail duplicating blocks that "
68              "end with indirect branches."), cl::init(20),
69     cl::Hidden);
70 
71 static cl::opt<unsigned>
72     TailDupPredSize("tail-dup-pred-size",
73                     cl::desc("Maximum predecessors (maximum successors at the "
74                              "same time) to consider tail duplicating blocks."),
75                     cl::init(16), cl::Hidden);
76 
77 static cl::opt<unsigned>
78     TailDupSuccSize("tail-dup-succ-size",
79                     cl::desc("Maximum successors (maximum predecessors at the "
80                              "same time) to consider tail duplicating blocks."),
81                     cl::init(16), cl::Hidden);
82 
83 static cl::opt<bool>
84     TailDupVerify("tail-dup-verify",
85                   cl::desc("Verify sanity of PHI instructions during taildup"),
86                   cl::init(false), cl::Hidden);
87 
88 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
89                                       cl::Hidden);
90 
91 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
92                             const MachineBranchProbabilityInfo *MBPIin,
93                             MBFIWrapper *MBFIin,
94                             ProfileSummaryInfo *PSIin,
95                             bool LayoutModeIn, unsigned TailDupSizeIn) {
96   MF = &MFin;
97   TII = MF->getSubtarget().getInstrInfo();
98   TRI = MF->getSubtarget().getRegisterInfo();
99   MRI = &MF->getRegInfo();
100   MBPI = MBPIin;
101   MBFI = MBFIin;
102   PSI = PSIin;
103   TailDupSize = TailDupSizeIn;
104 
105   assert(MBPI != nullptr && "Machine Branch Probability Info required");
106 
107   LayoutMode = LayoutModeIn;
108   this->PreRegAlloc = PreRegAlloc;
109 }
110 
111 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
112   for (MachineBasicBlock &MBB : llvm::drop_begin(MF)) {
113     SmallSetVector<MachineBasicBlock *, 8> Preds(MBB.pred_begin(),
114                                                  MBB.pred_end());
115     MachineBasicBlock::iterator MI = MBB.begin();
116     while (MI != MBB.end()) {
117       if (!MI->isPHI())
118         break;
119       for (MachineBasicBlock *PredBB : Preds) {
120         bool Found = false;
121         for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
122           MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
123           if (PHIBB == PredBB) {
124             Found = true;
125             break;
126           }
127         }
128         if (!Found) {
129           dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
130                  << *MI;
131           dbgs() << "  missing input from predecessor "
132                  << printMBBReference(*PredBB) << '\n';
133           llvm_unreachable(nullptr);
134         }
135       }
136 
137       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
138         MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
139         if (CheckExtra && !Preds.count(PHIBB)) {
140           dbgs() << "Warning: malformed PHI in " << printMBBReference(MBB)
141                  << ": " << *MI;
142           dbgs() << "  extra input from predecessor "
143                  << printMBBReference(*PHIBB) << '\n';
144           llvm_unreachable(nullptr);
145         }
146         if (PHIBB->getNumber() < 0) {
147           dbgs() << "Malformed PHI in " << printMBBReference(MBB) << ": "
148                  << *MI;
149           dbgs() << "  non-existing " << printMBBReference(*PHIBB) << '\n';
150           llvm_unreachable(nullptr);
151         }
152       }
153       ++MI;
154     }
155   }
156 }
157 
158 /// Tail duplicate the block and cleanup.
159 /// \p IsSimple - return value of isSimpleBB
160 /// \p MBB - block to be duplicated
161 /// \p ForcedLayoutPred - If non-null, treat this block as the layout
162 ///     predecessor, instead of using the ordering in MF
163 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
164 ///     all Preds that received a copy of \p MBB.
165 /// \p RemovalCallback - if non-null, called just before MBB is deleted.
166 bool TailDuplicator::tailDuplicateAndUpdate(
167     bool IsSimple, MachineBasicBlock *MBB,
168     MachineBasicBlock *ForcedLayoutPred,
169     SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
170     function_ref<void(MachineBasicBlock *)> *RemovalCallback,
171     SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
172   // Save the successors list.
173   SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
174                                                MBB->succ_end());
175 
176   SmallVector<MachineBasicBlock *, 8> TDBBs;
177   SmallVector<MachineInstr *, 16> Copies;
178   if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
179                      TDBBs, Copies, CandidatePtr))
180     return false;
181 
182   ++NumTails;
183 
184   SmallVector<MachineInstr *, 8> NewPHIs;
185   MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
186 
187   // TailBB's immediate successors are now successors of those predecessors
188   // which duplicated TailBB. Add the predecessors as sources to the PHI
189   // instructions.
190   bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
191   if (PreRegAlloc)
192     updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
193 
194   // If it is dead, remove it.
195   if (isDead) {
196     NumTailDupRemoved += MBB->size();
197     removeDeadBlock(MBB, RemovalCallback);
198     ++NumDeadBlocks;
199   }
200 
201   // Update SSA form.
202   if (!SSAUpdateVRs.empty()) {
203     for (unsigned VReg : SSAUpdateVRs) {
204       SSAUpdate.Initialize(VReg);
205 
206       // If the original definition is still around, add it as an available
207       // value.
208       MachineInstr *DefMI = MRI->getVRegDef(VReg);
209       MachineBasicBlock *DefBB = nullptr;
210       if (DefMI) {
211         DefBB = DefMI->getParent();
212         SSAUpdate.AddAvailableValue(DefBB, VReg);
213       }
214 
215       // Add the new vregs as available values.
216       DenseMap<Register, AvailableValsTy>::iterator LI =
217           SSAUpdateVals.find(VReg);
218       for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
219         MachineBasicBlock *SrcBB = J.first;
220         Register SrcReg = J.second;
221         SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
222       }
223 
224       SmallVector<MachineOperand *> DebugUses;
225       // Rewrite uses that are outside of the original def's block.
226       for (MachineOperand &UseMO :
227            llvm::make_early_inc_range(MRI->use_operands(VReg))) {
228         MachineInstr *UseMI = UseMO.getParent();
229         // Rewrite debug uses last so that they can take advantage of any
230         // register mappings introduced by other users in its BB, since we
231         // cannot create new register definitions specifically for the debug
232         // instruction (as debug instructions should not affect CodeGen).
233         if (UseMI->isDebugValue()) {
234           DebugUses.push_back(&UseMO);
235           continue;
236         }
237         if (UseMI->getParent() == DefBB && !UseMI->isPHI())
238           continue;
239         SSAUpdate.RewriteUse(UseMO);
240       }
241       for (auto *UseMO : DebugUses) {
242         MachineInstr *UseMI = UseMO->getParent();
243         UseMO->setReg(
244             SSAUpdate.GetValueInMiddleOfBlock(UseMI->getParent(), true));
245       }
246     }
247 
248     SSAUpdateVRs.clear();
249     SSAUpdateVals.clear();
250   }
251 
252   // Eliminate some of the copies inserted by tail duplication to maintain
253   // SSA form.
254   for (MachineInstr *Copy : Copies) {
255     if (!Copy->isCopy())
256       continue;
257     Register Dst = Copy->getOperand(0).getReg();
258     Register Src = Copy->getOperand(1).getReg();
259     if (MRI->hasOneNonDBGUse(Src) &&
260         MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
261       // Copy is the only use. Do trivial copy propagation here.
262       MRI->replaceRegWith(Dst, Src);
263       Copy->eraseFromParent();
264     }
265   }
266 
267   if (NewPHIs.size())
268     NumAddedPHIs += NewPHIs.size();
269 
270   if (DuplicatedPreds)
271     *DuplicatedPreds = std::move(TDBBs);
272 
273   return true;
274 }
275 
276 /// Look for small blocks that are unconditionally branched to and do not fall
277 /// through. Tail-duplicate their instructions into their predecessors to
278 /// eliminate (dynamic) branches.
279 bool TailDuplicator::tailDuplicateBlocks() {
280   bool MadeChange = false;
281 
282   if (PreRegAlloc && TailDupVerify) {
283     LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
284     VerifyPHIs(*MF, true);
285   }
286 
287   for (MachineBasicBlock &MBB :
288        llvm::make_early_inc_range(llvm::drop_begin(*MF))) {
289     if (NumTails == TailDupLimit)
290       break;
291 
292     bool IsSimple = isSimpleBB(&MBB);
293 
294     if (!shouldTailDuplicate(IsSimple, MBB))
295       continue;
296 
297     MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr);
298   }
299 
300   if (PreRegAlloc && TailDupVerify)
301     VerifyPHIs(*MF, false);
302 
303   return MadeChange;
304 }
305 
306 static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB,
307                          const MachineRegisterInfo *MRI) {
308   for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
309     if (UseMI.isDebugValue())
310       continue;
311     if (UseMI.getParent() != BB)
312       return true;
313   }
314   return false;
315 }
316 
317 static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
318   for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
319     if (MI->getOperand(i + 1).getMBB() == SrcBB)
320       return i;
321   return 0;
322 }
323 
324 // Remember which registers are used by phis in this block. This is
325 // used to determine which registers are liveout while modifying the
326 // block (which is why we need to copy the information).
327 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
328                               DenseSet<Register> *UsedByPhi) {
329   for (const auto &MI : BB) {
330     if (!MI.isPHI())
331       break;
332     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
333       Register SrcReg = MI.getOperand(i).getReg();
334       UsedByPhi->insert(SrcReg);
335     }
336   }
337 }
338 
339 /// Add a definition and source virtual registers pair for SSA update.
340 void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
341                                        MachineBasicBlock *BB) {
342   DenseMap<Register, AvailableValsTy>::iterator LI =
343       SSAUpdateVals.find(OrigReg);
344   if (LI != SSAUpdateVals.end())
345     LI->second.push_back(std::make_pair(BB, NewReg));
346   else {
347     AvailableValsTy Vals;
348     Vals.push_back(std::make_pair(BB, NewReg));
349     SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
350     SSAUpdateVRs.push_back(OrigReg);
351   }
352 }
353 
354 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
355 /// source register that's contributed by PredBB and update SSA update map.
356 void TailDuplicator::processPHI(
357     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
358     DenseMap<Register, RegSubRegPair> &LocalVRMap,
359     SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
360     const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
361   Register DefReg = MI->getOperand(0).getReg();
362   unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
363   assert(SrcOpIdx && "Unable to find matching PHI source?");
364   Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
365   unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
366   const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
367   LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
368 
369   // Insert a copy from source to the end of the block. The def register is the
370   // available value liveout of the block.
371   Register NewDef = MRI->createVirtualRegister(RC);
372   Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
373   if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
374     addSSAUpdateEntry(DefReg, NewDef, PredBB);
375 
376   if (!Remove)
377     return;
378 
379   // Remove PredBB from the PHI node.
380   MI->removeOperand(SrcOpIdx + 1);
381   MI->removeOperand(SrcOpIdx);
382   if (MI->getNumOperands() == 1 && !TailBB->hasAddressTaken())
383     MI->eraseFromParent();
384   else if (MI->getNumOperands() == 1)
385     MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
386 }
387 
388 /// Duplicate a TailBB instruction to PredBB and update
389 /// the source operands due to earlier PHI translation.
390 void TailDuplicator::duplicateInstruction(
391     MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
392     DenseMap<Register, RegSubRegPair> &LocalVRMap,
393     const DenseSet<Register> &UsedByPhi) {
394   // Allow duplication of CFI instructions.
395   if (MI->isCFIInstruction()) {
396     BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
397             TII->get(TargetOpcode::CFI_INSTRUCTION))
398         .addCFIIndex(MI->getOperand(0).getCFIIndex())
399         .setMIFlags(MI->getFlags());
400     return;
401   }
402   MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
403   if (PreRegAlloc) {
404     for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
405       MachineOperand &MO = NewMI.getOperand(i);
406       if (!MO.isReg())
407         continue;
408       Register Reg = MO.getReg();
409       if (!Reg.isVirtual())
410         continue;
411       if (MO.isDef()) {
412         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
413         Register NewReg = MRI->createVirtualRegister(RC);
414         MO.setReg(NewReg);
415         LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
416         if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
417           addSSAUpdateEntry(Reg, NewReg, PredBB);
418       } else {
419         auto VI = LocalVRMap.find(Reg);
420         if (VI != LocalVRMap.end()) {
421           // Need to make sure that the register class of the mapped register
422           // will satisfy the constraints of the class of the register being
423           // replaced.
424           auto *OrigRC = MRI->getRegClass(Reg);
425           auto *MappedRC = MRI->getRegClass(VI->second.Reg);
426           const TargetRegisterClass *ConstrRC;
427           if (VI->second.SubReg != 0) {
428             ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
429                                                      VI->second.SubReg);
430             if (ConstrRC) {
431               // The actual constraining (as in "find appropriate new class")
432               // is done by getMatchingSuperRegClass, so now we only need to
433               // change the class of the mapped register.
434               MRI->setRegClass(VI->second.Reg, ConstrRC);
435             }
436           } else {
437             // For mapped registers that do not have sub-registers, simply
438             // restrict their class to match the original one.
439 
440             // We don't want debug instructions affecting the resulting code so
441             // if we're cloning a debug instruction then just use MappedRC
442             // rather than constraining the register class further.
443             ConstrRC = NewMI.isDebugInstr()
444                            ? MappedRC
445                            : MRI->constrainRegClass(VI->second.Reg, OrigRC);
446           }
447 
448           if (ConstrRC) {
449             // If the class constraining succeeded, we can simply replace
450             // the old register with the mapped one.
451             MO.setReg(VI->second.Reg);
452             // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
453             // sub-register, we need to compose the sub-register indices.
454             MO.setSubReg(
455                 TRI->composeSubRegIndices(VI->second.SubReg, MO.getSubReg()));
456           } else {
457             // The direct replacement is not possible, due to failing register
458             // class constraints. An explicit COPY is necessary. Create one
459             // that can be reused.
460             Register NewReg = MRI->createVirtualRegister(OrigRC);
461             BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
462                     TII->get(TargetOpcode::COPY), NewReg)
463                 .addReg(VI->second.Reg, 0, VI->second.SubReg);
464             LocalVRMap.erase(VI);
465             LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
466             MO.setReg(NewReg);
467             // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
468             // is equivalent to the whole register Reg. Hence, Reg:subreg
469             // is same as NewReg:subreg, so keep the sub-register index
470             // unchanged.
471           }
472           // Clear any kill flags from this operand.  The new register could
473           // have uses after this one, so kills are not valid here.
474           MO.setIsKill(false);
475         }
476       }
477     }
478   }
479 }
480 
481 /// After FromBB is tail duplicated into its predecessor blocks, the successors
482 /// have gained new predecessors. Update the PHI instructions in them
483 /// accordingly.
484 void TailDuplicator::updateSuccessorsPHIs(
485     MachineBasicBlock *FromBB, bool isDead,
486     SmallVectorImpl<MachineBasicBlock *> &TDBBs,
487     SmallSetVector<MachineBasicBlock *, 8> &Succs) {
488   for (MachineBasicBlock *SuccBB : Succs) {
489     for (MachineInstr &MI : *SuccBB) {
490       if (!MI.isPHI())
491         break;
492       MachineInstrBuilder MIB(*FromBB->getParent(), MI);
493       unsigned Idx = 0;
494       for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
495         MachineOperand &MO = MI.getOperand(i + 1);
496         if (MO.getMBB() == FromBB) {
497           Idx = i;
498           break;
499         }
500       }
501 
502       assert(Idx != 0);
503       MachineOperand &MO0 = MI.getOperand(Idx);
504       Register Reg = MO0.getReg();
505       if (isDead) {
506         // Folded into the previous BB.
507         // There could be duplicate phi source entries. FIXME: Should sdisel
508         // or earlier pass fixed this?
509         for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
510           MachineOperand &MO = MI.getOperand(i + 1);
511           if (MO.getMBB() == FromBB) {
512             MI.removeOperand(i + 1);
513             MI.removeOperand(i);
514           }
515         }
516       } else
517         Idx = 0;
518 
519       // If Idx is set, the operands at Idx and Idx+1 must be removed.
520       // We reuse the location to avoid expensive removeOperand calls.
521 
522       DenseMap<Register, AvailableValsTy>::iterator LI =
523           SSAUpdateVals.find(Reg);
524       if (LI != SSAUpdateVals.end()) {
525         // This register is defined in the tail block.
526         for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
527           MachineBasicBlock *SrcBB = J.first;
528           // If we didn't duplicate a bb into a particular predecessor, we
529           // might still have added an entry to SSAUpdateVals to correcly
530           // recompute SSA. If that case, avoid adding a dummy extra argument
531           // this PHI.
532           if (!SrcBB->isSuccessor(SuccBB))
533             continue;
534 
535           Register SrcReg = J.second;
536           if (Idx != 0) {
537             MI.getOperand(Idx).setReg(SrcReg);
538             MI.getOperand(Idx + 1).setMBB(SrcBB);
539             Idx = 0;
540           } else {
541             MIB.addReg(SrcReg).addMBB(SrcBB);
542           }
543         }
544       } else {
545         // Live in tail block, must also be live in predecessors.
546         for (MachineBasicBlock *SrcBB : TDBBs) {
547           if (Idx != 0) {
548             MI.getOperand(Idx).setReg(Reg);
549             MI.getOperand(Idx + 1).setMBB(SrcBB);
550             Idx = 0;
551           } else {
552             MIB.addReg(Reg).addMBB(SrcBB);
553           }
554         }
555       }
556       if (Idx != 0) {
557         MI.removeOperand(Idx + 1);
558         MI.removeOperand(Idx);
559       }
560     }
561   }
562 }
563 
564 /// Determine if it is profitable to duplicate this block.
565 bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
566                                          MachineBasicBlock &TailBB) {
567   // When doing tail-duplication during layout, the block ordering is in flux,
568   // so canFallThrough returns a result based on incorrect information and
569   // should just be ignored.
570   if (!LayoutMode && TailBB.canFallThrough())
571     return false;
572 
573   // Don't try to tail-duplicate single-block loops.
574   if (TailBB.isSuccessor(&TailBB))
575     return false;
576 
577   // Duplicating a BB which has both multiple predecessors and successors will
578   // result in a complex CFG and also may cause huge amount of PHI nodes. If we
579   // want to remove this limitation, we have to address
580   // https://github.com/llvm/llvm-project/issues/78578.
581   if (TailBB.pred_size() > TailDupPredSize &&
582       TailBB.succ_size() > TailDupSuccSize)
583     return false;
584 
585   // Set the limit on the cost to duplicate. When optimizing for size,
586   // duplicate only one, because one branch instruction can be eliminated to
587   // compensate for the duplication.
588   unsigned MaxDuplicateCount;
589   if (TailDupSize == 0)
590     MaxDuplicateCount = TailDuplicateSize;
591   else
592     MaxDuplicateCount = TailDupSize;
593   if (llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI))
594     MaxDuplicateCount = 1;
595 
596   // If the block to be duplicated ends in an unanalyzable fallthrough, don't
597   // duplicate it.
598   // A similar check is necessary in MachineBlockPlacement to make sure pairs of
599   // blocks with unanalyzable fallthrough get layed out contiguously.
600   MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
601   SmallVector<MachineOperand, 4> PredCond;
602   if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
603       TailBB.canFallThrough())
604     return false;
605 
606   // If the target has hardware branch prediction that can handle indirect
607   // branches, duplicating them can often make them predictable when there
608   // are common paths through the code.  The limit needs to be high enough
609   // to allow undoing the effects of tail merging and other optimizations
610   // that rearrange the predecessors of the indirect branch.
611 
612   bool HasIndirectbr = false;
613   if (!TailBB.empty())
614     HasIndirectbr = TailBB.back().isIndirectBranch();
615 
616   if (HasIndirectbr && PreRegAlloc)
617     MaxDuplicateCount = TailDupIndirectBranchSize;
618 
619   // Check the instructions in the block to determine whether tail-duplication
620   // is invalid or unlikely to be profitable.
621   unsigned InstrCount = 0;
622   for (MachineInstr &MI : TailBB) {
623     // Non-duplicable things shouldn't be tail-duplicated.
624     // CFI instructions are marked as non-duplicable, because Darwin compact
625     // unwind info emission can't handle multiple prologue setups. In case of
626     // DWARF, allow them be duplicated, so that their existence doesn't prevent
627     // tail duplication of some basic blocks, that would be duplicated otherwise.
628     if (MI.isNotDuplicable() &&
629         (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
630         !MI.isCFIInstruction()))
631       return false;
632 
633     // Convergent instructions can be duplicated only if doing so doesn't add
634     // new control dependencies, which is what we're going to do here.
635     if (MI.isConvergent())
636       return false;
637 
638     // Do not duplicate 'return' instructions if this is a pre-regalloc run.
639     // A return may expand into a lot more instructions (e.g. reload of callee
640     // saved registers) after PEI.
641     if (PreRegAlloc && MI.isReturn())
642       return false;
643 
644     // Avoid duplicating calls before register allocation. Calls presents a
645     // barrier to register allocation so duplicating them may end up increasing
646     // spills.
647     if (PreRegAlloc && MI.isCall())
648       return false;
649 
650     // TailDuplicator::appendCopies will erroneously place COPYs after
651     // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same
652     // bug that was fixed in f7a53d82c090.
653     // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point
654     //        for the COPY when replacing PHIs.
655     if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
656       return false;
657 
658     if (MI.isBundle())
659       InstrCount += MI.getBundleSize();
660     else if (!MI.isPHI() && !MI.isMetaInstruction())
661       InstrCount += 1;
662 
663     if (InstrCount > MaxDuplicateCount)
664       return false;
665   }
666 
667   // Check if any of the successors of TailBB has a PHI node in which the
668   // value corresponding to TailBB uses a subregister.
669   // If a phi node uses a register paired with a subregister, the actual
670   // "value type" of the phi may differ from the type of the register without
671   // any subregisters. Due to a bug, tail duplication may add a new operand
672   // without a necessary subregister, producing an invalid code. This is
673   // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
674   // Disable tail duplication for this case for now, until the problem is
675   // fixed.
676   for (auto *SB : TailBB.successors()) {
677     for (auto &I : *SB) {
678       if (!I.isPHI())
679         break;
680       unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
681       assert(Idx != 0);
682       MachineOperand &PU = I.getOperand(Idx);
683       if (PU.getSubReg() != 0)
684         return false;
685     }
686   }
687 
688   if (HasIndirectbr && PreRegAlloc)
689     return true;
690 
691   if (IsSimple)
692     return true;
693 
694   if (!PreRegAlloc)
695     return true;
696 
697   return canCompletelyDuplicateBB(TailBB);
698 }
699 
700 /// True if this BB has only one unconditional jump.
701 bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
702   if (TailBB->succ_size() != 1)
703     return false;
704   if (TailBB->pred_empty())
705     return false;
706   MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(true);
707   if (I == TailBB->end())
708     return true;
709   return I->isUnconditionalBranch();
710 }
711 
712 static bool bothUsedInPHI(const MachineBasicBlock &A,
713                           const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
714   for (MachineBasicBlock *BB : A.successors())
715     if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
716       return true;
717 
718   return false;
719 }
720 
721 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
722   for (MachineBasicBlock *PredBB : BB.predecessors()) {
723     if (PredBB->succ_size() > 1)
724       return false;
725 
726     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
727     SmallVector<MachineOperand, 4> PredCond;
728     if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
729       return false;
730 
731     if (!PredCond.empty())
732       return false;
733   }
734   return true;
735 }
736 
737 bool TailDuplicator::duplicateSimpleBB(
738     MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
739     const DenseSet<Register> &UsedByPhi) {
740   SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
741                                             TailBB->succ_end());
742   SmallVector<MachineBasicBlock *, 8> Preds(TailBB->predecessors());
743   bool Changed = false;
744   for (MachineBasicBlock *PredBB : Preds) {
745     if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
746       continue;
747 
748     if (bothUsedInPHI(*PredBB, Succs))
749       continue;
750 
751     MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
752     SmallVector<MachineOperand, 4> PredCond;
753     if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
754       continue;
755 
756     Changed = true;
757     LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
758                       << "From simple Succ: " << *TailBB);
759 
760     MachineBasicBlock *NewTarget = *TailBB->succ_begin();
761     MachineBasicBlock *NextBB = PredBB->getNextNode();
762 
763     // Make PredFBB explicit.
764     if (PredCond.empty())
765       PredFBB = PredTBB;
766 
767     // Make fall through explicit.
768     if (!PredTBB)
769       PredTBB = NextBB;
770     if (!PredFBB)
771       PredFBB = NextBB;
772 
773     // Redirect
774     if (PredFBB == TailBB)
775       PredFBB = NewTarget;
776     if (PredTBB == TailBB)
777       PredTBB = NewTarget;
778 
779     // Make the branch unconditional if possible
780     if (PredTBB == PredFBB) {
781       PredCond.clear();
782       PredFBB = nullptr;
783     }
784 
785     // Avoid adding fall through branches.
786     if (PredFBB == NextBB)
787       PredFBB = nullptr;
788     if (PredTBB == NextBB && PredFBB == nullptr)
789       PredTBB = nullptr;
790 
791     auto DL = PredBB->findBranchDebugLoc();
792     TII->removeBranch(*PredBB);
793 
794     if (!PredBB->isSuccessor(NewTarget))
795       PredBB->replaceSuccessor(TailBB, NewTarget);
796     else {
797       PredBB->removeSuccessor(TailBB, true);
798       assert(PredBB->succ_size() <= 1);
799     }
800 
801     if (PredTBB)
802       TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
803 
804     TDBBs.push_back(PredBB);
805   }
806   return Changed;
807 }
808 
809 bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
810                                       MachineBasicBlock *PredBB) {
811   // EH edges are ignored by analyzeBranch.
812   if (PredBB->succ_size() > 1)
813     return false;
814 
815   MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
816   SmallVector<MachineOperand, 4> PredCond;
817   if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
818     return false;
819   if (!PredCond.empty())
820     return false;
821   // FIXME: This is overly conservative; it may be ok to relax this in the
822   // future under more specific conditions. If TailBB is an INLINEASM_BR
823   // indirect target, we need to see if the edge from PredBB to TailBB is from
824   // an INLINEASM_BR in PredBB, and then also if that edge was from the
825   // indirect target list, fallthrough/default target, or potentially both. If
826   // it's both, TailDuplicator::tailDuplicate will remove the edge, corrupting
827   // the successor list in PredBB and predecessor list in TailBB.
828   if (TailBB->isInlineAsmBrIndirectTarget())
829     return false;
830   return true;
831 }
832 
833 /// If it is profitable, duplicate TailBB's contents in each
834 /// of its predecessors.
835 /// \p IsSimple result of isSimpleBB
836 /// \p TailBB   Block to be duplicated.
837 /// \p ForcedLayoutPred  When non-null, use this block as the layout predecessor
838 ///                      instead of the previous block in MF's order.
839 /// \p TDBBs             A vector to keep track of all blocks tail-duplicated
840 ///                      into.
841 /// \p Copies            A vector of copy instructions inserted. Used later to
842 ///                      walk all the inserted copies and remove redundant ones.
843 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
844                           MachineBasicBlock *ForcedLayoutPred,
845                           SmallVectorImpl<MachineBasicBlock *> &TDBBs,
846                           SmallVectorImpl<MachineInstr *> &Copies,
847                           SmallVectorImpl<MachineBasicBlock *> *CandidatePtr) {
848   LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
849                     << '\n');
850 
851   bool ShouldUpdateTerminators = TailBB->canFallThrough();
852 
853   DenseSet<Register> UsedByPhi;
854   getRegsUsedByPHIs(*TailBB, &UsedByPhi);
855 
856   if (IsSimple)
857     return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi);
858 
859   // Iterate through all the unique predecessors and tail-duplicate this
860   // block into them, if possible. Copying the list ahead of time also
861   // avoids trouble with the predecessor list reallocating.
862   bool Changed = false;
863   SmallSetVector<MachineBasicBlock *, 8> Preds;
864   if (CandidatePtr)
865     Preds.insert(CandidatePtr->begin(), CandidatePtr->end());
866   else
867     Preds.insert(TailBB->pred_begin(), TailBB->pred_end());
868 
869   for (MachineBasicBlock *PredBB : Preds) {
870     assert(TailBB != PredBB &&
871            "Single-block loop should have been rejected earlier!");
872 
873     if (!canTailDuplicate(TailBB, PredBB))
874       continue;
875 
876     // Don't duplicate into a fall-through predecessor (at least for now).
877     // If profile is available, findDuplicateCandidates can choose better
878     // fall-through predecessor.
879     if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
880       bool IsLayoutSuccessor = false;
881       if (ForcedLayoutPred)
882         IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
883       else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
884         IsLayoutSuccessor = true;
885       if (IsLayoutSuccessor)
886         continue;
887     }
888 
889     LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
890                       << "From Succ: " << *TailBB);
891 
892     TDBBs.push_back(PredBB);
893 
894     // Remove PredBB's unconditional branch.
895     TII->removeBranch(*PredBB);
896 
897     // Clone the contents of TailBB into PredBB.
898     DenseMap<Register, RegSubRegPair> LocalVRMap;
899     SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
900     for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) {
901       if (MI.isPHI()) {
902         // Replace the uses of the def of the PHI with the register coming
903         // from PredBB.
904         processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
905       } else {
906         // Replace def of virtual registers with new registers, and update
907         // uses with PHI source register or the new registers.
908         duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
909       }
910     }
911     appendCopies(PredBB, CopyInfos, Copies);
912 
913     NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
914 
915     // Update the CFG.
916     PredBB->removeSuccessor(PredBB->succ_begin());
917     assert(PredBB->succ_empty() &&
918            "TailDuplicate called on block with multiple successors!");
919     for (MachineBasicBlock *Succ : TailBB->successors())
920       PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
921 
922     // Update branches in pred to jump to tail's layout successor if needed.
923     if (ShouldUpdateTerminators)
924       PredBB->updateTerminator(TailBB->getNextNode());
925 
926     Changed = true;
927     ++NumTailDups;
928   }
929 
930   // If TailBB was duplicated into all its predecessors except for the prior
931   // block, which falls through unconditionally, move the contents of this
932   // block into the prior block.
933   MachineBasicBlock *PrevBB = ForcedLayoutPred;
934   if (!PrevBB)
935     PrevBB = &*std::prev(TailBB->getIterator());
936   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
937   SmallVector<MachineOperand, 4> PriorCond;
938   // This has to check PrevBB->succ_size() because EH edges are ignored by
939   // analyzeBranch.
940   if (PrevBB->succ_size() == 1 &&
941       // Layout preds are not always CFG preds. Check.
942       *PrevBB->succ_begin() == TailBB &&
943       !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
944       PriorCond.empty() &&
945       (!PriorTBB || PriorTBB == TailBB) &&
946       TailBB->pred_size() == 1 &&
947       !TailBB->hasAddressTaken()) {
948     LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
949                       << "From MBB: " << *TailBB);
950     // There may be a branch to the layout successor. This is unlikely but it
951     // happens. The correct thing to do is to remove the branch before
952     // duplicating the instructions in all cases.
953     bool RemovedBranches = TII->removeBranch(*PrevBB) != 0;
954 
955     // If there are still tail instructions, abort the merge
956     if (PrevBB->getFirstTerminator() == PrevBB->end()) {
957       if (PreRegAlloc) {
958         DenseMap<Register, RegSubRegPair> LocalVRMap;
959         SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
960         MachineBasicBlock::iterator I = TailBB->begin();
961         // Process PHI instructions first.
962         while (I != TailBB->end() && I->isPHI()) {
963           // Replace the uses of the def of the PHI with the register coming
964           // from PredBB.
965           MachineInstr *MI = &*I++;
966           processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
967                      true);
968         }
969 
970         // Now copy the non-PHI instructions.
971         while (I != TailBB->end()) {
972           // Replace def of virtual registers with new registers, and update
973           // uses with PHI source register or the new registers.
974           MachineInstr *MI = &*I++;
975           assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
976           duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
977           MI->eraseFromParent();
978         }
979         appendCopies(PrevBB, CopyInfos, Copies);
980       } else {
981         TII->removeBranch(*PrevBB);
982         // No PHIs to worry about, just splice the instructions over.
983         PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
984       }
985       PrevBB->removeSuccessor(PrevBB->succ_begin());
986       assert(PrevBB->succ_empty());
987       PrevBB->transferSuccessors(TailBB);
988 
989       // Update branches in PrevBB based on Tail's layout successor.
990       if (ShouldUpdateTerminators)
991         PrevBB->updateTerminator(TailBB->getNextNode());
992 
993       TDBBs.push_back(PrevBB);
994       Changed = true;
995     } else {
996       LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
997                            "contains terminator instructions");
998       // Return early if no changes were made
999       if (!Changed)
1000         return RemovedBranches;
1001     }
1002     Changed |= RemovedBranches;
1003   }
1004 
1005   // If this is after register allocation, there are no phis to fix.
1006   if (!PreRegAlloc)
1007     return Changed;
1008 
1009   // If we made no changes so far, we are safe.
1010   if (!Changed)
1011     return Changed;
1012 
1013   // Handle the nasty case in that we duplicated a block that is part of a loop
1014   // into some but not all of its predecessors. For example:
1015   //    1 -> 2 <-> 3                 |
1016   //          \                      |
1017   //           \---> rest            |
1018   // if we duplicate 2 into 1 but not into 3, we end up with
1019   // 12 -> 3 <-> 2 -> rest           |
1020   //   \             /               |
1021   //    \----->-----/                |
1022   // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
1023   // with a phi in 3 (which now dominates 2).
1024   // What we do here is introduce a copy in 3 of the register defined by the
1025   // phi, just like when we are duplicating 2 into 3, but we don't copy any
1026   // real instructions or remove the 3 -> 2 edge from the phi in 2.
1027   for (MachineBasicBlock *PredBB : Preds) {
1028     if (is_contained(TDBBs, PredBB))
1029       continue;
1030 
1031     // EH edges
1032     if (PredBB->succ_size() != 1)
1033       continue;
1034 
1035     DenseMap<Register, RegSubRegPair> LocalVRMap;
1036     SmallVector<std::pair<Register, RegSubRegPair>, 4> CopyInfos;
1037     // Process PHI instructions first.
1038     for (MachineInstr &MI : make_early_inc_range(TailBB->phis())) {
1039       // Replace the uses of the def of the PHI with the register coming
1040       // from PredBB.
1041       processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
1042     }
1043     appendCopies(PredBB, CopyInfos, Copies);
1044   }
1045 
1046   return Changed;
1047 }
1048 
1049 /// At the end of the block \p MBB generate COPY instructions between registers
1050 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
1051 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
1052       SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
1053       SmallVectorImpl<MachineInstr*> &Copies) {
1054   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1055   const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
1056   for (auto &CI : CopyInfos) {
1057     auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
1058                 .addReg(CI.second.Reg, 0, CI.second.SubReg);
1059     Copies.push_back(C);
1060   }
1061 }
1062 
1063 /// Remove the specified dead machine basic block from the function, updating
1064 /// the CFG.
1065 void TailDuplicator::removeDeadBlock(
1066     MachineBasicBlock *MBB,
1067     function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1068   assert(MBB->pred_empty() && "MBB must be dead!");
1069   LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1070 
1071   MachineFunction *MF = MBB->getParent();
1072   // Update the call site info.
1073   for (const MachineInstr &MI : *MBB)
1074     if (MI.shouldUpdateCallSiteInfo())
1075       MF->eraseCallSiteInfo(&MI);
1076 
1077   if (RemovalCallback)
1078     (*RemovalCallback)(MBB);
1079 
1080   // Remove all successors.
1081   while (!MBB->succ_empty())
1082     MBB->removeSuccessor(MBB->succ_end() - 1);
1083 
1084   // Remove the block.
1085   MBB->eraseFromParent();
1086 }
1087