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