LLVM 24.0.0git
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"
21#include "llvm/ADT/Statistic.h"
34#include "llvm/IR/DebugLoc.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/Module.h"
38#include "llvm/Support/Debug.h"
42#include <cassert>
43#include <iterator>
44#include <utility>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "tailduplication"
49
50STATISTIC(NumTails, "Number of tails duplicated");
51STATISTIC(NumTailDups, "Number of tail duplicated blocks");
52STATISTIC(NumTailDupAdded,
53 "Number of instructions added due to tail duplication");
54STATISTIC(NumTailDupRemoved,
55 "Number of instructions removed due to tail duplication");
56STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
57STATISTIC(NumAddedPHIs, "Number of phis added");
58
59// Heuristic for tail duplication.
61 "tail-dup-size",
62 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
64
66 "tail-dup-indirect-size",
67 cl::desc("Maximum instructions to consider tail duplicating blocks that "
68 "end with indirect branches."), cl::init(20),
70
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
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
83static 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
88static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
90
91void 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
111static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
114 MBB.pred_end());
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.
167 bool IsSimple, MachineBasicBlock *MBB,
168 MachineBasicBlock *ForcedLayoutPred,
170 function_ref<void(MachineBasicBlock *)> *RemovalCallback,
172 // Save the successors list.
174 MBB->succ_end());
175
178 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred,
179 TDBBs, Copies, CandidatePtr))
180 return false;
181
182 ++NumTails;
183
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 (Register VReg : SSAUpdateVRs) {
204 SSAUpdate.Initialize(VReg);
205
206 // If the original definition is still around, add it as an available
207 // value.
208 MachineBasicBlock *DefBB = MRI->getDefBlock(VReg);
209 if (DefBB)
210 SSAUpdate.AddAvailableValue(DefBB, VReg);
211
212 // Add the new vregs as available values.
213 auto LI = SSAUpdateVals.find(VReg);
214 for (std::pair<MachineBasicBlock *, Register> &J : LI->second) {
215 MachineBasicBlock *SrcBB = J.first;
216 Register SrcReg = J.second;
217 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
218 }
219
221 // Rewrite uses that are outside of the original def's block.
222 for (MachineOperand &UseMO :
223 llvm::make_early_inc_range(MRI->use_operands(VReg))) {
224 MachineInstr *UseMI = UseMO.getParent();
225 // Rewrite debug uses last so that they can take advantage of any
226 // register mappings introduced by other users in its BB, since we
227 // cannot create new register definitions specifically for the debug
228 // instruction (as debug instructions should not affect CodeGen).
229 if (UseMI->isDebugValue()) {
230 DebugUses.push_back(&UseMO);
231 continue;
232 }
233 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
234 continue;
235 SSAUpdate.RewriteUse(UseMO);
236 }
237 for (auto *UseMO : DebugUses) {
238 MachineInstr *UseMI = UseMO->getParent();
239 UseMO->setReg(
240 SSAUpdate.GetValueInMiddleOfBlock(UseMI->getParent(), true));
241 }
242 }
243
244 SSAUpdateVRs.clear();
245 SSAUpdateVals.clear();
246 }
247
248 // Eliminate some of the copies inserted by tail duplication to maintain
249 // SSA form.
250 for (MachineInstr *Copy : Copies) {
251 if (!Copy->isCopy())
252 continue;
253 Register Dst = Copy->getOperand(0).getReg();
254 Register Src = Copy->getOperand(1).getReg();
255 if (MRI->hasOneNonDBGUse(Src) &&
256 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
257 // Copy is the only use. Do trivial copy propagation here.
258 MRI->replaceRegWith(Dst, Src);
259 Copy->eraseFromParent();
260 }
261 }
262
263 if (NewPHIs.size())
264 NumAddedPHIs += NewPHIs.size();
265
266 if (DuplicatedPreds)
267 *DuplicatedPreds = std::move(TDBBs);
268
269 return true;
270}
271
272/// Look for small blocks that are unconditionally branched to and do not fall
273/// through. Tail-duplicate their instructions into their predecessors to
274/// eliminate (dynamic) branches.
276 bool MadeChange = false;
277
278 if (PreRegAlloc && TailDupVerify) {
279 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
280 VerifyPHIs(*MF, true);
281 }
282
283 for (MachineBasicBlock &MBB :
285 if (NumTails == TailDupLimit)
286 break;
287
288 bool IsSimple = isSimpleBB(&MBB);
289
290 if (!shouldTailDuplicate(IsSimple, MBB))
291 continue;
292
293 MadeChange |= tailDuplicateAndUpdate(IsSimple, &MBB, nullptr);
294 }
295
296 if (PreRegAlloc && TailDupVerify)
297 VerifyPHIs(*MF, false);
298
299 return MadeChange;
300}
301
303 const MachineRegisterInfo *MRI) {
304 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
305 if (UseMI.isDebugValue())
306 continue;
307 if (UseMI.getParent() != BB)
308 return true;
309 }
310 return false;
311}
312
314 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
315 if (MI->getOperand(i + 1).getMBB() == SrcBB)
316 return i;
317 return 0;
318}
319
320// Remember which registers are used by phis in this block. This is
321// used to determine which registers are liveout while modifying the
322// block (which is why we need to copy the information).
324 DenseSet<Register> *UsedByPhi) {
325 for (const auto &MI : BB) {
326 if (!MI.isPHI())
327 break;
328 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
329 Register SrcReg = MI.getOperand(i).getReg();
330 UsedByPhi->insert(SrcReg);
331 }
332 }
333}
334
335/// Add a definition and source virtual registers pair for SSA update.
336void TailDuplicator::addSSAUpdateEntry(Register OrigReg, Register NewReg,
337 MachineBasicBlock *BB) {
338 auto LI = SSAUpdateVals.find(OrigReg);
339 if (LI != SSAUpdateVals.end())
340 LI->second.push_back(std::make_pair(BB, NewReg));
341 else {
342 AvailableValsTy Vals;
343 Vals.push_back(std::make_pair(BB, NewReg));
344 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
345 SSAUpdateVRs.push_back(OrigReg);
346 }
347}
348
349/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
350/// source register that's contributed by PredBB and update SSA update map.
351void TailDuplicator::processPHI(
354 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &Copies,
355 const DenseSet<Register> &RegsUsedByPhi, bool Remove) {
356 Register DefReg = MI->getOperand(0).getReg();
357 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
358 assert(SrcOpIdx && "Unable to find matching PHI source?");
359 Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
360 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
361 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
362 LocalVRMap.try_emplace(DefReg, SrcReg, SrcSubReg);
363
364 // Insert a copy from source to the end of the block. The def register is the
365 // available value liveout of the block.
366 Register NewDef = MRI->createVirtualRegister(RC);
367 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
368 if (!Remove) {
369 // Informing MachineSSAUpdater that DefReg -> NewDef in PredBB is not
370 // correct, because it could be used to update on other PHI. But the DefReg
371 // in the COPY will be properly updated by MachineSSAUpdater.
372 MI->getOperand(SrcOpIdx).setReg(NewDef);
373 MI->getOperand(SrcOpIdx).setSubReg(0);
374 return;
375 }
376 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
377 addSSAUpdateEntry(DefReg, NewDef, PredBB);
378
379 MI->removePHIIncomingValueFor(*PredBB);
380
381 if (MI->getNumOperands() == 1 && !TailBB->hasAddressTaken())
382 MI->eraseFromParent();
383 else if (MI->getNumOperands() == 1)
384 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
385}
386
387/// Duplicate a TailBB instruction to PredBB and update
388/// the source operands due to earlier PHI translation.
389void TailDuplicator::duplicateInstruction(
392 const DenseSet<Register> &UsedByPhi) {
393 // Allow duplication of CFI instructions.
394 if (MI->isCFIInstruction()) {
395 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
396 TII->get(TargetOpcode::CFI_INSTRUCTION))
397 .addCFIIndex(MI->getOperand(0).getCFIIndex())
398 .setMIFlags(MI->getFlags());
399 return;
400 }
401 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
402 if (!PreRegAlloc)
403 return;
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.try_emplace(Reg, NewReg, 0);
416 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
417 addSSAUpdateEntry(Reg, NewReg, PredBB);
418 continue;
419 }
420 auto VI = LocalVRMap.find(Reg);
421 if (VI == LocalVRMap.end())
422 continue;
423 // Need to make sure that the register class of the mapped register
424 // will satisfy the constraints of the class of the register being
425 // replaced.
426 auto *OrigRC = MRI->getRegClass(Reg);
427 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
428 const TargetRegisterClass *ConstrRC;
429 if (VI->second.SubReg != 0) {
430 ConstrRC =
431 TRI->getMatchingSuperRegClass(MappedRC, OrigRC, VI->second.SubReg);
432 if (ConstrRC) {
433 // The actual constraining (as in "find appropriate new class")
434 // is done by getMatchingSuperRegClass, so now we only need to
435 // change the class of the mapped register.
436 MRI->setRegClass(VI->second.Reg, ConstrRC);
437 }
438 } else {
439 // For mapped registers that do not have sub-registers, simply
440 // restrict their class to match the original one.
441
442 // We don't want debug instructions affecting the resulting code so
443 // if we're cloning a debug instruction then just use MappedRC
444 // rather than constraining the register class further.
445 ConstrRC = NewMI.isDebugInstr()
446 ? MappedRC
447 : MRI->constrainRegClass(VI->second.Reg, OrigRC);
448 }
449
450 if (ConstrRC) {
451 // If the class constraining succeeded, we can simply replace
452 // the old register with the mapped one.
453 MO.setReg(VI->second.Reg);
454 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
455 // sub-register, we need to compose the sub-register indices.
456 MO.setSubReg(
457 TRI->composeSubRegIndices(VI->second.SubReg, MO.getSubReg()));
458 } else {
459 // The direct replacement is not possible, due to failing register
460 // class constraints. An explicit COPY is necessary. Create one
461 // that can be reused.
462 Register NewReg = MRI->createVirtualRegister(OrigRC);
463 BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(), TII->get(TargetOpcode::COPY),
464 NewReg)
465 .addReg(VI->second.Reg, {}, VI->second.SubReg);
466 LocalVRMap.erase(VI);
467 LocalVRMap.try_emplace(Reg, NewReg, 0);
468 MO.setReg(NewReg);
469 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
470 // is equivalent to the whole register Reg. Hence, Reg:subreg
471 // is same as NewReg:subreg, so keep the sub-register index
472 // unchanged.
473 }
474 // Clear any kill flags from this operand. The new register could
475 // have uses after this one, so kills are not valid here.
476 MO.setIsKill(false);
477 }
478}
479
480/// After FromBB is tail duplicated into its predecessor blocks, the successors
481/// have gained new predecessors. Update the PHI instructions in them
482/// accordingly.
483void TailDuplicator::updateSuccessorsPHIs(
484 MachineBasicBlock *FromBB, bool isDead,
487 for (MachineBasicBlock *SuccBB : Succs) {
488 for (MachineInstr &MI : *SuccBB) {
489 if (!MI.isPHI())
490 break;
491 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
492 unsigned Idx = 0;
493 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
494 MachineOperand &MO = MI.getOperand(i + 1);
495 if (MO.getMBB() == FromBB) {
496 Idx = i;
497 break;
498 }
499 }
500
501 assert(Idx != 0);
502 MachineOperand &MO0 = MI.getOperand(Idx);
503 Register Reg = MO0.getReg();
504 if (isDead) {
505 // Folded into the previous BB.
506 // There could be duplicate phi source entries. FIXME: Should sdisel
507 // or earlier pass fixed this?
508 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
509 MachineOperand &MO = MI.getOperand(i + 1);
510 if (MO.getMBB() == FromBB) {
511 MI.removeOperand(i + 1);
512 MI.removeOperand(i);
513 }
514 }
515 } else
516 Idx = 0;
517
518 // If Idx is set, the operands at Idx and Idx+1 must be removed.
519 // We reuse the location to avoid expensive removeOperand calls.
520
521 auto LI = SSAUpdateVals.find(Reg);
522 if (LI != SSAUpdateVals.end()) {
523 // This register is defined in the tail block.
524 for (const std::pair<MachineBasicBlock *, Register> &J : LI->second) {
525 MachineBasicBlock *SrcBB = J.first;
526 // If we didn't duplicate a bb into a particular predecessor, we
527 // might still have added an entry to SSAUpdateVals to correcly
528 // recompute SSA. If that case, avoid adding a dummy extra argument
529 // this PHI.
530 if (!SrcBB->isSuccessor(SuccBB))
531 continue;
532
533 Register SrcReg = J.second;
534 if (Idx != 0) {
535 MI.getOperand(Idx).setReg(SrcReg);
536 MI.getOperand(Idx + 1).setMBB(SrcBB);
537 Idx = 0;
538 } else {
539 MIB.addReg(SrcReg).addMBB(SrcBB);
540 }
541 }
542 } else {
543 // Live in tail block, must also be live in predecessors.
544 for (MachineBasicBlock *SrcBB : TDBBs) {
545 if (Idx != 0) {
546 MI.getOperand(Idx).setReg(Reg);
547 MI.getOperand(Idx + 1).setMBB(SrcBB);
548 Idx = 0;
549 } else {
550 MIB.addReg(Reg).addMBB(SrcBB);
551 }
552 }
553 }
554 if (Idx != 0) {
555 MI.removeOperand(Idx + 1);
556 MI.removeOperand(Idx);
557 }
558 }
559 }
560}
561
562/// Determine if it is profitable to duplicate this block.
564 MachineBasicBlock &TailBB) {
565 // When doing tail-duplication during layout, the block ordering is in flux,
566 // so canFallThrough returns a result based on incorrect information and
567 // should just be ignored.
568 if (!LayoutMode && TailBB.canFallThrough())
569 return false;
570
571 // Don't try to tail-duplicate single-block loops.
572 if (TailBB.isSuccessor(&TailBB))
573 return false;
574
575 // Set the limit on the cost to duplicate. When optimizing for size,
576 // duplicate only one, because one branch instruction can be eliminated to
577 // compensate for the duplication.
578 unsigned MaxDuplicateCount;
579 if (TailDupSize == 0)
580 MaxDuplicateCount = TailDuplicateSize;
581 else
582 MaxDuplicateCount = TailDupSize;
583 if (llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI))
584 MaxDuplicateCount = 1;
585
586 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
587 // duplicate it.
588 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
589 // blocks with unanalyzable fallthrough get layed out contiguously.
590 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
592 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
593 TailBB.canFallThrough())
594 return false;
595
596 // If the target has hardware branch prediction that can handle indirect
597 // branches, duplicating them can often make them predictable when there
598 // are common paths through the code. The limit needs to be high enough
599 // to allow undoing the effects of tail merging and other optimizations
600 // that rearrange the predecessors of the indirect branch.
601
602 bool HasIndirectbr = false;
603 bool HasComputedGoto = false;
604 if (!TailBB.empty()) {
605 HasIndirectbr = TailBB.back().isIndirectBranch();
606 HasComputedGoto = TailBB.terminatorIsComputedGotoWithSuccessors();
607 }
608
609 if (HasIndirectbr && PreRegAlloc)
610 MaxDuplicateCount = TailDupIndirectBranchSize;
611
612 // Allow higher limits when the block has computed-gotos and running after
613 // register allocation. NB. This basically unfactors computed gotos that were
614 // factored early on in the compilation process to speed up edge based data
615 // flow. If we do not unfactor them again, it can seriously pessimize code
616 // with many computed jumps in the source code, such as interpreters.
617 // Therefore we do not restrict the computed gotos.
618 if (HasComputedGoto && !PreRegAlloc)
619 MaxDuplicateCount = std::max(MaxDuplicateCount, 10u);
620
621 // Check the instructions in the block to determine whether tail-duplication
622 // is invalid or unlikely to be profitable.
623 unsigned InstrCount = 0;
624 unsigned NumPhis = 0;
625 for (MachineInstr &MI : TailBB) {
626 // Non-duplicable things shouldn't be tail-duplicated.
627 // CFI instructions are marked as non-duplicable, because Darwin compact
628 // unwind info emission can't handle multiple prologue setups. In case of
629 // DWARF, allow them be duplicated, so that their existence doesn't prevent
630 // tail duplication of some basic blocks, that would be duplicated otherwise.
631 if (MI.isNotDuplicable() && (TailBB.getParent()
632 ->getFunction()
633 .getParent()
635 .isOSDarwin() ||
636 !MI.isCFIInstruction()))
637 return false;
638
639 // Convergent instructions can be duplicated only if doing so doesn't add
640 // new control dependencies, which is what we're going to do here.
641 if (MI.isConvergent())
642 return false;
643
644 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
645 // A return may expand into a lot more instructions (e.g. reload of callee
646 // saved registers) after PEI.
647 if (PreRegAlloc && MI.isReturn())
648 return false;
649
650 // Avoid duplicating calls before register allocation. Calls presents a
651 // barrier to register allocation so duplicating them may end up increasing
652 // spills.
653 if (PreRegAlloc && MI.isCall())
654 return false;
655
656 // TailDuplicator::appendCopies will erroneously place COPYs after
657 // INLINEASM_BR instructions after 4b0aa5724fea, which demonstrates the same
658 // bug that was fixed in f7a53d82c090.
659 // FIXME: Use findPHICopyInsertPoint() to find the correct insertion point
660 // for the COPY when replacing PHIs.
661 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
662 return false;
663
664 if (MI.isBundle())
665 InstrCount += MI.getBundleSize();
666 else if (!MI.isPHI() && !MI.isMetaInstruction())
667 InstrCount += 1;
668
669 if (InstrCount > MaxDuplicateCount)
670 return false;
671 NumPhis += MI.isPHI();
672 }
673
674 // Duplicating a BB which has both multiple predecessors and successors will
675 // may cause huge amount of PHI nodes. If we want to remove this limitation,
676 // we have to address https://github.com/llvm/llvm-project/issues/78578.
677 if (PreRegAlloc && TailBB.pred_size() > TailDupPredSize &&
678 TailBB.succ_size() > TailDupSuccSize) {
679 // If TailBB or any of its successors contains a phi, we may have to add a
680 // large number of additional phis with additional incoming values.
681 if (NumPhis != 0 || any_of(TailBB.successors(), [](MachineBasicBlock *MBB) {
682 return any_of(*MBB, [](MachineInstr &MI) { return MI.isPHI(); });
683 }))
684 return false;
685 }
686
687 // Check if any of the successors of TailBB has a PHI node in which the
688 // value corresponding to TailBB uses a subregister.
689 // If a phi node uses a register paired with a subregister, the actual
690 // "value type" of the phi may differ from the type of the register without
691 // any subregisters. Due to a bug, tail duplication may add a new operand
692 // without a necessary subregister, producing an invalid code. This is
693 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
694 // Disable tail duplication for this case for now, until the problem is
695 // fixed.
696 for (auto *SB : TailBB.successors()) {
697 for (auto &I : *SB) {
698 if (!I.isPHI())
699 break;
700 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
701 assert(Idx != 0);
702 MachineOperand &PU = I.getOperand(Idx);
703 if (PU.getSubReg() != 0)
704 return false;
705 }
706 }
707
708 if (HasIndirectbr && PreRegAlloc)
709 return true;
710
711 if (IsSimple)
712 return true;
713
714 if (!PreRegAlloc)
715 return true;
716
717 return canCompletelyDuplicateBB(TailBB);
718}
719
720/// True if this BB has only one unconditional jump.
722 if (TailBB->succ_size() != 1)
723 return false;
724 if (TailBB->pred_empty())
725 return false;
727 if (I == TailBB->end())
728 return true;
729 return I->isUnconditionalBranch();
730}
731
734 for (MachineBasicBlock *BB : A.successors())
735 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
736 return true;
737
738 return false;
739}
740
741bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
742 for (MachineBasicBlock *PredBB : BB.predecessors()) {
743 if (PredBB->succ_size() > 1)
744 return false;
745
746 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
747 SmallVector<MachineOperand, 4> PredCond;
748 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
749 return false;
750
751 if (!PredCond.empty())
752 return false;
753 }
754 return true;
755}
756
757bool TailDuplicator::duplicateSimpleBB(
759 const DenseSet<Register> &UsedByPhi) {
760 SmallPtrSet<MachineBasicBlock *, 8> Succs(llvm::from_range,
761 TailBB->successors());
763 bool Changed = false;
764 for (MachineBasicBlock *PredBB : Preds) {
765 if (PredBB->hasEHPadSuccessor() || PredBB->mayHaveInlineAsmBr())
766 continue;
767
768 if (bothUsedInPHI(*PredBB, Succs))
769 continue;
770
771 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
772 SmallVector<MachineOperand, 4> PredCond;
773 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
774 continue;
775
776 Changed = true;
777 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
778 << "From simple Succ: " << *TailBB);
779
780 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
781 MachineBasicBlock *NextBB = PredBB->getNextNode();
782
783 // Make PredFBB explicit.
784 if (PredCond.empty())
785 PredFBB = PredTBB;
786
787 // Make fall through explicit.
788 if (!PredTBB)
789 PredTBB = NextBB;
790 if (!PredFBB)
791 PredFBB = NextBB;
792
793 // Redirect
794 if (PredFBB == TailBB)
795 PredFBB = NewTarget;
796 if (PredTBB == TailBB)
797 PredTBB = NewTarget;
798
799 // Make the branch unconditional if possible
800 if (PredTBB == PredFBB) {
801 PredCond.clear();
802 PredFBB = nullptr;
803 }
804
805 // Avoid adding fall through branches.
806 if (PredFBB == NextBB)
807 PredFBB = nullptr;
808 if (PredTBB == NextBB && PredFBB == nullptr)
809 PredTBB = nullptr;
810
811 auto DL = PredBB->findBranchDebugLoc();
812 TII->removeBranch(*PredBB);
813
814 if (!PredBB->isSuccessor(NewTarget))
815 PredBB->replaceSuccessor(TailBB, NewTarget);
816 else {
817 PredBB->removeSuccessor(TailBB, true);
818 assert(PredBB->succ_size() <= 1);
819 }
820
821 if (PredTBB)
822 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
823
824 TDBBs.push_back(PredBB);
825 }
826 return Changed;
827}
828
830 MachineBasicBlock *PredBB) {
831 // EH edges are ignored by analyzeBranch.
832 if (PredBB->succ_size() > 1)
833 return false;
834
835 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
837 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
838 return false;
839 if (!PredCond.empty())
840 return false;
841 // FIXME: This is overly conservative; it may be ok to relax this in the
842 // future under more specific conditions. If TailBB is an INLINEASM_BR
843 // indirect target, we need to see if the edge from PredBB to TailBB is from
844 // an INLINEASM_BR in PredBB, and then also if that edge was from the
845 // indirect target list, fallthrough/default target, or potentially both. If
846 // it's both, TailDuplicator::tailDuplicate will remove the edge, corrupting
847 // the successor list in PredBB and predecessor list in TailBB.
848 if (TailBB->isInlineAsmBrIndirectTarget())
849 return false;
850 return true;
851}
852
853/// If it is profitable, duplicate TailBB's contents in each
854/// of its predecessors.
855/// \p IsSimple result of isSimpleBB
856/// \p TailBB Block to be duplicated.
857/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
858/// instead of the previous block in MF's order.
859/// \p TDBBs A vector to keep track of all blocks tail-duplicated
860/// into.
861/// \p Copies A vector of copy instructions inserted. Used later to
862/// walk all the inserted copies and remove redundant ones.
863bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
864 MachineBasicBlock *ForcedLayoutPred,
868 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
869 << '\n');
870
871 bool ShouldUpdateTerminators = TailBB->canFallThrough();
872
873 DenseSet<Register> UsedByPhi;
874 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
875
876 if (IsSimple)
877 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi);
878
879 // Iterate through all the unique predecessors and tail-duplicate this
880 // block into them, if possible. Copying the list ahead of time also
881 // avoids trouble with the predecessor list reallocating.
882 bool Changed = false;
884 if (CandidatePtr)
885 Preds.insert_range(*CandidatePtr);
886 else
887 Preds.insert_range(TailBB->predecessors());
888
889 for (MachineBasicBlock *PredBB : Preds) {
890 assert(TailBB != PredBB &&
891 "Single-block loop should have been rejected earlier!");
892
893 if (!canTailDuplicate(TailBB, PredBB))
894 continue;
895
896 // Don't duplicate into a fall-through predecessor (at least for now).
897 // If profile is available, findDuplicateCandidates can choose better
898 // fall-through predecessor.
899 if (!(MF->getFunction().hasProfileData() && LayoutMode)) {
900 bool IsLayoutSuccessor = false;
901 if (ForcedLayoutPred)
902 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
903 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
904 IsLayoutSuccessor = true;
905 if (IsLayoutSuccessor)
906 continue;
907 }
908
909 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
910 << "From Succ: " << *TailBB);
911
912 TDBBs.push_back(PredBB);
913
914 // Remove PredBB's unconditional branch.
915 TII->removeBranch(*PredBB);
916
917 // Clone the contents of TailBB into PredBB.
920 for (MachineInstr &MI : llvm::make_early_inc_range(*TailBB)) {
921 if (MI.isPHI()) {
922 // Replace the uses of the def of the PHI with the register coming
923 // from PredBB.
924 processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
925 } else {
926 // Replace def of virtual registers with new registers, and update
927 // uses with PHI source register or the new registers.
928 duplicateInstruction(&MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
929 }
930 }
931 appendCopies(PredBB, CopyInfos, Copies);
932
933 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
934
935 // Update the CFG.
936 PredBB->removeSuccessor(PredBB->succ_begin());
937 assert(PredBB->succ_empty() &&
938 "TailDuplicate called on block with multiple successors!");
939 for (MachineBasicBlock *Succ : TailBB->successors())
940 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
941
942 // Update branches in pred to jump to tail's layout successor if needed.
943 if (ShouldUpdateTerminators)
944 PredBB->updateTerminator(TailBB->getNextNode());
945
946 Changed = true;
947 ++NumTailDups;
948 }
949
950 // If TailBB was duplicated into all its predecessors except for the prior
951 // block, which falls through unconditionally, move the contents of this
952 // block into the prior block.
953 MachineBasicBlock *PrevBB = ForcedLayoutPred;
954 if (!PrevBB)
955 PrevBB = &*std::prev(TailBB->getIterator());
956 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
957 SmallVector<MachineOperand, 4> PriorCond;
958 // This has to check PrevBB->succ_size() because EH edges are ignored by
959 // analyzeBranch.
960 if (PrevBB->succ_size() == 1 &&
961 // Layout preds are not always CFG preds. Check.
962 *PrevBB->succ_begin() == TailBB &&
963 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
964 PriorCond.empty() &&
965 (!PriorTBB || PriorTBB == TailBB) &&
966 TailBB->pred_size() == 1 &&
967 !TailBB->hasAddressTaken()) {
968 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
969 << "From MBB: " << *TailBB);
970 // There may be a branch to the layout successor. This is unlikely but it
971 // happens. The correct thing to do is to remove the branch before
972 // duplicating the instructions in all cases.
973 bool RemovedBranches = TII->removeBranch(*PrevBB) != 0;
974
975 // If there are still tail instructions, abort the merge
976 if (PrevBB->getFirstTerminator() == PrevBB->end()) {
977 if (PreRegAlloc) {
978 DenseMap<Register, RegSubRegPair> LocalVRMap;
981 // Process PHI instructions first.
982 while (I != TailBB->end() && I->isPHI()) {
983 // Replace the uses of the def of the PHI with the register coming
984 // from PredBB.
985 MachineInstr *MI = &*I++;
986 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
987 true);
988 }
989
990 // Now copy the non-PHI instructions.
991 while (I != TailBB->end()) {
992 // Replace def of virtual registers with new registers, and update
993 // uses with PHI source register or the new registers.
994 MachineInstr *MI = &*I++;
995 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
996 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
997 MI->eraseFromParent();
998 }
999 appendCopies(PrevBB, CopyInfos, Copies);
1000 } else {
1001 TII->removeBranch(*PrevBB);
1002 // No PHIs to worry about, just splice the instructions over.
1003 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
1004 }
1005 PrevBB->removeSuccessor(PrevBB->succ_begin());
1006 assert(PrevBB->succ_empty());
1007 PrevBB->transferSuccessors(TailBB);
1008
1009 // Update branches in PrevBB based on Tail's layout successor.
1010 if (ShouldUpdateTerminators)
1011 PrevBB->updateTerminator(TailBB->getNextNode());
1012
1013 TDBBs.push_back(PrevBB);
1014 Changed = true;
1015 } else {
1016 LLVM_DEBUG(dbgs() << "Abort merging blocks, the predecessor still "
1017 "contains terminator instructions");
1018 // Return early if no changes were made
1019 if (!Changed)
1020 return RemovedBranches;
1021 }
1022 Changed |= RemovedBranches;
1023 }
1024
1025 // If this is after register allocation, there are no phis to fix.
1026 if (!PreRegAlloc)
1027 return Changed;
1028
1029 // If we made no changes so far, we are safe.
1030 if (!Changed)
1031 return Changed;
1032
1033 // Handle the nasty case in that we duplicated a block that is part of a loop
1034 // into some but not all of its predecessors. For example:
1035 // 1 -> 2 <-> 3 |
1036 // \ |
1037 // \---> rest |
1038 // if we duplicate 2 into 1 but not into 3, we end up with
1039 // 12 -> 3 <-> 2 -> rest |
1040 // \ / |
1041 // \----->-----/ |
1042 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
1043 // with a phi in 3 (which now dominates 2).
1044 // What we do here is introduce a copy in 3 of the register defined by the
1045 // phi, just like when we are duplicating 2 into 3, but we don't copy any
1046 // real instructions or remove the 3 -> 2 edge from the phi in 2.
1047 for (MachineBasicBlock *PredBB : Preds) {
1048 if (is_contained(TDBBs, PredBB))
1049 continue;
1050
1051 // EH edges
1052 if (PredBB->succ_size() != 1)
1053 continue;
1054
1055 DenseMap<Register, RegSubRegPair> LocalVRMap;
1057 // Process PHI instructions first.
1058 for (MachineInstr &MI : make_early_inc_range(TailBB->phis())) {
1059 // Replace the uses of the def of the PHI with the register coming
1060 // from PredBB.
1061 processPHI(&MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
1062 }
1063 appendCopies(PredBB, CopyInfos, Copies);
1064 }
1065
1066 return Changed;
1067}
1068
1069/// At the end of the block \p MBB generate COPY instructions between registers
1070/// described by \p CopyInfos. Append resulting instructions to \p Copies.
1071void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
1072 SmallVectorImpl<std::pair<Register, RegSubRegPair>> &CopyInfos,
1075 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
1076 for (auto &CI : CopyInfos) {
1077 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
1078 .addReg(CI.second.Reg, {}, CI.second.SubReg);
1079 Copies.push_back(C);
1080 }
1081}
1082
1083/// Remove the specified dead machine basic block from the function, updating
1084/// the CFG.
1085void TailDuplicator::removeDeadBlock(
1087 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
1088 assert(MBB->pred_empty() && "MBB must be dead!");
1089 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
1090
1091 MachineFunction *MF = MBB->getParent();
1092 // Update the call info.
1093 for (const MachineInstr &MI : *MBB)
1094 if (MI.shouldUpdateAdditionalCallInfo())
1096
1097 if (RemovalCallback)
1098 (*RemovalCallback)(MBB);
1099
1100 // Remove all successors.
1101 while (!MBB->succ_empty())
1103
1104 // Remove the block.
1106}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT, const SimplifyQuery &SQ)
static unsigned InstrCount
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition MD5.cpp:57
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
SI Lower i1 Copies
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static cl::opt< unsigned > TailDuplicateSize("tail-dup-size", cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), cl::Hidden)
static cl::opt< unsigned > TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden)
static cl::opt< unsigned > TailDupPredSize("tail-dup-pred-size", cl::desc("Maximum predecessors (maximum successors at the " "same time) to consider tail duplicating blocks."), cl::init(16), cl::Hidden)
static cl::opt< unsigned > TailDupSuccSize("tail-dup-succ-size", cl::desc("Maximum successors (maximum predecessors at the " "same time) to consider tail duplicating blocks."), cl::init(16), cl::Hidden)
static cl::opt< bool > TailDupVerify("tail-dup-verify", cl::desc("Verify sanity of PHI instructions during taildup"), cl::init(false), cl::Hidden)
static void VerifyPHIs(MachineFunction &MF, bool CheckExtra)
static bool bothUsedInPHI(const MachineBasicBlock &A, const SmallPtrSet< MachineBasicBlock *, 8 > &SuccsB)
static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB)
static void getRegsUsedByPHIs(const MachineBasicBlock &BB, DenseSet< Register > *UsedByPhi)
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)
static bool isDefLiveOut(Register Reg, MachineBasicBlock *BB, const MachineRegisterInfo *MRI)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
bool erase(const KeyT &Val)
Definition DenseMap.h:931
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:313
Module * getParent()
Get the module that this global value is contained inside of...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI bool hasEHPadSuccessor() const
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
bool terminatorIsComputedGotoWithSuccessors() const
Returns true if the original IR terminator is an indirectbr with successor blocks.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool mayHaveInlineAsmBr() const
Returns true if this block may have an INLINEASM_BR (overestimate, by checking if any of the successo...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
void eraseAdditionalCallInfo(const MachineInstr *MI)
Following functions update call site info.
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
Representation of each machine instruction.
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
LLVM_ABI void Initialize(Register V)
Initialize - Reset this object to get ready for a new set of SSA updates.
LLVM_ABI Register GetValueInMiddleOfBlock(MachineBasicBlock *BB, bool ExistingValueOnly=false)
GetValueInMiddleOfBlock - Construct SSA form, materializing a value that is live in the middle of the...
LLVM_ABI void RewriteUse(MachineOperand &U)
RewriteUse - Rewrite a use of the symbolic value.
LLVM_ABI void AddAvailableValue(MachineBasicBlock *BB, Register V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void initMF(MachineFunction &MF, bool PreRegAlloc, const MachineBranchProbabilityInfo *MBPI, MBFIWrapper *MBFI, ProfileSummaryInfo *PSI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
LLVM_ABI bool tailDuplicateBlocks()
Look for small blocks that are unconditionally branched to and do not fall through.
LLVM_ABI bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock * > *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr, SmallVectorImpl< MachineBasicBlock * > *CandidatePtr=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
static LLVM_ABI bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
LLVM_ABI bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
LLVM_ABI bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
const TargetRegisterInfo & getRegisterInfo() const
virtual const TargetInstrInfo * getInstrInfo() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:724
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
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:187
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto successors(const MachineBasicBlock *BB)
constexpr from_range_t from_range
LLVM_ABI 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.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58