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