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