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