LLVM  10.0.0
TailDuplicator.cpp
Go to the documentation of this file.
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 
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"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Function.h"
39 #include "llvm/Support/Debug.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <iterator>
46 #include <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "tailduplication"
51 
52 STATISTIC(NumTails, "Number of tails duplicated");
53 STATISTIC(NumTailDups, "Number of tail duplicated blocks");
54 STATISTIC(NumTailDupAdded,
55  "Number of instructions added due to tail duplication");
56 STATISTIC(NumTailDupRemoved,
57  "Number of instructions removed due to tail duplication");
58 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
59 STATISTIC(NumAddedPHIs, "Number of phis added");
60 
61 // Heuristic for tail duplication.
63  "tail-dup-size",
64  cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
65  cl::Hidden);
66 
68  "tail-dup-indirect-size",
69  cl::desc("Maximum instructions to consider tail duplicating blocks that "
70  "end with indirect branches."), cl::init(20),
71  cl::Hidden);
72 
73 static cl::opt<bool>
74  TailDupVerify("tail-dup-verify",
75  cl::desc("Verify sanity of PHI instructions during taildup"),
76  cl::init(false), cl::Hidden);
77 
78 static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
79  cl::Hidden);
80 
81 void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
82  const MachineBranchProbabilityInfo *MBPIin,
83  const MachineBlockFrequencyInfo *MBFIin,
84  ProfileSummaryInfo *PSIin,
85  bool LayoutModeIn, unsigned TailDupSizeIn) {
86  MF = &MFin;
87  TII = MF->getSubtarget().getInstrInfo();
88  TRI = MF->getSubtarget().getRegisterInfo();
89  MRI = &MF->getRegInfo();
90  MMI = &MF->getMMI();
91  MBPI = MBPIin;
92  MBFI = MBFIin;
93  PSI = PSIin;
94  TailDupSize = TailDupSizeIn;
95 
96  assert(MBPI != nullptr && "Machine Branch Probability Info required");
97 
98  LayoutMode = LayoutModeIn;
99  this->PreRegAlloc = PreRegAlloc;
100 }
101 
102 static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
103  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
104  MachineBasicBlock *MBB = &*I;
106  MBB->pred_end());
108  while (MI != MBB->end()) {
109  if (!MI->isPHI())
110  break;
111  for (MachineBasicBlock *PredBB : Preds) {
112  bool Found = false;
113  for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
114  MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
115  if (PHIBB == PredBB) {
116  Found = true;
117  break;
118  }
119  }
120  if (!Found) {
121  dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
122  << *MI;
123  dbgs() << " missing input from predecessor "
124  << printMBBReference(*PredBB) << '\n';
125  llvm_unreachable(nullptr);
126  }
127  }
128 
129  for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
130  MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
131  if (CheckExtra && !Preds.count(PHIBB)) {
132  dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
133  << ": " << *MI;
134  dbgs() << " extra input from predecessor "
135  << printMBBReference(*PHIBB) << '\n';
136  llvm_unreachable(nullptr);
137  }
138  if (PHIBB->getNumber() < 0) {
139  dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
140  << *MI;
141  dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
142  llvm_unreachable(nullptr);
143  }
144  }
145  ++MI;
146  }
147  }
148 }
149 
150 /// Tail duplicate the block and cleanup.
151 /// \p IsSimple - return value of isSimpleBB
152 /// \p MBB - block to be duplicated
153 /// \p ForcedLayoutPred - If non-null, treat this block as the layout
154 /// predecessor, instead of using the ordering in MF
155 /// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
156 /// all Preds that received a copy of \p MBB.
157 /// \p RemovalCallback - if non-null, called just before MBB is deleted.
159  bool IsSimple, MachineBasicBlock *MBB,
160  MachineBasicBlock *ForcedLayoutPred,
161  SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
162  function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
163  // Save the successors list.
165  MBB->succ_end());
166 
169  if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
170  return false;
171 
172  ++NumTails;
173 
175  MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
176 
177  // TailBB's immediate successors are now successors of those predecessors
178  // which duplicated TailBB. Add the predecessors as sources to the PHI
179  // instructions.
180  bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
181  if (PreRegAlloc)
182  updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
183 
184  // If it is dead, remove it.
185  if (isDead) {
186  NumTailDupRemoved += MBB->size();
187  removeDeadBlock(MBB, RemovalCallback);
188  ++NumDeadBlocks;
189  }
190 
191  // Update SSA form.
192  if (!SSAUpdateVRs.empty()) {
193  for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
194  unsigned VReg = SSAUpdateVRs[i];
195  SSAUpdate.Initialize(VReg);
196 
197  // If the original definition is still around, add it as an available
198  // value.
199  MachineInstr *DefMI = MRI->getVRegDef(VReg);
200  MachineBasicBlock *DefBB = nullptr;
201  if (DefMI) {
202  DefBB = DefMI->getParent();
203  SSAUpdate.AddAvailableValue(DefBB, VReg);
204  }
205 
206  // Add the new vregs as available values.
208  SSAUpdateVals.find(VReg);
209  for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
210  MachineBasicBlock *SrcBB = LI->second[j].first;
211  unsigned SrcReg = LI->second[j].second;
212  SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
213  }
214 
215  // Rewrite uses that are outside of the original def's block.
217  while (UI != MRI->use_end()) {
218  MachineOperand &UseMO = *UI;
219  MachineInstr *UseMI = UseMO.getParent();
220  ++UI;
221  if (UseMI->isDebugValue()) {
222  // SSAUpdate can replace the use with an undef. That creates
223  // a debug instruction that is a kill.
224  // FIXME: Should it SSAUpdate job to delete debug instructions
225  // instead of replacing the use with undef?
226  UseMI->eraseFromParent();
227  continue;
228  }
229  if (UseMI->getParent() == DefBB && !UseMI->isPHI())
230  continue;
231  SSAUpdate.RewriteUse(UseMO);
232  }
233  }
234 
235  SSAUpdateVRs.clear();
236  SSAUpdateVals.clear();
237  }
238 
239  // Eliminate some of the copies inserted by tail duplication to maintain
240  // SSA form.
241  for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
242  MachineInstr *Copy = Copies[i];
243  if (!Copy->isCopy())
244  continue;
245  Register Dst = Copy->getOperand(0).getReg();
246  Register Src = Copy->getOperand(1).getReg();
247  if (MRI->hasOneNonDBGUse(Src) &&
248  MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
249  // Copy is the only use. Do trivial copy propagation here.
250  MRI->replaceRegWith(Dst, Src);
251  Copy->eraseFromParent();
252  }
253  }
254 
255  if (NewPHIs.size())
256  NumAddedPHIs += NewPHIs.size();
257 
258  if (DuplicatedPreds)
259  *DuplicatedPreds = std::move(TDBBs);
260 
261  return true;
262 }
263 
264 /// Look for small blocks that are unconditionally branched to and do not fall
265 /// through. Tail-duplicate their instructions into their predecessors to
266 /// eliminate (dynamic) branches.
268  bool MadeChange = false;
269 
270  if (PreRegAlloc && TailDupVerify) {
271  LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
272  VerifyPHIs(*MF, true);
273  }
274 
275  for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
276  MachineBasicBlock *MBB = &*I++;
277 
278  if (NumTails == TailDupLimit)
279  break;
280 
281  bool IsSimple = isSimpleBB(MBB);
282 
283  if (!shouldTailDuplicate(IsSimple, *MBB))
284  continue;
285 
286  MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
287  }
288 
289  if (PreRegAlloc && TailDupVerify)
290  VerifyPHIs(*MF, false);
291 
292  return MadeChange;
293 }
294 
295 static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
296  const MachineRegisterInfo *MRI) {
297  for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
298  if (UseMI.isDebugValue())
299  continue;
300  if (UseMI.getParent() != BB)
301  return true;
302  }
303  return false;
304 }
305 
307  for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
308  if (MI->getOperand(i + 1).getMBB() == SrcBB)
309  return i;
310  return 0;
311 }
312 
313 // Remember which registers are used by phis in this block. This is
314 // used to determine which registers are liveout while modifying the
315 // block (which is why we need to copy the information).
316 static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
317  DenseSet<unsigned> *UsedByPhi) {
318  for (const auto &MI : BB) {
319  if (!MI.isPHI())
320  break;
321  for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
322  Register SrcReg = MI.getOperand(i).getReg();
323  UsedByPhi->insert(SrcReg);
324  }
325  }
326 }
327 
328 /// Add a definition and source virtual registers pair for SSA update.
329 void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
330  MachineBasicBlock *BB) {
332  SSAUpdateVals.find(OrigReg);
333  if (LI != SSAUpdateVals.end())
334  LI->second.push_back(std::make_pair(BB, NewReg));
335  else {
336  AvailableValsTy Vals;
337  Vals.push_back(std::make_pair(BB, NewReg));
338  SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
339  SSAUpdateVRs.push_back(OrigReg);
340  }
341 }
342 
343 /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
344 /// source register that's contributed by PredBB and update SSA update map.
345 void TailDuplicator::processPHI(
348  SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
349  const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
350  Register DefReg = MI->getOperand(0).getReg();
351  unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
352  assert(SrcOpIdx && "Unable to find matching PHI source?");
353  Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
354  unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
355  const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
356  LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
357 
358  // Insert a copy from source to the end of the block. The def register is the
359  // available value liveout of the block.
360  Register NewDef = MRI->createVirtualRegister(RC);
361  Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
362  if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
363  addSSAUpdateEntry(DefReg, NewDef, PredBB);
364 
365  if (!Remove)
366  return;
367 
368  // Remove PredBB from the PHI node.
369  MI->RemoveOperand(SrcOpIdx + 1);
370  MI->RemoveOperand(SrcOpIdx);
371  if (MI->getNumOperands() == 1)
372  MI->eraseFromParent();
373 }
374 
375 /// Duplicate a TailBB instruction to PredBB and update
376 /// the source operands due to earlier PHI translation.
377 void TailDuplicator::duplicateInstruction(
378  MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
380  const DenseSet<unsigned> &UsedByPhi) {
381  // Allow duplication of CFI instructions.
382  if (MI->isCFIInstruction()) {
383  BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
384  TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
385  MI->getOperand(0).getCFIIndex());
386  return;
387  }
388  MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
389  if (PreRegAlloc) {
390  for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
391  MachineOperand &MO = NewMI.getOperand(i);
392  if (!MO.isReg())
393  continue;
394  Register Reg = MO.getReg();
395  if (!Register::isVirtualRegister(Reg))
396  continue;
397  if (MO.isDef()) {
398  const TargetRegisterClass *RC = MRI->getRegClass(Reg);
399  Register NewReg = MRI->createVirtualRegister(RC);
400  MO.setReg(NewReg);
401  LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
402  if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
403  addSSAUpdateEntry(Reg, NewReg, PredBB);
404  } else {
405  auto VI = LocalVRMap.find(Reg);
406  if (VI != LocalVRMap.end()) {
407  // Need to make sure that the register class of the mapped register
408  // will satisfy the constraints of the class of the register being
409  // replaced.
410  auto *OrigRC = MRI->getRegClass(Reg);
411  auto *MappedRC = MRI->getRegClass(VI->second.Reg);
412  const TargetRegisterClass *ConstrRC;
413  if (VI->second.SubReg != 0) {
414  ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
415  VI->second.SubReg);
416  if (ConstrRC) {
417  // The actual constraining (as in "find appropriate new class")
418  // is done by getMatchingSuperRegClass, so now we only need to
419  // change the class of the mapped register.
420  MRI->setRegClass(VI->second.Reg, ConstrRC);
421  }
422  } else {
423  // For mapped registers that do not have sub-registers, simply
424  // restrict their class to match the original one.
425  ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
426  }
427 
428  if (ConstrRC) {
429  // If the class constraining succeeded, we can simply replace
430  // the old register with the mapped one.
431  MO.setReg(VI->second.Reg);
432  // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
433  // sub-register, we need to compose the sub-register indices.
435  VI->second.SubReg));
436  } else {
437  // The direct replacement is not possible, due to failing register
438  // class constraints. An explicit COPY is necessary. Create one
439  // that can be reused
440  auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
441  if (NewRC == nullptr)
442  NewRC = OrigRC;
443  Register NewReg = MRI->createVirtualRegister(NewRC);
444  BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
445  TII->get(TargetOpcode::COPY), NewReg)
446  .addReg(VI->second.Reg, 0, VI->second.SubReg);
447  LocalVRMap.erase(VI);
448  LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
449  MO.setReg(NewReg);
450  // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
451  // is equivalent to the whole register Reg. Hence, Reg:subreg
452  // is same as NewReg:subreg, so keep the sub-register index
453  // unchanged.
454  }
455  // Clear any kill flags from this operand. The new register could
456  // have uses after this one, so kills are not valid here.
457  MO.setIsKill(false);
458  }
459  }
460  }
461  }
462 }
463 
464 /// After FromBB is tail duplicated into its predecessor blocks, the successors
465 /// have gained new predecessors. Update the PHI instructions in them
466 /// accordingly.
467 void TailDuplicator::updateSuccessorsPHIs(
468  MachineBasicBlock *FromBB, bool isDead,
471  for (MachineBasicBlock *SuccBB : Succs) {
472  for (MachineInstr &MI : *SuccBB) {
473  if (!MI.isPHI())
474  break;
475  MachineInstrBuilder MIB(*FromBB->getParent(), MI);
476  unsigned Idx = 0;
477  for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
478  MachineOperand &MO = MI.getOperand(i + 1);
479  if (MO.getMBB() == FromBB) {
480  Idx = i;
481  break;
482  }
483  }
484 
485  assert(Idx != 0);
486  MachineOperand &MO0 = MI.getOperand(Idx);
487  Register Reg = MO0.getReg();
488  if (isDead) {
489  // Folded into the previous BB.
490  // There could be duplicate phi source entries. FIXME: Should sdisel
491  // or earlier pass fixed this?
492  for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
493  MachineOperand &MO = MI.getOperand(i + 1);
494  if (MO.getMBB() == FromBB) {
495  MI.RemoveOperand(i + 1);
496  MI.RemoveOperand(i);
497  }
498  }
499  } else
500  Idx = 0;
501 
502  // If Idx is set, the operands at Idx and Idx+1 must be removed.
503  // We reuse the location to avoid expensive RemoveOperand calls.
504 
506  SSAUpdateVals.find(Reg);
507  if (LI != SSAUpdateVals.end()) {
508  // This register is defined in the tail block.
509  for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
510  MachineBasicBlock *SrcBB = LI->second[j].first;
511  // If we didn't duplicate a bb into a particular predecessor, we
512  // might still have added an entry to SSAUpdateVals to correcly
513  // recompute SSA. If that case, avoid adding a dummy extra argument
514  // this PHI.
515  if (!SrcBB->isSuccessor(SuccBB))
516  continue;
517 
518  unsigned SrcReg = LI->second[j].second;
519  if (Idx != 0) {
520  MI.getOperand(Idx).setReg(SrcReg);
521  MI.getOperand(Idx + 1).setMBB(SrcBB);
522  Idx = 0;
523  } else {
524  MIB.addReg(SrcReg).addMBB(SrcBB);
525  }
526  }
527  } else {
528  // Live in tail block, must also be live in predecessors.
529  for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
530  MachineBasicBlock *SrcBB = TDBBs[j];
531  if (Idx != 0) {
532  MI.getOperand(Idx).setReg(Reg);
533  MI.getOperand(Idx + 1).setMBB(SrcBB);
534  Idx = 0;
535  } else {
536  MIB.addReg(Reg).addMBB(SrcBB);
537  }
538  }
539  }
540  if (Idx != 0) {
541  MI.RemoveOperand(Idx + 1);
542  MI.RemoveOperand(Idx);
543  }
544  }
545  }
546 }
547 
548 /// Determine if it is profitable to duplicate this block.
550  MachineBasicBlock &TailBB) {
551  // When doing tail-duplication during layout, the block ordering is in flux,
552  // so canFallThrough returns a result based on incorrect information and
553  // should just be ignored.
554  if (!LayoutMode && TailBB.canFallThrough())
555  return false;
556 
557  // Don't try to tail-duplicate single-block loops.
558  if (TailBB.isSuccessor(&TailBB))
559  return false;
560 
561  // Set the limit on the cost to duplicate. When optimizing for size,
562  // duplicate only one, because one branch instruction can be eliminated to
563  // compensate for the duplication.
564  unsigned MaxDuplicateCount;
565  bool OptForSize = MF->getFunction().hasOptSize() ||
566  llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI);
567  if (TailDupSize == 0)
568  MaxDuplicateCount = TailDuplicateSize;
569  else
570  MaxDuplicateCount = TailDupSize;
571  if (OptForSize)
572  MaxDuplicateCount = 1;
573 
574  // If the block to be duplicated ends in an unanalyzable fallthrough, don't
575  // duplicate it.
576  // A similar check is necessary in MachineBlockPlacement to make sure pairs of
577  // blocks with unanalyzable fallthrough get layed out contiguously.
578  MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
580  if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
581  TailBB.canFallThrough())
582  return false;
583 
584  // If the target has hardware branch prediction that can handle indirect
585  // branches, duplicating them can often make them predictable when there
586  // are common paths through the code. The limit needs to be high enough
587  // to allow undoing the effects of tail merging and other optimizations
588  // that rearrange the predecessors of the indirect branch.
589 
590  bool HasIndirectbr = false;
591  if (!TailBB.empty())
592  HasIndirectbr = TailBB.back().isIndirectBranch();
593 
594  if (HasIndirectbr && PreRegAlloc)
595  MaxDuplicateCount = TailDupIndirectBranchSize;
596 
597  // Check the instructions in the block to determine whether tail-duplication
598  // is invalid or unlikely to be profitable.
599  unsigned InstrCount = 0;
600  for (MachineInstr &MI : TailBB) {
601  // Non-duplicable things shouldn't be tail-duplicated.
602  // CFI instructions are marked as non-duplicable, because Darwin compact
603  // unwind info emission can't handle multiple prologue setups. In case of
604  // DWARF, allow them be duplicated, so that their existence doesn't prevent
605  // tail duplication of some basic blocks, that would be duplicated otherwise.
606  if (MI.isNotDuplicable() &&
607  (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
608  !MI.isCFIInstruction()))
609  return false;
610 
611  // Convergent instructions can be duplicated only if doing so doesn't add
612  // new control dependencies, which is what we're going to do here.
613  if (MI.isConvergent())
614  return false;
615 
616  // Do not duplicate 'return' instructions if this is a pre-regalloc run.
617  // A return may expand into a lot more instructions (e.g. reload of callee
618  // saved registers) after PEI.
619  if (PreRegAlloc && MI.isReturn())
620  return false;
621 
622  // Avoid duplicating calls before register allocation. Calls presents a
623  // barrier to register allocation so duplicating them may end up increasing
624  // spills.
625  if (PreRegAlloc && MI.isCall())
626  return false;
627 
628  if (!MI.isPHI() && !MI.isMetaInstruction())
629  InstrCount += 1;
630 
631  if (InstrCount > MaxDuplicateCount)
632  return false;
633  }
634 
635  // Check if any of the successors of TailBB has a PHI node in which the
636  // value corresponding to TailBB uses a subregister.
637  // If a phi node uses a register paired with a subregister, the actual
638  // "value type" of the phi may differ from the type of the register without
639  // any subregisters. Due to a bug, tail duplication may add a new operand
640  // without a necessary subregister, producing an invalid code. This is
641  // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
642  // Disable tail duplication for this case for now, until the problem is
643  // fixed.
644  for (auto SB : TailBB.successors()) {
645  for (auto &I : *SB) {
646  if (!I.isPHI())
647  break;
648  unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
649  assert(Idx != 0);
650  MachineOperand &PU = I.getOperand(Idx);
651  if (PU.getSubReg() != 0)
652  return false;
653  }
654  }
655 
656  if (HasIndirectbr && PreRegAlloc)
657  return true;
658 
659  if (IsSimple)
660  return true;
661 
662  if (!PreRegAlloc)
663  return true;
664 
665  return canCompletelyDuplicateBB(TailBB);
666 }
667 
668 /// True if this BB has only one unconditional jump.
670  if (TailBB->succ_size() != 1)
671  return false;
672  if (TailBB->pred_empty())
673  return false;
675  if (I == TailBB->end())
676  return true;
677  return I->isUnconditionalBranch();
678 }
679 
680 static bool bothUsedInPHI(const MachineBasicBlock &A,
681  const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
682  for (MachineBasicBlock *BB : A.successors())
683  if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
684  return true;
685 
686  return false;
687 }
688 
689 bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
690  for (MachineBasicBlock *PredBB : BB.predecessors()) {
691  if (PredBB->succ_size() > 1)
692  return false;
693 
694  MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
696  if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
697  return false;
698 
699  if (!PredCond.empty())
700  return false;
701  }
702  return true;
703 }
704 
705 bool TailDuplicator::duplicateSimpleBB(
707  const DenseSet<unsigned> &UsedByPhi,
710  TailBB->succ_end());
712  TailBB->pred_end());
713  bool Changed = false;
714  for (MachineBasicBlock *PredBB : Preds) {
715  if (PredBB->hasEHPadSuccessor())
716  continue;
717 
718  if (bothUsedInPHI(*PredBB, Succs))
719  continue;
720 
721  MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
723  if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
724  continue;
725 
726  Changed = true;
727  LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
728  << "From simple Succ: " << *TailBB);
729 
730  MachineBasicBlock *NewTarget = *TailBB->succ_begin();
731  MachineBasicBlock *NextBB = PredBB->getNextNode();
732 
733  // Make PredFBB explicit.
734  if (PredCond.empty())
735  PredFBB = PredTBB;
736 
737  // Make fall through explicit.
738  if (!PredTBB)
739  PredTBB = NextBB;
740  if (!PredFBB)
741  PredFBB = NextBB;
742 
743  // Redirect
744  if (PredFBB == TailBB)
745  PredFBB = NewTarget;
746  if (PredTBB == TailBB)
747  PredTBB = NewTarget;
748 
749  // Make the branch unconditional if possible
750  if (PredTBB == PredFBB) {
751  PredCond.clear();
752  PredFBB = nullptr;
753  }
754 
755  // Avoid adding fall through branches.
756  if (PredFBB == NextBB)
757  PredFBB = nullptr;
758  if (PredTBB == NextBB && PredFBB == nullptr)
759  PredTBB = nullptr;
760 
761  auto DL = PredBB->findBranchDebugLoc();
762  TII->removeBranch(*PredBB);
763 
764  if (!PredBB->isSuccessor(NewTarget))
765  PredBB->replaceSuccessor(TailBB, NewTarget);
766  else {
767  PredBB->removeSuccessor(TailBB, true);
768  assert(PredBB->succ_size() <= 1);
769  }
770 
771  if (PredTBB)
772  TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
773 
774  TDBBs.push_back(PredBB);
775  }
776  return Changed;
777 }
778 
780  MachineBasicBlock *PredBB) {
781  // EH edges are ignored by analyzeBranch.
782  if (PredBB->succ_size() > 1)
783  return false;
784 
785  MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
787  if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
788  return false;
789  if (!PredCond.empty())
790  return false;
791  return true;
792 }
793 
794 /// If it is profitable, duplicate TailBB's contents in each
795 /// of its predecessors.
796 /// \p IsSimple result of isSimpleBB
797 /// \p TailBB Block to be duplicated.
798 /// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
799 /// instead of the previous block in MF's order.
800 /// \p TDBBs A vector to keep track of all blocks tail-duplicated
801 /// into.
802 /// \p Copies A vector of copy instructions inserted. Used later to
803 /// walk all the inserted copies and remove redundant ones.
804 bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
805  MachineBasicBlock *ForcedLayoutPred,
808  LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
809  << '\n');
810 
811  DenseSet<unsigned> UsedByPhi;
812  getRegsUsedByPHIs(*TailBB, &UsedByPhi);
813 
814  if (IsSimple)
815  return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
816 
817  // Iterate through all the unique predecessors and tail-duplicate this
818  // block into them, if possible. Copying the list ahead of time also
819  // avoids trouble with the predecessor list reallocating.
820  bool Changed = false;
822  TailBB->pred_end());
823  for (MachineBasicBlock *PredBB : Preds) {
824  assert(TailBB != PredBB &&
825  "Single-block loop should have been rejected earlier!");
826 
827  if (!canTailDuplicate(TailBB, PredBB))
828  continue;
829 
830  // Don't duplicate into a fall-through predecessor (at least for now).
831  bool IsLayoutSuccessor = false;
832  if (ForcedLayoutPred)
833  IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
834  else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
835  IsLayoutSuccessor = true;
836  if (IsLayoutSuccessor)
837  continue;
838 
839  LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
840  << "From Succ: " << *TailBB);
841 
842  TDBBs.push_back(PredBB);
843 
844  // Remove PredBB's unconditional branch.
845  TII->removeBranch(*PredBB);
846 
847  // Clone the contents of TailBB into PredBB.
850  for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
851  I != E; /* empty */) {
852  MachineInstr *MI = &*I;
853  ++I;
854  if (MI->isPHI()) {
855  // Replace the uses of the def of the PHI with the register coming
856  // from PredBB.
857  processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
858  } else {
859  // Replace def of virtual registers with new registers, and update
860  // uses with PHI source register or the new registers.
861  duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
862  }
863  }
864  appendCopies(PredBB, CopyInfos, Copies);
865 
866  NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
867 
868  // Update the CFG.
869  PredBB->removeSuccessor(PredBB->succ_begin());
870  assert(PredBB->succ_empty() &&
871  "TailDuplicate called on block with multiple successors!");
872  for (MachineBasicBlock *Succ : TailBB->successors())
873  PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
874 
875  Changed = true;
876  ++NumTailDups;
877  }
878 
879  // If TailBB was duplicated into all its predecessors except for the prior
880  // block, which falls through unconditionally, move the contents of this
881  // block into the prior block.
882  MachineBasicBlock *PrevBB = ForcedLayoutPred;
883  if (!PrevBB)
884  PrevBB = &*std::prev(TailBB->getIterator());
885  MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
887  // This has to check PrevBB->succ_size() because EH edges are ignored by
888  // analyzeBranch.
889  if (PrevBB->succ_size() == 1 &&
890  // Layout preds are not always CFG preds. Check.
891  *PrevBB->succ_begin() == TailBB &&
892  !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
893  PriorCond.empty() &&
894  (!PriorTBB || PriorTBB == TailBB) &&
895  TailBB->pred_size() == 1 &&
896  !TailBB->hasAddressTaken()) {
897  LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
898  << "From MBB: " << *TailBB);
899  // There may be a branch to the layout successor. This is unlikely but it
900  // happens. The correct thing to do is to remove the branch before
901  // duplicating the instructions in all cases.
902  TII->removeBranch(*PrevBB);
903  if (PreRegAlloc) {
906  MachineBasicBlock::iterator I = TailBB->begin();
907  // Process PHI instructions first.
908  while (I != TailBB->end() && I->isPHI()) {
909  // Replace the uses of the def of the PHI with the register coming
910  // from PredBB.
911  MachineInstr *MI = &*I++;
912  processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
913  }
914 
915  // Now copy the non-PHI instructions.
916  while (I != TailBB->end()) {
917  // Replace def of virtual registers with new registers, and update
918  // uses with PHI source register or the new registers.
919  MachineInstr *MI = &*I++;
920  assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
921  duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
922  MI->eraseFromParent();
923  }
924  appendCopies(PrevBB, CopyInfos, Copies);
925  } else {
926  TII->removeBranch(*PrevBB);
927  // No PHIs to worry about, just splice the instructions over.
928  PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
929  }
930  PrevBB->removeSuccessor(PrevBB->succ_begin());
931  assert(PrevBB->succ_empty());
932  PrevBB->transferSuccessors(TailBB);
933  TDBBs.push_back(PrevBB);
934  Changed = true;
935  }
936 
937  // If this is after register allocation, there are no phis to fix.
938  if (!PreRegAlloc)
939  return Changed;
940 
941  // If we made no changes so far, we are safe.
942  if (!Changed)
943  return Changed;
944 
945  // Handle the nasty case in that we duplicated a block that is part of a loop
946  // into some but not all of its predecessors. For example:
947  // 1 -> 2 <-> 3 |
948  // \ |
949  // \---> rest |
950  // if we duplicate 2 into 1 but not into 3, we end up with
951  // 12 -> 3 <-> 2 -> rest |
952  // \ / |
953  // \----->-----/ |
954  // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
955  // with a phi in 3 (which now dominates 2).
956  // What we do here is introduce a copy in 3 of the register defined by the
957  // phi, just like when we are duplicating 2 into 3, but we don't copy any
958  // real instructions or remove the 3 -> 2 edge from the phi in 2.
959  for (MachineBasicBlock *PredBB : Preds) {
960  if (is_contained(TDBBs, PredBB))
961  continue;
962 
963  // EH edges
964  if (PredBB->succ_size() != 1)
965  continue;
966 
969  MachineBasicBlock::iterator I = TailBB->begin();
970  // Process PHI instructions first.
971  while (I != TailBB->end() && I->isPHI()) {
972  // Replace the uses of the def of the PHI with the register coming
973  // from PredBB.
974  MachineInstr *MI = &*I++;
975  processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
976  }
977  appendCopies(PredBB, CopyInfos, Copies);
978  }
979 
980  return Changed;
981 }
982 
983 /// At the end of the block \p MBB generate COPY instructions between registers
984 /// described by \p CopyInfos. Append resulting instructions to \p Copies.
985 void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
986  SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
989  const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
990  for (auto &CI : CopyInfos) {
991  auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
992  .addReg(CI.second.Reg, 0, CI.second.SubReg);
993  Copies.push_back(C);
994  }
995 }
996 
997 /// Remove the specified dead machine basic block from the function, updating
998 /// the CFG.
999 void TailDuplicator::removeDeadBlock(
1000  MachineBasicBlock *MBB,
1001  function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1002  assert(MBB->pred_empty() && "MBB must be dead!");
1003  LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1004 
1005  if (RemovalCallback)
1006  (*RemovalCallback)(MBB);
1007 
1008  // Remove all successors.
1009  while (!MBB->succ_empty())
1010  MBB->removeSuccessor(MBB->succ_end() - 1);
1011 
1012  // Remove the block.
1013  MBB->eraseFromParent();
1014 }
uint64_t CallInst * C
bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
void initMF(MachineFunction &MF, bool PreRegAlloc, const MachineBranchProbabilityInfo *MBPI, const MachineBlockFrequencyInfo *MBFI, ProfileSummaryInfo *PSI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:682
static cl::opt< unsigned > TailDuplicateSize("tail-dup-size", cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), cl::Hidden)
MachineBasicBlock * getMBB() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:633
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool isCFIInstruction() const
void push_back(const T &Elt)
Definition: SmallVector.h:211
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:400
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:188
Analysis providing profile information.
unsigned Reg
virtual MachineInstr & duplicate(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const
Clones instruction or the whole instruction bundle Orig and insert into MBB before InsertBefore...
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
unsigned getSubReg() const
static void VerifyPHIs(MachineFunction &MF, bool CheckExtra)
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:99
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
STATISTIC(NumFunctions, "Total number of functions")
void RewriteUse(MachineOperand &U)
RewriteUse - Rewrite a use of the symbolic value.
A debug info location.
Definition: DebugLoc.h:33
MachineModuleInfo & getMMI() const
static unsigned InstrCount
bool isMetaInstruction() const
Return true if this instruction doesn&#39;t produce any output in the form of executable instructions...
bool isPHI() const
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< succ_iterator > successors()
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
void eraseFromParent()
This method unlinks &#39;this&#39; from the containing function and deletes it.
static use_iterator use_end()
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
static bool bothUsedInPHI(const MachineBasicBlock &A, const SmallPtrSet< MachineBasicBlock *, 8 > &SuccsB)
unsigned getCFIIndex() const
bool tailDuplicateBlocks()
Look for small blocks that are unconditionally branched to and do not fall through.
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
Definition: MachineInstr.h:712
bool isBundle() const
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
void setReg(Register Reg)
Change the register this operand corresponds to.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
void Initialize(unsigned V)
Initialize - Reset this object to get ready for a new set of SSA updates.
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
bool isReturn(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:672
static bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock *> *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineInstrBuilder & UseMI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE and DBG_LABEL instructions...
unsigned composeSubRegIndices(unsigned a, unsigned b) const
Return the subregister index you get from composing two subregister indices.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
void setMBB(MachineBasicBlock *MBB)
constexpr double e
Definition: MathExtras.h:57
virtual const TargetRegisterClass * getMatchingSuperRegClass(const TargetRegisterClass *A, const TargetRegisterClass *B, unsigned Idx) const
Return a subclass of the specified register class A so that each register in it has a sub-register of...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
self_iterator getIterator()
Definition: ilist_node.h:81
iterator_range< pred_iterator > predecessors()
bool isCopy() const
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
bool isConvergent(QueryType Type=AnyInBundle) const
Return true if this instruction is convergent.
Definition: MachineInstr.h:779
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
size_t size() const
Definition: SmallVector.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setIsKill(bool Val=true)
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:297
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB, const MachineRegisterInfo *MRI)
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
A pair composed of a register and a sub-register index.
MachineInstrBuilder MachineInstrBuilder & DefMI
SI Lower i1 Copies
static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB)
unsigned pred_size() const
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static cl::opt< unsigned > TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden)
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile...
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
unsigned succ_size() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB &#39;Other&#39; at the position From, and insert it into this MBB right before &#39;...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
use_iterator use_begin(unsigned RegNo) const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
#define I(x, y, z)
Definition: MD5.cpp:58
void setSubReg(unsigned subReg)
iterator end()
Definition: DenseMap.h:82
void AddAvailableValue(MachineBasicBlock *BB, unsigned V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register...
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
iterator_range< use_instr_iterator > use_instructions(unsigned Reg) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:69
IRTranslator LLVM IR MI
static cl::opt< unsigned > TailDupIndirectBranchSize("tail-dup-indirect-size", cl::desc("Maximum instructions to consider tail duplicating blocks that " "end with indirect branches."), cl::init(20), cl::Hidden)
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
void RemoveOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
Register getReg() const
getReg - Returns the register number.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
static void getRegsUsedByPHIs(const MachineBasicBlock &BB, DenseSet< unsigned > *UsedByPhi)
static cl::opt< bool > TailDupVerify("tail-dup-verify", cl::desc("Verify sanity of PHI instructions during taildup"), cl::init(false), cl::Hidden)
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
bool isNotDuplicable(QueryType Type=AnyInBundle) const
Return true if this instruction cannot be safely duplicated.
Definition: MachineInstr.h:772
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1241