LLVM 23.0.0git
BranchFolding.cpp
Go to the documentation of this file.
1//===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
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 pass forwards branches to unconditional branches to make them branch
10// directly to the target block. This pass often results in dead MBB's, which
11// it then removes.
12//
13// Note that this pass must be run after register allocation, it cannot handle
14// SSA form. It also must handle virtual registers for targets that emit virtual
15// ISA (e.g. NVPTX).
16//
17//===----------------------------------------------------------------------===//
18
19#include "BranchFolding.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/Statistic.h"
47#include "llvm/Config/llvm-config.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
52#include "llvm/MC/LaneBitmask.h"
54#include "llvm/Pass.h"
58#include "llvm/Support/Debug.h"
62#include <cassert>
63#include <cstddef>
64#include <iterator>
65#include <numeric>
66
67using namespace llvm;
68
69#define DEBUG_TYPE "branch-folder"
70
71STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
72STATISTIC(NumBranchOpts, "Number of branches optimized");
73STATISTIC(NumTailMerge , "Number of block tails merged");
74STATISTIC(NumHoist , "Number of times common instructions are hoisted");
75STATISTIC(NumTailCalls, "Number of tail calls optimized");
76
78 FlagEnableTailMerge("enable-tail-merge",
80
81// Override the common-code hoisting sub-phase of BranchFolding. Unset by
82// default, in which case the value configured by the caller is used.
84 "branch-folder-hoist-common-code", cl::init(cl::boolOrDefault::BOU_UNSET),
86 cl::desc("Override common-code hoisting in the BranchFolding pass"));
87
88// Override the basic-block reordering sub-phase of BranchFolding. Unset by
89// default, in which case the value configured by the caller is used.
91 "branch-folder-reorder-blocks", cl::init(cl::boolOrDefault::BOU_UNSET),
93 cl::desc("Override basic-block reordering in the BranchFolding pass"));
94
95// Throttle for huge numbers of predecessors (compile speed problems)
97TailMergeThreshold("tail-merge-threshold",
98 cl::desc("Max number of predecessors to consider tail merging"),
99 cl::init(150), cl::Hidden);
100
101// Heuristic for tail merging (and, inversely, tail duplication).
103TailMergeSize("tail-merge-size",
104 cl::desc("Min number of instructions to consider tail merging"),
105 cl::init(3), cl::Hidden);
106
107namespace {
108
109 /// BranchFolderPass - Wrap branch folder in a machine function pass.
110class BranchFolderLegacy : public MachineFunctionPass {
111 bool EnableCommonHoist;
112 bool EnableBasicBlockReordering;
113
114public:
115 static char ID;
116
117 explicit BranchFolderLegacy(bool EnableCommonHoist = true,
118 bool EnableBasicBlockReordering = true)
119 : MachineFunctionPass(ID), EnableCommonHoist(EnableCommonHoist),
120 EnableBasicBlockReordering(EnableBasicBlockReordering) {}
121
122 bool runOnMachineFunction(MachineFunction &MF) override;
123
124 void getAnalysisUsage(AnalysisUsage &AU) const override {
125 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
126 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
127 AU.addRequired<ProfileSummaryInfoWrapperPass>();
128 AU.addRequired<TargetPassConfig>();
130 }
131
132 MachineFunctionProperties getRequiredProperties() const override {
133 return MachineFunctionProperties().setNoPHIs();
134 }
135};
136
137} // end anonymous namespace
138
139char BranchFolderLegacy::ID = 0;
140
141char &llvm::BranchFolderPassID = BranchFolderLegacy::ID;
142
143INITIALIZE_PASS(BranchFolderLegacy, DEBUG_TYPE, "Control Flow Optimizer", false,
144 false)
145
148 MFPropsModifier _(*this, MF);
149 bool EnableTailMerge =
150 !MF.getTarget().requiresStructuredCFG() && this->EnableTailMerge;
151
152 auto &MBPI = MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
153 auto *PSI = MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(MF)
154 .getCachedResult<ProfileSummaryAnalysis>(
155 *MF.getFunction().getParent());
156 if (!PSI)
158 "ProfileSummaryAnalysis is required for BranchFoldingPass", false);
159
160 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
161 MBFIWrapper MBBFreqInfo(MBFI);
162 BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo, MBPI,
163 PSI);
164 Folder.setBasicBlockReordering(true);
165 if (Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
166 MF.getSubtarget().getRegisterInfo()))
168
169 return PreservedAnalyses::all();
170}
171
172bool BranchFolderLegacy::runOnMachineFunction(MachineFunction &MF) {
173 if (skipFunction(MF.getFunction()))
174 return false;
175
176 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
177 // TailMerge can create jump into if branches that make CFG irreducible for
178 // HW that requires structurized CFG.
179 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
180 PassConfig->getEnableTailMerge();
181 MBFIWrapper MBBFreqInfo(
182 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
183 BranchFolder Folder(
184 EnableTailMerge, EnableCommonHoist, MBBFreqInfo,
185 getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(),
186 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
187 Folder.setBasicBlockReordering(EnableBasicBlockReordering);
188 return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
190}
191
192BranchFolder::BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist,
193 MBFIWrapper &FreqInfo,
194 const MachineBranchProbabilityInfo &ProbInfo,
195 ProfileSummaryInfo *PSI, unsigned MinTailLength)
196 : EnableHoistCommonCode(CommonHoist), EnableBasicBlockReordering(true),
197 MinCommonTailLength(MinTailLength), MBBFreqInfo(FreqInfo), MBPI(ProbInfo),
198 PSI(PSI) {
199 switch (FlagEnableTailMerge) {
201 EnableTailMerge = DefaultEnableTailMerge;
202 break;
204 EnableTailMerge = true;
205 break;
207 EnableTailMerge = false;
208 break;
209 }
210}
211
212void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
213 assert(MBB->pred_empty() && "MBB must be dead!");
214 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
215
216 MachineFunction *MF = MBB->getParent();
217 // drop all successors.
218 while (!MBB->succ_empty())
219 MBB->removeSuccessor(MBB->succ_end()-1);
220
221 // Avoid matching if this pointer gets reused.
222 TriedMerging.erase(MBB);
223
224 // Update call info.
225 for (const MachineInstr &MI : *MBB)
226 if (MI.shouldUpdateAdditionalCallInfo())
228
229 // Remove the block.
230 if (MLI)
231 MLI->removeBlock(MBB);
232 MF->erase(MBB);
233 EHScopeMembership.erase(MBB);
234}
235
237 const TargetInstrInfo *tii,
238 const TargetRegisterInfo *tri,
239 MachineLoopInfo *mli, bool AfterPlacement) {
240 if (!tii) return false;
241
242 TriedMerging.clear();
243
245 AfterBlockPlacement = AfterPlacement;
246 TII = tii;
247 TRI = tri;
248 MLI = mli;
249 this->MRI = &MRI;
250
251 if (MinCommonTailLength == 0) {
252 MinCommonTailLength = TailMergeSize.getNumOccurrences() > 0
254 : TII->getTailMergeSize(MF);
255 }
256
257 UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
258 if (!UpdateLiveIns)
259 MRI.invalidateLiveness();
260
261 // Command-line flags take final precedence over the caller-configured values,
262 // letting individual BranchFolding sub-phases be toggled (for tests and for
263 // targets that only want a safe subset of the optimization).
265 EnableHoistCommonCode =
268 EnableBasicBlockReordering =
270
271 bool MadeChange = false;
272
273 // Recalculate EH scope membership.
274 EHScopeMembership = getEHScopeMembership(MF);
275
276 bool MadeChangeThisIteration = true;
277 while (MadeChangeThisIteration) {
278 MadeChangeThisIteration = TailMergeBlocks(MF);
279 // No need to clean up if tail merging does not change anything after the
280 // block placement.
281 if (!AfterBlockPlacement || MadeChangeThisIteration)
282 MadeChangeThisIteration |= OptimizeBranches(MF);
283 if (EnableHoistCommonCode)
284 MadeChangeThisIteration |= HoistCommonCode(MF);
285 MadeChange |= MadeChangeThisIteration;
286 }
287
288 // See if any jump tables have become dead as the code generator
289 // did its thing.
291 if (!JTI)
292 return MadeChange;
293
294 // Walk the function to find jump tables that are live.
295 BitVector JTIsLive(JTI->getJumpTables().size());
296 for (const MachineBasicBlock &BB : MF) {
297 for (const MachineInstr &I : BB)
298 for (const MachineOperand &Op : I.operands()) {
299 if (!Op.isJTI()) continue;
300
301 // Remember that this JT is live.
302 JTIsLive.set(Op.getIndex());
303 }
304 }
305
306 // Finally, remove dead jump tables. This happens when the
307 // indirect jump was unreachable (and thus deleted).
308 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
309 if (!JTIsLive.test(i)) {
310 JTI->RemoveJumpTable(i);
311 MadeChange = true;
312 }
313
314 return MadeChange;
315}
316
317//===----------------------------------------------------------------------===//
318// Tail Merging of Blocks
319//===----------------------------------------------------------------------===//
320
321/// HashMachineInstr - Compute a hash value for MI and its operands.
322static unsigned HashMachineInstr(const MachineInstr &MI) {
323 unsigned Hash = MI.getOpcode();
324 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
325 const MachineOperand &Op = MI.getOperand(i);
326
327 // Merge in bits from the operand if easy. We can't use MachineOperand's
328 // hash_code here because it's not deterministic and we sort by hash value
329 // later.
330 unsigned OperandHash = 0;
331 switch (Op.getType()) {
333 OperandHash = Op.getReg().id();
334 break;
336 OperandHash = Op.getImm();
337 break;
339 OperandHash = Op.getMBB()->getNumber();
340 break;
344 OperandHash = Op.getIndex();
345 break;
348 // Global address / external symbol are too hard, don't bother, but do
349 // pull in the offset.
350 OperandHash = Op.getOffset();
351 break;
352 default:
353 break;
354 }
355
356 Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
357 }
358 return Hash;
359}
360
361/// HashEndOfMBB - Hash the last instruction in the MBB.
362static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
363 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(false);
364 if (I == MBB.end())
365 return 0;
366
367 return HashMachineInstr(*I);
368}
369
370/// Whether MI should be counted as an instruction when calculating common tail.
372 return !(MI.isDebugInstr() || MI.isCFIInstruction());
373}
374
375/// Iterate backwards from the given iterator \p I, towards the beginning of the
376/// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator
377/// pointing to that MI. If no such MI is found, return the end iterator.
381 while (I != MBB->begin()) {
382 --I;
384 return I;
385 }
386 return MBB->end();
387}
388
389/// Given two machine basic blocks, return the number of instructions they
390/// actually have in common together at their end. If a common tail is found (at
391/// least by one instruction), then iterators for the first shared instruction
392/// in each block are returned as well.
393///
394/// Non-instructions according to countsAsInstruction are ignored.
396 MachineBasicBlock *MBB2,
399 MachineBasicBlock::iterator MBBI1 = MBB1->end();
400 MachineBasicBlock::iterator MBBI2 = MBB2->end();
401
402 unsigned TailLen = 0;
403 while (true) {
404 MBBI1 = skipBackwardPastNonInstructions(MBBI1, MBB1);
405 MBBI2 = skipBackwardPastNonInstructions(MBBI2, MBB2);
406 if (MBBI1 == MBB1->end() || MBBI2 == MBB2->end())
407 break;
408 if (!MBBI1->isIdenticalTo(*MBBI2) ||
409 // FIXME: This check is dubious. It's used to get around a problem where
410 // people incorrectly expect inline asm directives to remain in the same
411 // relative order. This is untenable because normal compiler
412 // optimizations (like this one) may reorder and/or merge these
413 // directives.
414 MBBI1->isInlineAsm()) {
415 break;
416 }
417 if (MBBI1->getFlag(MachineInstr::NoMerge) ||
418 MBBI2->getFlag(MachineInstr::NoMerge))
419 break;
420 ++TailLen;
421 I1 = MBBI1;
422 I2 = MBBI2;
423 }
424
425 return TailLen;
426}
427
428void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
429 MachineBasicBlock &NewDest) {
430 if (UpdateLiveIns) {
431 // OldInst should always point to an instruction.
432 MachineBasicBlock &OldMBB = *OldInst->getParent();
433 LiveRegs.clear();
434 LiveRegs.addLiveOuts(OldMBB);
435 // Move backward to the place where will insert the jump.
437 do {
438 --I;
439 LiveRegs.stepBackward(*I);
440 } while (I != OldInst);
441
442 // Merging the tails may have switched some undef operand to non-undef ones.
443 // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
444 // register.
445 for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {
446 // We computed the liveins with computeLiveIn earlier and should only see
447 // full registers:
448 assert(P.LaneMask == LaneBitmask::getAll() &&
449 "Can only handle full register.");
450 MCRegister Reg = P.PhysReg;
451 if (!LiveRegs.available(*MRI, Reg))
452 continue;
453 DebugLoc DL;
454 BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg);
455 }
456 }
457
458 TII->ReplaceTailWithBranchTo(OldInst, &NewDest);
459 ++NumTailMerge;
460}
461
462MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
464 const BasicBlock *BB) {
465 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
466 return nullptr;
467
468 MachineFunction &MF = *CurMBB.getParent();
469
470 // Create the fall-through block.
472 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
473 CurMBB.getParent()->insert(++MBBI, NewMBB);
474
475 // Move all the successors of this block to the specified block.
476 NewMBB->transferSuccessors(&CurMBB);
477
478 // Add an edge from CurMBB to NewMBB for the fall-through.
479 CurMBB.addSuccessor(NewMBB);
480
481 // Splice the code over.
482 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
483
484 // NewMBB belongs to the same loop as CurMBB.
485 if (MLI)
486 if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
487 ML->addBasicBlockToLoop(NewMBB, *MLI);
488
489 // NewMBB inherits CurMBB's block frequency.
490 MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
491
492 if (UpdateLiveIns)
493 computeAndAddLiveIns(LiveRegs, *NewMBB);
494
495 // Add the new block to the EH scope.
496 const auto &EHScopeI = EHScopeMembership.find(&CurMBB);
497 if (EHScopeI != EHScopeMembership.end()) {
498 auto n = EHScopeI->second;
499 EHScopeMembership[NewMBB] = n;
500 }
501
502 return NewMBB;
503}
504
505/// EstimateRuntime - Make a rough estimate for how long it will take to run
506/// the specified code.
509 unsigned Time = 0;
510 for (; I != E; ++I) {
511 if (!countsAsInstruction(*I))
512 continue;
513 if (I->isCall())
514 Time += 10;
515 else if (I->mayLoadOrStore())
516 Time += 2;
517 else
518 ++Time;
519 }
520 return Time;
521}
522
523// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
524// branches temporarily for tail merging). In the case where CurMBB ends
525// with a conditional branch to the next block, optimize by reversing the
526// test and conditionally branching to SuccMBB instead.
527static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
528 const TargetInstrInfo *TII, const DebugLoc &BranchDL) {
529 MachineFunction *MF = CurMBB->getParent();
531 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
533 DebugLoc dl = CurMBB->findBranchDebugLoc();
534 if (!dl)
535 dl = BranchDL;
536 if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
537 MachineBasicBlock *NextBB = &*I;
538 if (TBB == NextBB && !Cond.empty() && !FBB) {
539 if (!TII->reverseBranchCondition(Cond)) {
540 TII->removeBranch(*CurMBB);
541 TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
542 return;
543 }
544 }
545 }
546 TII->insertBranch(*CurMBB, SuccBB, nullptr,
548}
549
550bool
551BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
552 if (getHash() < o.getHash())
553 return true;
554 if (getHash() > o.getHash())
555 return false;
556 if (getBlock()->getNumber() < o.getBlock()->getNumber())
557 return true;
558 if (getBlock()->getNumber() > o.getBlock()->getNumber())
559 return false;
560 return false;
561}
562
563/// CountTerminators - Count the number of terminators in the given
564/// block and set I to the position of the first non-terminator, if there
565/// is one, or MBB->end() otherwise.
568 I = MBB->end();
569 unsigned NumTerms = 0;
570 while (true) {
571 if (I == MBB->begin()) {
572 I = MBB->end();
573 break;
574 }
575 --I;
576 if (!I->isTerminator()) break;
577 ++NumTerms;
578 }
579 return NumTerms;
580}
581
582/// A no successor, non-return block probably ends in unreachable and is cold.
583/// Also consider a block that ends in an indirect branch to be a return block,
584/// since many targets use plain indirect branches to return.
586 if (!MBB->succ_empty())
587 return false;
588 if (MBB->empty())
589 return true;
590 return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
591}
592
593/// ProfitableToMerge - Check if two machine basic blocks have a common tail
594/// and decide if it would be profitable to merge those tails. Return the
595/// length of the common tail and iterators to the first common instruction
596/// in each block.
597/// MBB1, MBB2 The blocks to check
598/// MinCommonTailLength Minimum size of tail block to be merged.
599/// CommonTailLen Out parameter to record the size of the shared tail between
600/// MBB1 and MBB2
601/// I1, I2 Iterator references that will be changed to point to the first
602/// instruction in the common tail shared by MBB1,MBB2
603/// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
604/// relative to SuccBB
605/// PredBB The layout predecessor of SuccBB, if any.
606/// EHScopeMembership map from block to EH scope #.
607/// AfterPlacement True if we are merging blocks after layout. Stricter
608/// thresholds apply to prevent undoing tail-duplication.
609static bool
611 unsigned MinCommonTailLength, unsigned &CommonTailLen,
614 MachineBasicBlock *PredBB,
616 bool AfterPlacement,
617 MBFIWrapper &MBBFreqInfo,
618 ProfileSummaryInfo *PSI) {
619 // It is never profitable to tail-merge blocks from two different EH scopes.
620 if (!EHScopeMembership.empty()) {
621 auto EHScope1 = EHScopeMembership.find(MBB1);
622 assert(EHScope1 != EHScopeMembership.end());
623 auto EHScope2 = EHScopeMembership.find(MBB2);
624 assert(EHScope2 != EHScopeMembership.end());
625 if (EHScope1->second != EHScope2->second)
626 return false;
627 }
628
629 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
630 if (CommonTailLen == 0)
631 return false;
632 LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)
633 << " and " << printMBBReference(*MBB2) << " is "
634 << CommonTailLen << '\n');
635
636 // Move the iterators to the beginning of the MBB if we only got debug
637 // instructions before the tail. This is to avoid splitting a block when we
638 // only got debug instructions before the tail (to be invariant on -g).
639 if (skipDebugInstructionsForward(MBB1->begin(), MBB1->end(), false) == I1)
640 I1 = MBB1->begin();
641 if (skipDebugInstructionsForward(MBB2->begin(), MBB2->end(), false) == I2)
642 I2 = MBB2->begin();
643
644 bool FullBlockTail1 = I1 == MBB1->begin();
645 bool FullBlockTail2 = I2 == MBB2->begin();
646
647 // It's almost always profitable to merge any number of non-terminator
648 // instructions with the block that falls through into the common successor.
649 // This is true only for a single successor. For multiple successors, we are
650 // trading a conditional branch for an unconditional one.
651 // TODO: Re-visit successor size for non-layout tail merging.
652 if ((MBB1 == PredBB || MBB2 == PredBB) &&
653 (!AfterPlacement || MBB1->succ_size() == 1)) {
655 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
656 if (CommonTailLen > NumTerms)
657 return true;
658 }
659
660 // If these are identical non-return blocks with no successors, merge them.
661 // Such blocks are typically cold calls to noreturn functions like abort, and
662 // are unlikely to become a fallthrough target after machine block placement.
663 // Tail merging these blocks is unlikely to create additional unconditional
664 // branches, and will reduce the size of this cold code.
665 if (FullBlockTail1 && FullBlockTail2 &&
667 return true;
668
669 // If one of the blocks can be completely merged and happens to be in
670 // a position where the other could fall through into it, merge any number
671 // of instructions, because it can be done without a branch.
672 // TODO: If the blocks are not adjacent, move one of them so that they are?
673 if (MBB1->isLayoutSuccessor(MBB2) && FullBlockTail2)
674 return true;
675 if (MBB2->isLayoutSuccessor(MBB1) && FullBlockTail1)
676 return true;
677
678 // If both blocks are identical and end in a branch, merge them unless they
679 // both have a fallthrough predecessor and successor.
680 // We can only do this after block placement because it depends on whether
681 // there are fallthroughs, and we don't know until after layout.
682 if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {
683 auto BothFallThrough = [](MachineBasicBlock *MBB) {
684 if (!MBB->succ_empty() && !MBB->canFallThrough())
685 return false;
687 MachineFunction *MF = MBB->getParent();
688 return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
689 };
690 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
691 return true;
692 }
693
694 // If both blocks have an unconditional branch temporarily stripped out,
695 // count that as an additional common instruction for the following
696 // heuristics. This heuristic is only accurate for single-succ blocks, so to
697 // make sure that during layout merging and duplicating don't crash, we check
698 // for that when merging during layout.
699 unsigned EffectiveTailLen = CommonTailLen;
700 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
701 (MBB1->succ_size() == 1 || !AfterPlacement) &&
702 !MBB1->back().isBarrier() &&
703 !MBB2->back().isBarrier())
704 ++EffectiveTailLen;
705
706 // Check if the common tail is long enough to be worthwhile.
707 if (EffectiveTailLen >= MinCommonTailLength)
708 return true;
709
710 // If we are optimizing for code size, 2 instructions in common is enough if
711 // we don't have to split a block. At worst we will be introducing 1 new
712 // branch instruction, which is likely to be smaller than the 2
713 // instructions that would be deleted in the merge.
714 bool OptForSize = llvm::shouldOptimizeForSize(MBB1, PSI, &MBBFreqInfo) &&
715 llvm::shouldOptimizeForSize(MBB2, PSI, &MBBFreqInfo);
716 return EffectiveTailLen >= 2 && OptForSize &&
717 (FullBlockTail1 || FullBlockTail2);
718}
719
720unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
721 unsigned MinCommonTailLength,
722 MachineBasicBlock *SuccBB,
723 MachineBasicBlock *PredBB) {
724 unsigned maxCommonTailLength = 0U;
725 SameTails.clear();
726 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
727 MPIterator HighestMPIter = std::prev(MergePotentials.end());
728 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
729 B = MergePotentials.begin();
730 CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
731 for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
732 unsigned CommonTailLen;
733 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
734 MinCommonTailLength,
735 CommonTailLen, TrialBBI1, TrialBBI2,
736 SuccBB, PredBB,
737 EHScopeMembership,
738 AfterBlockPlacement, MBBFreqInfo, PSI)) {
739 if (CommonTailLen > maxCommonTailLength) {
740 SameTails.clear();
741 maxCommonTailLength = CommonTailLen;
742 HighestMPIter = CurMPIter;
743 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
744 }
745 if (HighestMPIter == CurMPIter &&
746 CommonTailLen == maxCommonTailLength)
747 SameTails.push_back(SameTailElt(I, TrialBBI2));
748 }
749 if (I == B)
750 break;
751 }
752 }
753 return maxCommonTailLength;
754}
755
756void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
757 MachineBasicBlock *SuccBB,
758 MachineBasicBlock *PredBB,
759 const DebugLoc &BranchDL) {
760 MPIterator CurMPIter, B;
761 for (CurMPIter = std::prev(MergePotentials.end()),
762 B = MergePotentials.begin();
763 CurMPIter->getHash() == CurHash; --CurMPIter) {
764 // Put the unconditional branch back, if we need one.
765 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
766 if (SuccBB && CurMBB != PredBB)
767 FixTail(CurMBB, SuccBB, TII, BranchDL);
768 if (CurMPIter == B)
769 break;
770 }
771 if (CurMPIter->getHash() != CurHash)
772 CurMPIter++;
773 MergePotentials.erase(CurMPIter, MergePotentials.end());
774}
775
776bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
777 MachineBasicBlock *SuccBB,
778 unsigned maxCommonTailLength,
779 unsigned &commonTailIndex) {
780 commonTailIndex = 0;
781 unsigned TimeEstimate = ~0U;
782 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
783 // Use PredBB if possible; that doesn't require a new branch.
784 if (SameTails[i].getBlock() == PredBB) {
785 commonTailIndex = i;
786 break;
787 }
788 // Otherwise, make a (fairly bogus) choice based on estimate of
789 // how long it will take the various blocks to execute.
790 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
791 SameTails[i].getTailStartPos());
792 if (t <= TimeEstimate) {
793 TimeEstimate = t;
794 commonTailIndex = i;
795 }
796 }
797
799 SameTails[commonTailIndex].getTailStartPos();
800 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
801
802 LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "
803 << maxCommonTailLength);
804
805 // If the split block unconditionally falls-thru to SuccBB, it will be
806 // merged. In control flow terms it should then take SuccBB's name. e.g. If
807 // SuccBB is an inner loop, the common tail is still part of the inner loop.
808 const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
809 SuccBB->getBasicBlock() : MBB->getBasicBlock();
810 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
811 if (!newMBB) {
812 LLVM_DEBUG(dbgs() << "... failed!");
813 return false;
814 }
815
816 SameTails[commonTailIndex].setBlock(newMBB);
817 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
818
819 // If we split PredBB, newMBB is the new predecessor.
820 if (PredBB == MBB)
821 PredBB = newMBB;
822
823 return true;
824}
825
826/// Ensure undef flag is preserved only when it is present in both instructions.
827static void mergeUndefFlag(MachineInstr &Merged, const MachineInstr &Other) {
828 for (unsigned I = 0, E = Merged.getNumOperands(); I != E; ++I) {
829 MachineOperand &MO = Merged.getOperand(I);
830 if (MO.isReg() && MO.isUndef() && !Other.getOperand(I).isUndef())
831 MO.setIsUndef(false);
832 }
833}
834
835static void
837 MachineBasicBlock &MBBCommon) {
838 MachineBasicBlock *MBB = MBBIStartPos->getParent();
839 // Note CommonTailLen does not necessarily matches the size of
840 // the common BB nor all its instructions because of debug
841 // instructions differences.
842 unsigned CommonTailLen = 0;
843 for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
844 ++CommonTailLen;
845
848 MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
849 MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
850
851 while (CommonTailLen--) {
852 assert(MBBI != MBBIE && "Reached BB end within common tail length!");
853 (void)MBBIE;
854
855 if (!countsAsInstruction(*MBBI)) {
856 ++MBBI;
857 continue;
858 }
859
860 while ((MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon))
861 ++MBBICommon;
862
863 assert(MBBICommon != MBBIECommon &&
864 "Reached BB end within common tail length!");
865 assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
866
867 // Merge MMOs from memory operations in the common block.
868 if (MBBICommon->mayLoadOrStore())
869 MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI});
870
871 // Drop undef flags if they aren't present in all merged instructions.
872 mergeUndefFlag(*MBBICommon, *MBBI);
873
874 ++MBBI;
875 ++MBBICommon;
876 }
877}
878
879void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {
880 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
881
882 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
883 for (unsigned int i = 0 ; i != SameTails.size() ; ++i) {
884 if (i != commonTailIndex) {
885 NextCommonInsts[i] = SameTails[i].getTailStartPos();
886 mergeOperations(SameTails[i].getTailStartPos(), *MBB);
887 } else {
888 assert(SameTails[i].getTailStartPos() == MBB->begin() &&
889 "MBB is not a common tail only block");
890 }
891 }
892
893 for (auto &MI : *MBB) {
895 continue;
896 DebugLoc DL = MI.getDebugLoc();
897 for (unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
898 if (i == commonTailIndex)
899 continue;
900
901 auto &Pos = NextCommonInsts[i];
902 assert(Pos != SameTails[i].getBlock()->end() &&
903 "Reached BB end within common tail");
904 while (!countsAsInstruction(*Pos)) {
905 ++Pos;
906 assert(Pos != SameTails[i].getBlock()->end() &&
907 "Reached BB end within common tail");
908 }
909 assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
910 DL = DebugLoc::getMergedLocation(DL, Pos->getDebugLoc());
911 NextCommonInsts[i] = ++Pos;
912 }
913 MI.setDebugLoc(DL);
914 }
915
916 if (UpdateLiveIns) {
917 LivePhysRegs NewLiveIns(*TRI);
918 computeLiveIns(NewLiveIns, *MBB);
919 LiveRegs.init(*TRI);
920
921 // The flag merging may lead to some register uses no longer using the
922 // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
923 for (MachineBasicBlock *Pred : MBB->predecessors()) {
924 LiveRegs.clear();
925 LiveRegs.addLiveOuts(*Pred);
926 MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();
927 for (Register Reg : NewLiveIns) {
928 if (!LiveRegs.available(*MRI, Reg))
929 continue;
930
931 // Skip the register if we are about to add one of its super registers.
932 // TODO: Common this up with the same logic in addLineIns().
933 if (any_of(TRI->superregs(Reg), [&](MCPhysReg SReg) {
934 return NewLiveIns.contains(SReg) && !MRI->isReserved(SReg);
935 }))
936 continue;
937
938 DebugLoc DL;
939 BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF),
940 Reg);
941 }
942 }
943
944 MBB->clearLiveIns();
945 addLiveIns(*MBB, NewLiveIns);
946 }
947}
948
949// See if any of the blocks in MergePotentials (which all have SuccBB as a
950// successor, or all have no successor if it is null) can be tail-merged.
951// If there is a successor, any blocks in MergePotentials that are not
952// tail-merged and are not immediately before Succ must have an unconditional
953// branch to Succ added (but the predecessor/successor lists need no
954// adjustment). The lone predecessor of Succ that falls through into Succ,
955// if any, is given in PredBB.
956// MinCommonTailLength - Except for the special cases below, tail-merge if
957// there are at least this many instructions in common.
958bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
959 MachineBasicBlock *PredBB,
960 unsigned MinCommonTailLength) {
961 bool MadeChange = false;
962
963 LLVM_DEBUG({
964 dbgs() << "\nTryTailMergeBlocks: ";
965 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
966 dbgs() << printMBBReference(*MergePotentials[i].getBlock())
967 << (i == e - 1 ? "" : ", ");
968 dbgs() << "\n";
969 if (SuccBB) {
970 dbgs() << " with successor " << printMBBReference(*SuccBB) << '\n';
971 if (PredBB)
972 dbgs() << " which has fall-through from " << printMBBReference(*PredBB)
973 << "\n";
974 }
975 dbgs() << "Looking for common tails of at least " << MinCommonTailLength
976 << " instruction" << (MinCommonTailLength == 1 ? "" : "s") << '\n';
977 });
978
979 // Sort by hash value so that blocks with identical end sequences sort
980 // together.
981#if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN
982 // If origin-tracking is enabled then MergePotentialElt is no longer a POD
983 // type, so we need std::sort instead.
984 std::sort(MergePotentials.begin(), MergePotentials.end());
985#else
986 array_pod_sort(MergePotentials.begin(), MergePotentials.end());
987#endif
988
989 // Walk through equivalence sets looking for actual exact matches.
990 while (MergePotentials.size() > 1) {
991 unsigned CurHash = MergePotentials.back().getHash();
992 const DebugLoc &BranchDL = MergePotentials.back().getBranchDebugLoc();
993
994 // Build SameTails, identifying the set of blocks with this hash code
995 // and with the maximum number of instructions in common.
996 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
997 MinCommonTailLength,
998 SuccBB, PredBB);
999
1000 // If we didn't find any pair that has at least MinCommonTailLength
1001 // instructions in common, remove all blocks with this hash code and retry.
1002 if (SameTails.empty()) {
1003 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
1004 continue;
1005 }
1006
1007 // If one of the blocks is the entire common tail (and is not the entry
1008 // block/an EH pad, which we can't jump to), we can treat all blocks with
1009 // this same tail at once. Use PredBB if that is one of the possibilities,
1010 // as that will not introduce any extra branches.
1011 MachineBasicBlock *EntryBB =
1012 &MergePotentials.front().getBlock()->getParent()->front();
1013 unsigned commonTailIndex = SameTails.size();
1014 // If there are two blocks, check to see if one can be made to fall through
1015 // into the other.
1016 if (SameTails.size() == 2 &&
1017 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
1018 SameTails[1].tailIsWholeBlock() && !SameTails[1].getBlock()->isEHPad())
1019 commonTailIndex = 1;
1020 else if (SameTails.size() == 2 &&
1021 SameTails[1].getBlock()->isLayoutSuccessor(
1022 SameTails[0].getBlock()) &&
1023 SameTails[0].tailIsWholeBlock() &&
1024 !SameTails[0].getBlock()->isEHPad())
1025 commonTailIndex = 0;
1026 else {
1027 // Otherwise just pick one, favoring the fall-through predecessor if
1028 // there is one.
1029 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
1030 MachineBasicBlock *MBB = SameTails[i].getBlock();
1031 if ((MBB == EntryBB || MBB->isEHPad()) &&
1032 SameTails[i].tailIsWholeBlock())
1033 continue;
1034 if (MBB == PredBB) {
1035 commonTailIndex = i;
1036 break;
1037 }
1038 if (SameTails[i].tailIsWholeBlock())
1039 commonTailIndex = i;
1040 }
1041 }
1042
1043 if (commonTailIndex == SameTails.size() ||
1044 (SameTails[commonTailIndex].getBlock() == PredBB &&
1045 !SameTails[commonTailIndex].tailIsWholeBlock())) {
1046 // None of the blocks consist entirely of the common tail.
1047 // Split a block so that one does.
1048 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
1049 maxCommonTailLength, commonTailIndex)) {
1050 RemoveBlocksWithHash(CurHash, SuccBB, PredBB, BranchDL);
1051 continue;
1052 }
1053 }
1054
1055 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
1056
1057 // Recompute common tail MBB's edge weights and block frequency.
1058 setCommonTailEdgeWeights(*MBB);
1059
1060 // Merge debug locations, MMOs and undef flags across identical instructions
1061 // for common tail.
1062 mergeCommonTails(commonTailIndex);
1063
1064 // MBB is common tail. Adjust all other BB's to jump to this one.
1065 // Traversal must be forwards so erases work.
1066 LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)
1067 << " for ");
1068 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
1069 if (commonTailIndex == i)
1070 continue;
1071 LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())
1072 << (i == e - 1 ? "" : ", "));
1073 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
1074 replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);
1075 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
1076 MergePotentials.erase(SameTails[i].getMPIter());
1077 }
1078 LLVM_DEBUG(dbgs() << "\n");
1079 // We leave commonTailIndex in the worklist in case there are other blocks
1080 // that match it with a smaller number of instructions.
1081 MadeChange = true;
1082 }
1083 return MadeChange;
1084}
1085
1086bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
1087 bool MadeChange = false;
1088 if (!EnableTailMerge)
1089 return MadeChange;
1090
1091 // First find blocks with no successors.
1092 // Block placement may create new tail merging opportunities for these blocks.
1093 MergePotentials.clear();
1094 for (MachineBasicBlock &MBB : MF) {
1095 if (MergePotentials.size() == TailMergeThreshold)
1096 break;
1097 if (!TriedMerging.count(&MBB) && MBB.succ_empty())
1098 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB,
1100 }
1101
1102 // If this is a large problem, avoid visiting the same basic blocks
1103 // multiple times.
1104 if (MergePotentials.size() == TailMergeThreshold)
1105 for (const MergePotentialsElt &Elt : MergePotentials)
1106 TriedMerging.insert(Elt.getBlock());
1107
1108 // See if we can do any tail merging on those.
1109 if (MergePotentials.size() >= 2)
1110 MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
1111
1112 // Look at blocks (IBB) with multiple predecessors (PBB).
1113 // We change each predecessor to a canonical form, by
1114 // (1) temporarily removing any unconditional branch from the predecessor
1115 // to IBB, and
1116 // (2) alter conditional branches so they branch to the other block
1117 // not IBB; this may require adding back an unconditional branch to IBB
1118 // later, where there wasn't one coming in. E.g.
1119 // Bcc IBB
1120 // fallthrough to QBB
1121 // here becomes
1122 // Bncc QBB
1123 // with a conceptual B to IBB after that, which never actually exists.
1124 // With those changes, we see whether the predecessors' tails match,
1125 // and merge them if so. We change things out of canonical form and
1126 // back to the way they were later in the process. (OptimizeBranches
1127 // would undo some of this, but we can't use it, because we'd get into
1128 // a compile-time infinite loop repeatedly doing and undoing the same
1129 // transformations.)
1130
1131 for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1132 I != E; ++I) {
1133 if (I->pred_size() < 2) continue;
1134 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
1135 MachineBasicBlock *IBB = &*I;
1136 MachineBasicBlock *PredBB = &*std::prev(I);
1137 MergePotentials.clear();
1138 MachineLoop *ML;
1139
1140 // Bail if merging after placement and IBB is the loop header because
1141 // -- If merging predecessors that belong to the same loop as IBB, the
1142 // common tail of merged predecessors may become the loop top if block
1143 // placement is called again and the predecessors may branch to this common
1144 // tail and require more branches. This can be relaxed if
1145 // MachineBlockPlacement::findBestLoopTop is more flexible.
1146 // --If merging predecessors that do not belong to the same loop as IBB, the
1147 // loop info of IBB's loop and the other loops may be affected. Calling the
1148 // block placement again may make big change to the layout and eliminate the
1149 // reason to do tail merging here.
1150 if (AfterBlockPlacement && MLI) {
1151 ML = MLI->getLoopFor(IBB);
1152 if (ML && IBB == ML->getHeader())
1153 continue;
1154 }
1155
1156 for (MachineBasicBlock *PBB : I->predecessors()) {
1157 if (MergePotentials.size() == TailMergeThreshold)
1158 break;
1159
1160 if (TriedMerging.count(PBB))
1161 continue;
1162
1163 // Skip blocks that loop to themselves, can't tail merge these.
1164 if (PBB == IBB)
1165 continue;
1166
1167 // Visit each predecessor only once.
1168 if (!UniquePreds.insert(PBB).second)
1169 continue;
1170
1171 // Skip blocks which may jump to a landing pad or jump from an asm blob.
1172 // Can't tail merge these.
1173 if (PBB->hasEHPadSuccessor() || PBB->mayHaveInlineAsmBr())
1174 continue;
1175
1176 // After block placement, only consider predecessors that belong to the
1177 // same loop as IBB. The reason is the same as above when skipping loop
1178 // header.
1179 if (AfterBlockPlacement && MLI)
1180 if (ML != MLI->getLoopFor(PBB))
1181 continue;
1182
1183 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1185 if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1186 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1187 // branch.
1189 if (!Cond.empty() && TBB == IBB) {
1190 if (TII->reverseBranchCondition(NewCond))
1191 continue;
1192 // This is the QBB case described above
1193 if (!FBB) {
1194 auto Next = ++PBB->getIterator();
1195 if (Next != MF.end())
1196 FBB = &*Next;
1197 }
1198 }
1199
1200 // Remove the unconditional branch at the end, if any.
1201 DebugLoc dl = PBB->findBranchDebugLoc();
1202 if (TBB && (Cond.empty() || FBB)) {
1203 TII->removeBranch(*PBB);
1204 if (!Cond.empty())
1205 // reinsert conditional branch only, for now
1206 TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1207 NewCond, dl);
1208 }
1209
1210 MergePotentials.push_back(
1211 MergePotentialsElt(HashEndOfMBB(*PBB), PBB, dl));
1212 }
1213 }
1214
1215 // If this is a large problem, avoid visiting the same basic blocks multiple
1216 // times.
1217 if (MergePotentials.size() == TailMergeThreshold)
1218 for (MergePotentialsElt &Elt : MergePotentials)
1219 TriedMerging.insert(Elt.getBlock());
1220
1221 if (MergePotentials.size() >= 2)
1222 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1223
1224 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1225 // result of removing blocks in TryTailMergeBlocks.
1226 PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1227 if (MergePotentials.size() == 1 &&
1228 MergePotentials.begin()->getBlock() != PredBB)
1229 FixTail(MergePotentials.begin()->getBlock(), IBB, TII,
1230 MergePotentials.begin()->getBranchDebugLoc());
1231 }
1232
1233 return MadeChange;
1234}
1235
1236void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1237 SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1238 BlockFrequency AccumulatedMBBFreq;
1239
1240 // Aggregate edge frequency of successor edge j:
1241 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1242 // where bb is a basic block that is in SameTails.
1243 for (const auto &Src : SameTails) {
1244 const MachineBasicBlock *SrcMBB = Src.getBlock();
1245 BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1246 AccumulatedMBBFreq += BlockFreq;
1247
1248 // It is not necessary to recompute edge weights if TailBB has less than two
1249 // successors.
1250 if (TailMBB.succ_size() <= 1)
1251 continue;
1252
1253 auto EdgeFreq = EdgeFreqLs.begin();
1254
1255 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1256 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1257 *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1258 }
1259
1260 MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1261
1262 if (TailMBB.succ_size() <= 1)
1263 return;
1264
1265 auto SumEdgeFreq =
1266 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1267 .getFrequency();
1268 auto EdgeFreq = EdgeFreqLs.begin();
1269
1270 if (SumEdgeFreq > 0) {
1271 for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1272 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1274 EdgeFreq->getFrequency(), SumEdgeFreq);
1275 TailMBB.setSuccProbability(SuccI, Prob);
1276 }
1277 }
1278}
1279
1280//===----------------------------------------------------------------------===//
1281// Branch Optimization
1282//===----------------------------------------------------------------------===//
1283
1284bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1285 bool MadeChange = false;
1286
1287 // Make sure blocks are numbered in order
1288 MF.RenumberBlocks();
1289 // Renumbering blocks alters EH scope membership, recalculate it.
1290 EHScopeMembership = getEHScopeMembership(MF);
1291
1292 for (MachineBasicBlock &MBB :
1294 MadeChange |= OptimizeBlock(&MBB);
1295
1296 // If it is dead, remove it.
1298 !MBB.isEHPad()) {
1299 RemoveDeadBlock(&MBB);
1300 MadeChange = true;
1301 ++NumDeadBlocks;
1302 }
1303 }
1304
1305 return MadeChange;
1306}
1307
1308// Blocks should be considered empty if they contain only debug info;
1309// else the debug info would affect codegen.
1311 return MBB->getFirstNonDebugInstr(true) == MBB->end();
1312}
1313
1314// Blocks with only debug info and branches should be considered the same
1315// as blocks with only branches.
1317 MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1318 assert(I != MBB->end() && "empty block!");
1319 return I->isBranch();
1320}
1321
1322/// IsBetterFallthrough - Return true if it would be clearly better to
1323/// fall-through to MBB1 than to fall through into MBB2. This has to return
1324/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1325/// result in infinite loops.
1327 MachineBasicBlock *MBB2) {
1328 assert(MBB1 && MBB2 && "Unknown MachineBasicBlock");
1329
1330 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1331 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1332 // optimize branches that branch to either a return block or an assert block
1333 // into a fallthrough to the return.
1336 if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1337 return false;
1338
1339 // If there is a clear successor ordering we make sure that one block
1340 // will fall through to the next
1341 if (MBB1->isSuccessor(MBB2)) return true;
1342 if (MBB2->isSuccessor(MBB1)) return false;
1343
1344 return MBB2I->isCall() && !MBB1I->isCall();
1345}
1346
1349 MachineBasicBlock &PredMBB) {
1350 auto InsertBefore = PredMBB.getFirstTerminator();
1351 for (MachineInstr &MI : MBB.instrs())
1352 if (MI.isDebugInstr()) {
1353 TII->duplicate(PredMBB, InsertBefore, MI);
1354 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
1355 << MI);
1356 }
1357}
1358
1361 MachineBasicBlock &SuccMBB) {
1362 auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin());
1363 for (MachineInstr &MI : MBB.instrs())
1364 if (MI.isDebugInstr()) {
1365 TII->duplicate(SuccMBB, InsertBefore, MI);
1366 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
1367 << MI);
1368 }
1369}
1370
1371// Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
1372// a basic block is removed we would lose the debug information unless we have
1373// copied the information to a predecessor/successor.
1374//
1375// TODO: This function only handles some simple cases. An alternative would be
1376// to run a heavier analysis, such as the LiveDebugValues pass, before we do
1377// branch folding.
1380 assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");
1381 // If this MBB is the only predecessor of a successor it is legal to copy
1382 // DBG_VALUE instructions to the beginning of the successor.
1383 for (MachineBasicBlock *SuccBB : MBB.successors())
1384 if (SuccBB->pred_size() == 1)
1385 copyDebugInfoToSuccessor(TII, MBB, *SuccBB);
1386 // If this MBB is the only successor of a predecessor it is legal to copy the
1387 // DBG_VALUE instructions to the end of the predecessor (just before the
1388 // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
1389 for (MachineBasicBlock *PredBB : MBB.predecessors())
1390 if (PredBB->succ_size() == 1)
1392}
1393
1394bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1395 bool MadeChange = false;
1396 MachineFunction &MF = *MBB->getParent();
1397ReoptimizeBlock:
1398
1399 MachineFunction::iterator FallThrough = MBB->getIterator();
1400 ++FallThrough;
1401
1402 // Make sure MBB and FallThrough belong to the same EH scope.
1403 bool SameEHScope = true;
1404 if (!EHScopeMembership.empty() && FallThrough != MF.end()) {
1405 auto MBBEHScope = EHScopeMembership.find(MBB);
1406 assert(MBBEHScope != EHScopeMembership.end());
1407 auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);
1408 assert(FallThroughEHScope != EHScopeMembership.end());
1409 SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
1410 }
1411
1412 // Analyze the branch in the current block. As a side-effect, this may cause
1413 // the block to become empty.
1414 MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1416 bool CurUnAnalyzable =
1417 TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1418
1419 // If this block is empty, make everyone use its fall-through, not the block
1420 // explicitly. Landing pads should not do this since the landing-pad table
1421 // points to this block. Blocks with their addresses taken shouldn't be
1422 // optimized away.
1423 if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1424 SameEHScope) {
1426 // Dead block? Leave for cleanup later.
1427 if (MBB->pred_empty()) return MadeChange;
1428
1429 if (FallThrough == MF.end()) {
1430 // TODO: Simplify preds to not branch here if possible!
1431 } else if (FallThrough->isEHPad()) {
1432 // Don't rewrite to a landing pad fallthough. That could lead to the case
1433 // where a BB jumps to more than one landing pad.
1434 // TODO: Is it ever worth rewriting predecessors which don't already
1435 // jump to a landing pad, and so can safely jump to the fallthrough?
1436 } else if (MBB->isSuccessor(&*FallThrough)) {
1437 // Rewrite all predecessors of the old block to go to the fallthrough
1438 // instead.
1439 while (!MBB->pred_empty()) {
1440 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1441 Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1442 }
1443 // Add rest successors of MBB to successors of FallThrough. Those
1444 // successors are not directly reachable via MBB, so it should be
1445 // landing-pad.
1446 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
1447 if (*SI != &*FallThrough && !FallThrough->isSuccessor(*SI)) {
1448 assert((*SI)->isEHPad() && "Bad CFG");
1449 FallThrough->copySuccessor(MBB, SI);
1450 }
1451 // If MBB was the target of a jump table, update jump tables to go to the
1452 // fallthrough instead.
1453 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1454 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1455 MadeChange = true;
1456 }
1457 return MadeChange;
1458 }
1459
1460 // Check to see if we can simplify the terminator of the block before this
1461 // one.
1462 MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1463
1464 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1466 bool PriorUnAnalyzable =
1467 TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1468 if (!PriorUnAnalyzable) {
1469 // If the previous branch is conditional and both conditions go to the same
1470 // destination, remove the branch, replacing it with an unconditional one or
1471 // a fall-through.
1472 if (PriorTBB && PriorTBB == PriorFBB) {
1473 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1474 TII->removeBranch(PrevBB);
1475 PriorCond.clear();
1476 if (PriorTBB != MBB)
1477 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, Dl);
1478 MadeChange = true;
1479 ++NumBranchOpts;
1480 goto ReoptimizeBlock;
1481 }
1482
1483 // If the previous block unconditionally falls through to this block and
1484 // this block has no other predecessors, move the contents of this block
1485 // into the prior block. This doesn't usually happen when SimplifyCFG
1486 // has been used, but it can happen if tail merging splits a fall-through
1487 // predecessor of a block.
1488 // This has to check PrevBB->succ_size() because EH edges are ignored by
1489 // analyzeBranch.
1490 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1491 PrevBB.succ_size() == 1 && PrevBB.isSuccessor(MBB) &&
1492 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1493 LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1494 << "From MBB: " << *MBB);
1495 // Remove redundant DBG_VALUEs first.
1496 if (!PrevBB.empty()) {
1497 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1498 --PrevBBIter;
1500 // Check if DBG_VALUE at the end of PrevBB is identical to the
1501 // DBG_VALUE at the beginning of MBB.
1502 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1503 && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {
1504 if (!MBBIter->isIdenticalTo(*PrevBBIter))
1505 break;
1506 MachineInstr &DuplicateDbg = *MBBIter;
1507 ++MBBIter; -- PrevBBIter;
1508 DuplicateDbg.eraseFromParent();
1509 }
1510 }
1511 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1512 PrevBB.removeSuccessor(PrevBB.succ_begin());
1513 assert(PrevBB.succ_empty());
1514 PrevBB.transferSuccessors(MBB);
1515 MadeChange = true;
1516 return MadeChange;
1517 }
1518
1519 // If the previous branch *only* branches to *this* block (conditional or
1520 // not) remove the branch.
1521 if (PriorTBB == MBB && !PriorFBB) {
1522 TII->removeBranch(PrevBB);
1523 MadeChange = true;
1524 ++NumBranchOpts;
1525 goto ReoptimizeBlock;
1526 }
1527
1528 // If the prior block branches somewhere else on the condition and here if
1529 // the condition is false, remove the uncond second branch.
1530 if (PriorFBB == MBB) {
1531 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1532 TII->removeBranch(PrevBB);
1533 TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, Dl);
1534 MadeChange = true;
1535 ++NumBranchOpts;
1536 goto ReoptimizeBlock;
1537 }
1538
1539 // If the prior block branches here on true and somewhere else on false, and
1540 // if the branch condition is reversible, reverse the branch to create a
1541 // fall-through.
1542 if (PriorTBB == MBB) {
1543 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1544 if (!TII->reverseBranchCondition(NewPriorCond)) {
1545 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1546 TII->removeBranch(PrevBB);
1547 TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, Dl);
1548 MadeChange = true;
1549 ++NumBranchOpts;
1550 goto ReoptimizeBlock;
1551 }
1552 }
1553
1554 // If this block has no successors (e.g. it is a return block or ends with
1555 // a call to a no-return function like abort or __cxa_throw) and if the pred
1556 // falls through into this block, and if it would otherwise fall through
1557 // into the block after this, move this block to the end of the function.
1558 //
1559 // We consider it more likely that execution will stay in the function (e.g.
1560 // due to loops) than it is to exit it. This asserts in loops etc, moving
1561 // the assert condition out of the loop body.
1562 if (EnableBasicBlockReordering && MBB->succ_empty() && !PriorCond.empty() &&
1563 !PriorFBB && MachineFunction::iterator(PriorTBB) == FallThrough &&
1564 !MBB->canFallThrough()) {
1565 bool DoTransform = true;
1566
1567 // We have to be careful that the succs of PredBB aren't both no-successor
1568 // blocks. If neither have successors and if PredBB is the second from
1569 // last block in the function, we'd just keep swapping the two blocks for
1570 // last. Only do the swap if one is clearly better to fall through than
1571 // the other.
1572 if (FallThrough == --MF.end() &&
1573 !IsBetterFallthrough(PriorTBB, MBB))
1574 DoTransform = false;
1575
1576 if (DoTransform) {
1577 // Reverse the branch so we will fall through on the previous true cond.
1578 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1579 if (!TII->reverseBranchCondition(NewPriorCond)) {
1580 LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1581 << "To make fallthrough to: " << *PriorTBB << "\n");
1582
1583 DebugLoc Dl = PrevBB.findBranchDebugLoc();
1584 TII->removeBranch(PrevBB);
1585 TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, Dl);
1586
1587 // Move this block to the end of the function.
1588 MBB->moveAfter(&MF.back());
1589 MadeChange = true;
1590 ++NumBranchOpts;
1591 return MadeChange;
1592 }
1593 }
1594 }
1595 }
1596
1597 if (!IsEmptyBlock(MBB)) {
1598 MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1599 if (TII->isUnconditionalTailCall(TailCall)) {
1601 for (auto &Pred : MBB->predecessors()) {
1602 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1604 bool PredAnalyzable =
1605 !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1606
1607 // Only eliminate if MBB == TBB (Taken Basic Block)
1608 if (PredAnalyzable && !PredCond.empty() && PredTBB == MBB &&
1609 PredTBB != PredFBB) {
1610 // The predecessor has a conditional branch to this block which
1611 // consists of only a tail call. Try to fold the tail call into the
1612 // conditional branch.
1613 if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1614 // TODO: It would be nice if analyzeBranch() could provide a pointer
1615 // to the branch instruction so replaceBranchWithTailCall() doesn't
1616 // have to search for it.
1617 TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1618 PredsChanged.push_back(Pred);
1619 }
1620 }
1621 // If the predecessor is falling through to this block, we could reverse
1622 // the branch condition and fold the tail call into that. However, after
1623 // that we might have to re-arrange the CFG to fall through to the other
1624 // block and there is a high risk of regressing code size rather than
1625 // improving it.
1626 }
1627 if (!PredsChanged.empty()) {
1628 NumTailCalls += PredsChanged.size();
1629 for (auto &Pred : PredsChanged)
1630 Pred->removeSuccessor(MBB);
1631
1632 return true;
1633 }
1634 }
1635 }
1636
1637 if (!CurUnAnalyzable) {
1638 // If this is a two-way branch, and the FBB branches to this block, reverse
1639 // the condition so the single-basic-block loop is faster. Instead of:
1640 // Loop: xxx; jcc Out; jmp Loop
1641 // we want:
1642 // Loop: xxx; jncc Loop; jmp Out
1643 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1644 SmallVector<MachineOperand, 4> NewCond(CurCond);
1645 if (!TII->reverseBranchCondition(NewCond)) {
1647 TII->removeBranch(*MBB);
1648 TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, Dl);
1649 MadeChange = true;
1650 ++NumBranchOpts;
1651 goto ReoptimizeBlock;
1652 }
1653 }
1654
1655 // If this branch is the only thing in its block, see if we can forward
1656 // other blocks across it.
1657 if (CurTBB && CurCond.empty() && !CurFBB &&
1658 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1659 !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1661 // This block may contain just an unconditional branch. Because there can
1662 // be 'non-branch terminators' in the block, try removing the branch and
1663 // then seeing if the block is empty.
1664 TII->removeBranch(*MBB);
1665 // If the only things remaining in the block are debug info, remove these
1666 // as well, so this will behave the same as an empty block in non-debug
1667 // mode.
1668 if (IsEmptyBlock(MBB)) {
1669 // Make the block empty, losing the debug info (we could probably
1670 // improve this in some cases.)
1671 MBB->erase(MBB->begin(), MBB->end());
1672 }
1673 // If this block is just an unconditional branch to CurTBB, we can
1674 // usually completely eliminate the block. The only case we cannot
1675 // completely eliminate the block is when the block before this one
1676 // falls through into MBB and we can't understand the prior block's branch
1677 // condition.
1678 if (MBB->empty()) {
1679 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1680 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1681 !PrevBB.isSuccessor(MBB)) {
1682 // If the prior block falls through into us, turn it into an
1683 // explicit branch to us to make updates simpler.
1684 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1685 PriorTBB != MBB && PriorFBB != MBB) {
1686 if (!PriorTBB) {
1687 assert(PriorCond.empty() && !PriorFBB &&
1688 "Bad branch analysis");
1689 PriorTBB = MBB;
1690 } else {
1691 assert(!PriorFBB && "Machine CFG out of date!");
1692 PriorFBB = MBB;
1693 }
1694 DebugLoc PrevDl = PrevBB.findBranchDebugLoc();
1695 TII->removeBranch(PrevBB);
1696 TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, PrevDl);
1697 }
1698
1699 // Iterate through all the predecessors, revectoring each in-turn.
1700 size_t PI = 0;
1701 bool DidChange = false;
1702 bool HasBranchToSelf = false;
1703 while(PI != MBB->pred_size()) {
1704 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1705 if (PMBB == MBB) {
1706 // If this block has an uncond branch to itself, leave it.
1707 ++PI;
1708 HasBranchToSelf = true;
1709 } else {
1710 DidChange = true;
1711 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1712 // Add rest successors of MBB to successors of CurTBB. Those
1713 // successors are not directly reachable via MBB, so it should be
1714 // landing-pad.
1715 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE;
1716 ++SI)
1717 if (*SI != CurTBB && !CurTBB->isSuccessor(*SI)) {
1718 assert((*SI)->isEHPad() && "Bad CFG");
1719 CurTBB->copySuccessor(MBB, SI);
1720 }
1721 // If this change resulted in PMBB ending in a conditional
1722 // branch where both conditions go to the same destination,
1723 // change this to an unconditional branch.
1724 MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1726 bool NewCurUnAnalyzable = TII->analyzeBranch(
1727 *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1728 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1729 DebugLoc PrevDl = PMBB->findBranchDebugLoc();
1730 TII->removeBranch(*PMBB);
1731 NewCurCond.clear();
1732 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond,
1733 PrevDl);
1734 MadeChange = true;
1735 ++NumBranchOpts;
1736 }
1737 }
1738 }
1739
1740 // Change any jumptables to go to the new MBB.
1741 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1742 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1743 if (DidChange) {
1744 ++NumBranchOpts;
1745 MadeChange = true;
1746 if (!HasBranchToSelf) return MadeChange;
1747 }
1748 }
1749 }
1750
1751 // Add the branch back if the block is more than just an uncond branch.
1752 TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, Dl);
1753 }
1754 }
1755
1756 // If the prior block doesn't fall through into this block, and if this
1757 // block doesn't fall through into some other block, see if we can find a
1758 // place to move this block where a fall-through will happen.
1759 if (EnableBasicBlockReordering && !PrevBB.canFallThrough()) {
1760 // Now we know that there was no fall-through into this block, check to
1761 // see if it has a fall-through into its successor.
1762 bool CurFallsThru = MBB->canFallThrough();
1763
1764 if (!MBB->isEHPad()) {
1765 // Check all the predecessors of this block. If one of them has no fall
1766 // throughs, and analyzeBranch thinks it _could_ fallthrough to this
1767 // block, move this block right after it.
1768 for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1769 // Analyze the branch at the end of the pred.
1770 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1772 if (PredBB != MBB && !PredBB->canFallThrough() &&
1773 !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1774 (PredTBB == MBB || PredFBB == MBB) &&
1775 (!CurFallsThru || !CurTBB || !CurFBB) &&
1776 (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1777 // If the current block doesn't fall through, just move it.
1778 // If the current block can fall through and does not end with a
1779 // conditional branch, we need to append an unconditional jump to
1780 // the (current) next block. To avoid a possible compile-time
1781 // infinite loop, move blocks only backward in this case.
1782 // Also, if there are already 2 branches here, we cannot add a third;
1783 // this means we have the case
1784 // Bcc next
1785 // B elsewhere
1786 // next:
1787 if (CurFallsThru) {
1788 MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1789 CurCond.clear();
1790 TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1791 }
1792 MBB->moveAfter(PredBB);
1793 MadeChange = true;
1794 goto ReoptimizeBlock;
1795 }
1796 }
1797 }
1798
1799 if (!CurFallsThru) {
1800 // Check analyzable branch-successors to see if we can move this block
1801 // before one.
1802 if (!CurUnAnalyzable) {
1803 for (MachineBasicBlock *SuccBB : {CurFBB, CurTBB}) {
1804 if (!SuccBB)
1805 continue;
1806 // Analyze the branch at the end of the block before the succ.
1807 MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1808
1809 // If this block doesn't already fall-through to that successor, and
1810 // if the succ doesn't already have a block that can fall through into
1811 // it, we can arrange for the fallthrough to happen.
1812 if (SuccBB != MBB && &*SuccPrev != MBB &&
1813 !SuccPrev->canFallThrough()) {
1814 MBB->moveBefore(SuccBB);
1815 MadeChange = true;
1816 goto ReoptimizeBlock;
1817 }
1818 }
1819 }
1820
1821 // Okay, there is no really great place to put this block. If, however,
1822 // the block before this one would be a fall-through if this block were
1823 // removed, move this block to the end of the function. There is no real
1824 // advantage in "falling through" to an EH block, so we don't want to
1825 // perform this transformation for that case.
1826 //
1827 // Also, Windows EH introduced the possibility of an arbitrary number of
1828 // successors to a given block. The analyzeBranch call does not consider
1829 // exception handling and so we can get in a state where a block
1830 // containing a call is followed by multiple EH blocks that would be
1831 // rotated infinitely at the end of the function if the transformation
1832 // below were performed for EH "FallThrough" blocks. Therefore, even if
1833 // that appears not to be happening anymore, we should assume that it is
1834 // possible and not remove the "!FallThrough()->isEHPad" condition below.
1835 //
1836 // Similarly, the analyzeBranch call does not consider callbr, which also
1837 // introduces the possibility of infinite rotation, as there may be
1838 // multiple successors of PrevBB. Thus we check such case by
1839 // FallThrough->isInlineAsmBrIndirectTarget().
1840 // NOTE: Checking if PrevBB contains callbr is more precise, but much
1841 // more expensive.
1842 MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1844
1845 if (FallThrough != MF.end() && !FallThrough->isEHPad() &&
1846 !FallThrough->isInlineAsmBrIndirectTarget() &&
1847 !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1848 PrevBB.isSuccessor(&*FallThrough)) {
1849 MBB->moveAfter(&MF.back());
1850 MadeChange = true;
1851 return MadeChange;
1852 }
1853 }
1854 }
1855
1856 return MadeChange;
1857}
1858
1859//===----------------------------------------------------------------------===//
1860// Hoist Common Code
1861//===----------------------------------------------------------------------===//
1862
1863bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1864 bool MadeChange = false;
1865 for (MachineBasicBlock &MBB : llvm::make_early_inc_range(MF))
1866 MadeChange |= HoistCommonCodeInSuccs(&MBB);
1867
1868 return MadeChange;
1869}
1870
1871/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1872/// its 'true' successor.
1874 MachineBasicBlock *TrueBB) {
1875 for (MachineBasicBlock *SuccBB : BB->successors())
1876 if (SuccBB != TrueBB)
1877 return SuccBB;
1878 return nullptr;
1879}
1880
1881template <class Container>
1883 Container &Set) {
1884 if (Reg.isPhysical()) {
1885 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1886 Set.insert(*AI);
1887 } else {
1888 Set.insert(Reg);
1889 }
1890}
1891
1892/// findHoistingInsertPosAndDeps - Find the location to move common instructions
1893/// in successors to. The location is usually just before the terminator,
1894/// however if the terminator is a conditional branch and its previous
1895/// instruction is the flag setting instruction, the previous instruction is
1896/// the preferred location. This function also gathers uses and defs of the
1897/// instructions from the insertion point to the end of the block. The data is
1898/// used by HoistCommonCodeInSuccs to ensure safety.
1899static
1901 const TargetInstrInfo *TII,
1902 const TargetRegisterInfo *TRI,
1904 SmallSet<Register, 4> &Defs) {
1905 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1906 if (!TII->isUnpredicatedTerminator(*Loc))
1907 return MBB->end();
1908
1909 for (const MachineOperand &MO : Loc->operands()) {
1910 if (!MO.isReg())
1911 continue;
1912 Register Reg = MO.getReg();
1913 if (!Reg)
1914 continue;
1915 if (MO.isUse()) {
1917 } else {
1918 if (!MO.isDead())
1919 // Don't try to hoist code in the rare case the terminator defines a
1920 // register that is later used.
1921 return MBB->end();
1922
1923 // If the terminator defines a register, make sure we don't hoist
1924 // the instruction whose def might be clobbered by the terminator.
1925 addRegAndItsAliases(Reg, TRI, Defs);
1926 }
1927 }
1928
1929 if (Uses.empty())
1930 return Loc;
1931 // If the terminator is the only instruction in the block and Uses is not
1932 // empty (or we would have returned above), we can still safely hoist
1933 // instructions just before the terminator as long as the Defs/Uses are not
1934 // violated (which is checked in HoistCommonCodeInSuccs).
1935 if (Loc == MBB->begin())
1936 return Loc;
1937
1938 // The terminator is probably a conditional branch, try not to separate the
1939 // branch from condition setting instruction.
1941
1942 bool IsDef = false;
1943 for (const MachineOperand &MO : PI->operands()) {
1944 // If PI has a regmask operand, it is probably a call. Separate away.
1945 if (MO.isRegMask())
1946 return Loc;
1947 if (!MO.isReg() || MO.isUse())
1948 continue;
1949 Register Reg = MO.getReg();
1950 if (!Reg)
1951 continue;
1952 if (Uses.count(Reg)) {
1953 IsDef = true;
1954 break;
1955 }
1956 }
1957 if (!IsDef)
1958 // The condition setting instruction is not just before the conditional
1959 // branch.
1960 return Loc;
1961
1962 // Be conservative, don't insert instruction above something that may have
1963 // side-effects. And since it's potentially bad to separate flag setting
1964 // instruction from the conditional branch, just abort the optimization
1965 // completely.
1966 // Also avoid moving code above predicated instruction since it's hard to
1967 // reason about register liveness with predicated instruction.
1968 bool DontMoveAcrossStore = true;
1969 if (!PI->isSafeToMove(DontMoveAcrossStore) || TII->isPredicated(*PI))
1970 return MBB->end();
1971
1972 // Find out what registers are live. Note this routine is ignoring other live
1973 // registers which are only used by instructions in successor blocks.
1974 for (const MachineOperand &MO : PI->operands()) {
1975 if (!MO.isReg())
1976 continue;
1977 Register Reg = MO.getReg();
1978 if (!Reg)
1979 continue;
1980 if (MO.isUse()) {
1982 } else {
1983 if (Uses.erase(Reg)) {
1984 if (Reg.isPhysical()) {
1985 for (MCPhysReg SubReg : TRI->subregs(Reg))
1986 Uses.erase(SubReg); // Use sub-registers to be conservative
1987 }
1988 }
1989 addRegAndItsAliases(Reg, TRI, Defs);
1990 }
1991 }
1992
1993 return PI;
1994}
1995
1996bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1997 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1999 if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
2000 return false;
2001
2002 if (!FBB) FBB = findFalseBlock(MBB, TBB);
2003 if (!FBB)
2004 // Malformed bcc? True and false blocks are the same?
2005 return false;
2006
2007 // Restrict the optimization to cases where MBB is the only predecessor,
2008 // it is an obvious win.
2009 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
2010 return false;
2011
2012 // Find a suitable position to hoist the common instructions to. Also figure
2013 // out which registers are used or defined by instructions from the insertion
2014 // point to the end of the block.
2015 SmallSet<Register, 4> Uses, Defs;
2017 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
2018 if (Loc == MBB->end())
2019 return false;
2020
2021 bool HasDups = false;
2022 SmallSet<Register, 4> ActiveDefsSet, AllDefsSet;
2024 MachineBasicBlock::iterator FIB = FBB->begin();
2026 MachineBasicBlock::iterator FIE = FBB->end();
2027 MachineFunction &MF = *TBB->getParent();
2028 while (TIB != TIE && FIB != FIE) {
2029 // Skip dbg_value instructions. These do not count.
2030 TIB = skipDebugInstructionsForward(TIB, TIE, false);
2031 FIB = skipDebugInstructionsForward(FIB, FIE, false);
2032 if (TIB == TIE || FIB == FIE)
2033 break;
2034
2035 if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
2036 break;
2037
2038 if (TII->isPredicated(*TIB))
2039 // Hard to reason about register liveness with predicated instruction.
2040 break;
2041
2042 if (!TII->isSafeToMove(*TIB, TBB, MF))
2043 // Don't hoist the instruction if it isn't safe to move.
2044 break;
2045
2046 bool IsSafe = true;
2047 for (MachineOperand &MO : TIB->operands()) {
2048 // Don't attempt to hoist instructions with register masks.
2049 if (MO.isRegMask()) {
2050 IsSafe = false;
2051 break;
2052 }
2053 if (!MO.isReg())
2054 continue;
2055 Register Reg = MO.getReg();
2056 if (!Reg)
2057 continue;
2058 if (MO.isDef()) {
2059 if (Uses.count(Reg)) {
2060 // Avoid clobbering a register that's used by the instruction at
2061 // the point of insertion.
2062 IsSafe = false;
2063 break;
2064 }
2065
2066 if (Defs.count(Reg) && !MO.isDead()) {
2067 // Don't hoist the instruction if the def would be clobber by the
2068 // instruction at the point insertion. FIXME: This is overly
2069 // conservative. It should be possible to hoist the instructions
2070 // in BB2 in the following example:
2071 // BB1:
2072 // r1, eflag = op1 r2, r3
2073 // brcc eflag
2074 //
2075 // BB2:
2076 // r1 = op2, ...
2077 // = op3, killed r1
2078 IsSafe = false;
2079 break;
2080 }
2081 } else if (!ActiveDefsSet.count(Reg)) {
2082 if (Defs.count(Reg)) {
2083 // Use is defined by the instruction at the point of insertion.
2084 IsSafe = false;
2085 break;
2086 }
2087
2088 if (MO.isKill() && Uses.count(Reg))
2089 // Kills a register that's read by the instruction at the point of
2090 // insertion. Remove the kill marker.
2091 MO.setIsKill(false);
2092 }
2093 }
2094 if (!IsSafe)
2095 break;
2096
2097 bool DontMoveAcrossStore = true;
2098 if (!TIB->isSafeToMove(DontMoveAcrossStore))
2099 break;
2100
2101 // Remove kills from ActiveDefsSet, these registers had short live ranges.
2102 for (const MachineOperand &MO : TIB->all_uses()) {
2103 if (!MO.isKill())
2104 continue;
2105 Register Reg = MO.getReg();
2106 if (!Reg)
2107 continue;
2108 if (!AllDefsSet.count(Reg)) {
2109 continue;
2110 }
2111 if (Reg.isPhysical()) {
2112 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
2113 ActiveDefsSet.erase(*AI);
2114 } else {
2115 ActiveDefsSet.erase(Reg);
2116 }
2117 }
2118
2119 // Track local defs so we can update liveins.
2120 for (const MachineOperand &MO : TIB->all_defs()) {
2121 if (MO.isDead())
2122 continue;
2123 Register Reg = MO.getReg();
2124 if (!Reg || Reg.isVirtual())
2125 continue;
2126 addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
2127 addRegAndItsAliases(Reg, TRI, AllDefsSet);
2128 }
2129
2130 HasDups = true;
2131 ++TIB;
2132 ++FIB;
2133 }
2134
2135 if (!HasDups)
2136 return false;
2137
2138 // Hoist the instructions from [T.begin, TIB) and then delete [F.begin, FIB).
2139 // If we're hoisting from a single block then just splice. Else step through
2140 // and merge the debug locations.
2141 if (TBB == FBB) {
2142 MBB->splice(Loc, TBB, TBB->begin(), TIB);
2143 } else {
2144 // Merge the debug locations, and hoist and kill the debug instructions from
2145 // both branches. FIXME: We could probably try harder to preserve some debug
2146 // instructions (but at least this isn't producing wrong locations).
2147 MachineInstrBuilder MIRBuilder(*MBB->getParent(), Loc);
2148 auto HoistAndKillDbgInstr = [MBB, Loc](MachineBasicBlock::iterator DI) {
2149 assert(DI->isDebugInstr() && "Expected a debug instruction");
2150 if (DI->isDebugRef()) {
2151 const TargetInstrInfo *TII =
2153 const MCInstrDesc &DBGV = TII->get(TargetOpcode::DBG_VALUE);
2154 DI = BuildMI(*MBB->getParent(), DI->getDebugLoc(), DBGV, false, 0,
2155 DI->getDebugVariable(), DI->getDebugExpression());
2156 MBB->insert(Loc, &*DI);
2157 return;
2158 }
2159 // Deleting a DBG_PHI results in an undef at the referenced DBG_INSTR_REF.
2160 if (DI->isDebugPHI()) {
2161 DI->eraseFromParent();
2162 return;
2163 }
2164 // Move DBG_LABELs without modifying them. Set DBG_VALUEs undef.
2165 if (!DI->isDebugLabel())
2166 DI->setDebugValueUndef();
2167 DI->moveBefore(&*Loc);
2168 };
2169
2170 // TIB and FIB point to the end of the regions to hoist/merge in TBB and
2171 // FBB.
2173 MachineBasicBlock::iterator FI = FBB->begin();
2176 // Hoist and kill debug instructions from FBB. After this loop FI points
2177 // to the next non-debug instruction to hoist (checked in assert after the
2178 // TBB debug instruction handling code).
2179 while (FI != FE && FI->isDebugInstr())
2180 HoistAndKillDbgInstr(FI++);
2181
2182 // Kill debug instructions before moving.
2183 if (TI->isDebugInstr()) {
2184 HoistAndKillDbgInstr(TI);
2185 continue;
2186 }
2187
2188 // FI and TI now point to identical non-debug instructions.
2189 assert(FI != FE && "Unexpected end of FBB range");
2190 // Pseudo probes are excluded from the range when identifying foldable
2191 // instructions, so we don't expect to see one now.
2192 assert(!TI->isPseudoProbe() && "Unexpected pseudo probe in range");
2193 // NOTE: The loop above checks CheckKillDead but we can't do that here as
2194 // it modifies some kill markers after the check.
2195 assert(TI->isIdenticalTo(*FI, MachineInstr::CheckDefs) &&
2196 "Expected non-debug lockstep");
2197
2198 // Drop undef flag on the hoisted instruction if it was not present in
2199 // both of the original ones.
2200 mergeUndefFlag(*TI, *FI);
2201
2202 // Merge debug locs on hoisted instructions.
2203 TI->setDebugLoc(
2204 DILocation::getMergedLocation(TI->getDebugLoc(), FI->getDebugLoc()));
2205 TI->moveBefore(&*Loc);
2206 ++FI;
2207 }
2208 }
2209
2210 FBB->erase(FBB->begin(), FIB);
2211
2212 if (UpdateLiveIns)
2213 fullyRecomputeLiveIns({TBB, FBB});
2214
2215 ++NumHoist;
2216 return true;
2217}
2218
2220 bool EnableBasicBlockReordering) {
2221 return new BranchFolderLegacy(EnableCommonHoist, EnableBasicBlockReordering);
2222}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file implements the BitVector class.
static unsigned EstimateRuntime(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
EstimateRuntime - Make a rough estimate for how long it will take to run the specified code.
static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2)
Given two machine basic blocks, return the number of instructions they actually have in common togeth...
static cl::opt< cl::boolOrDefault > FlagEnableHoistCommonCode("branch-folder-hoist-common-code", cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden, cl::desc("Override common-code hoisting in the BranchFolding pass"))
static void mergeUndefFlag(MachineInstr &Merged, const MachineInstr &Other)
Ensure undef flag is preserved only when it is present in both instructions.
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
findFalseBlock - BB has a fallthrough.
static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock &PredMBB)
static unsigned HashMachineInstr(const MachineInstr &MI)
HashMachineInstr - Compute a hash value for MI and its operands.
static bool countsAsInstruction(const MachineInstr &MI)
Whether MI should be counted as an instruction when calculating common tail.
static cl::opt< cl::boolOrDefault > FlagEnableTailMerge("enable-tail-merge", cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden)
static unsigned CountTerminators(MachineBasicBlock *MBB, MachineBasicBlock::iterator &I)
CountTerminators - Count the number of terminators in the given block and set I to the position of th...
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB)
A no successor, non-return block probably ends in unreachable and is cold.
static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII, MachineBasicBlock &MBB)
static MachineBasicBlock::iterator skipBackwardPastNonInstructions(MachineBasicBlock::iterator I, MachineBasicBlock *MBB)
Iterate backwards from the given iterator I, towards the beginning of the block.
static cl::opt< unsigned > TailMergeThreshold("tail-merge-threshold", cl::desc("Max number of predecessors to consider tail merging"), cl::init(150), cl::Hidden)
static void addRegAndItsAliases(Register Reg, const TargetRegisterInfo *TRI, Container &Set)
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static bool ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, unsigned MinCommonTailLength, unsigned &CommonTailLen, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB, DenseMap< const MachineBasicBlock *, int > &EHScopeMembership, bool AfterPlacement, MBFIWrapper &MBBFreqInfo, ProfileSummaryInfo *PSI)
ProfitableToMerge - Check if two machine basic blocks have a common tail and decide if it would be pr...
static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock &SuccMBB)
static bool IsBranchOnlyBlock(MachineBasicBlock *MBB)
static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, const TargetInstrInfo *TII, const DebugLoc &BranchDL)
static bool IsBetterFallthrough(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2)
IsBetterFallthrough - Return true if it would be clearly better to fall-through to MBB1 than to fall ...
static unsigned HashEndOfMBB(const MachineBasicBlock &MBB)
HashEndOfMBB - Hash the last instruction in the MBB.
static cl::opt< cl::boolOrDefault > FlagEnableBlockReordering("branch-folder-reorder-blocks", cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden, cl::desc("Override basic-block reordering in the BranchFolding pass"))
static void mergeOperations(MachineBasicBlock::iterator MBBIStartPos, MachineBasicBlock &MBBCommon)
static MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, SmallSet< Register, 4 > &Uses, SmallSet< Register, 4 > &Defs)
findHoistingInsertPosAndDeps - Find the location to move common instructions in successors to.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallSet 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
Target-Independent Code Generator Pass Configuration Options pass.
AnalysisUsage & addRequired()
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
bool OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineLoopInfo *mli=nullptr, bool AfterPlacement=false)
Perhaps branch folding, tail merging and other CFG optimizations on the given function.
BranchFolder(bool DefaultEnableTailMerge, bool CommonHoist, MBFIWrapper &FreqInfo, const MachineBranchProbabilityInfo &ProbInfo, ProfileSummaryInfo *PSI, unsigned MinTailLength=0)
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static LLVM_ABI DILocation * getMergedLocation(DILocation *LocA, DILocation *LocB)
Attempts to merge LocA and LocB into a single location; see DebugLoc::getMergedLocation for more deta...
A debug info location.
Definition DebugLoc.h:126
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:172
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool empty() const
Definition DenseMap.h:171
iterator end()
Definition DenseMap.h:141
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
MCRegAliasIterator enumerates all registers aliasing Reg.
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isEHPad() const
Returns true if the block is a landing pad.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI void moveBefore(MachineBasicBlock *NewAfter)
Move 'this' block before or after the specified block.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
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 void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI void clearLiveIns()
Clear live in list.
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 copySuccessor(const MachineBasicBlock *Orig, succ_iterator I)
Copy a successor (and any probability info) from original block to this block's.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
LLVM_ABI void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
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...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
bool isMachineBlockAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
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 void moveAfter(MachineBasicBlock *NewBefore)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
BasicBlockListType::iterator iterator
void eraseAdditionalCallInfo(const MachineInstr *MI)
Following functions update call site info.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void erase(iterator MBBI)
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
unsigned getNumOperands() const
Retuns the total number of operands.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
void RemoveJumpTable(unsigned Idx)
RemoveJumpTable - Mark the specific index as being dead.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsUndef(bool Val=true)
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
bool requiresStructuredCFG() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
constexpr double e
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
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:315
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI FunctionPass * createBranchFolder(bool EnableCommonHoist=true, bool EnableBasicBlockReordering=true)
createBranchFolder - Create the BranchFolder pass, optionally disabling the common-code hoisting and/...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
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:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1596
LLVM_ABI void computeLiveIns(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
Computes registers live-in to MBB assuming all of its successors live-in lists are up-to-date.
LLVM_ABI char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
LLVM_ABI void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
LLVM_ABI DenseMap< const MachineBasicBlock *, int > getEHScopeMembership(const MachineFunction &MF)
Definition Analysis.cpp:757
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82