1 //===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
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
7 //===----------------------------------------------------------------------===//
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
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
17 //===----------------------------------------------------------------------===//
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/MachineBlockFrequencyInfo.h"
28 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/MachineSizeOpts.h"
39 #include "llvm/CodeGen/MBFIWrapper.h"
40 #include "llvm/CodeGen/TargetInstrInfo.h"
41 #include "llvm/CodeGen/TargetOpcodes.h"
42 #include "llvm/CodeGen/TargetPassConfig.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/InitializePasses.h"
49 #include "llvm/MC/LaneBitmask.h"
50 #include "llvm/MC/MCRegisterInfo.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/BlockFrequency.h"
53 #include "llvm/Support/BranchProbability.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
66 #define DEBUG_TYPE "branch-folder"
68 STATISTIC(NumDeadBlocks
, "Number of dead blocks removed");
69 STATISTIC(NumBranchOpts
, "Number of branches optimized");
70 STATISTIC(NumTailMerge
, "Number of block tails merged");
71 STATISTIC(NumHoist
, "Number of times common instructions are hoisted");
72 STATISTIC(NumTailCalls
, "Number of tail calls optimized");
74 static cl::opt
<cl::boolOrDefault
> FlagEnableTailMerge("enable-tail-merge",
75 cl::init(cl::BOU_UNSET
), cl::Hidden
);
77 // Throttle for huge numbers of predecessors (compile speed problems)
78 static cl::opt
<unsigned>
79 TailMergeThreshold("tail-merge-threshold",
80 cl::desc("Max number of predecessors to consider tail merging"),
81 cl::init(150), cl::Hidden
);
83 // Heuristic for tail merging (and, inversely, tail duplication).
84 // TODO: This should be replaced with a target query.
85 static cl::opt
<unsigned>
86 TailMergeSize("tail-merge-size",
87 cl::desc("Min number of instructions to consider tail merging"),
88 cl::init(3), cl::Hidden
);
92 /// BranchFolderPass - Wrap branch folder in a machine function pass.
93 class BranchFolderPass
: public MachineFunctionPass
{
97 explicit BranchFolderPass(): MachineFunctionPass(ID
) {}
99 bool runOnMachineFunction(MachineFunction
&MF
) override
;
101 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
102 AU
.addRequired
<MachineBlockFrequencyInfo
>();
103 AU
.addRequired
<MachineBranchProbabilityInfo
>();
104 AU
.addRequired
<ProfileSummaryInfoWrapperPass
>();
105 AU
.addRequired
<TargetPassConfig
>();
106 MachineFunctionPass::getAnalysisUsage(AU
);
110 } // end anonymous namespace
112 char BranchFolderPass::ID
= 0;
114 char &llvm::BranchFolderPassID
= BranchFolderPass::ID
;
116 INITIALIZE_PASS(BranchFolderPass
, DEBUG_TYPE
,
117 "Control Flow Optimizer", false, false)
119 bool BranchFolderPass::runOnMachineFunction(MachineFunction
&MF
) {
120 if (skipFunction(MF
.getFunction()))
123 TargetPassConfig
*PassConfig
= &getAnalysis
<TargetPassConfig
>();
124 // TailMerge can create jump into if branches that make CFG irreducible for
125 // HW that requires structurized CFG.
126 bool EnableTailMerge
= !MF
.getTarget().requiresStructuredCFG() &&
127 PassConfig
->getEnableTailMerge();
128 MBFIWrapper
MBBFreqInfo(
129 getAnalysis
<MachineBlockFrequencyInfo
>());
130 BranchFolder
Folder(EnableTailMerge
, /*CommonHoist=*/true, MBBFreqInfo
,
131 getAnalysis
<MachineBranchProbabilityInfo
>(),
132 &getAnalysis
<ProfileSummaryInfoWrapperPass
>().getPSI());
133 return Folder
.OptimizeFunction(MF
, MF
.getSubtarget().getInstrInfo(),
134 MF
.getSubtarget().getRegisterInfo());
137 BranchFolder::BranchFolder(bool DefaultEnableTailMerge
, bool CommonHoist
,
138 MBFIWrapper
&FreqInfo
,
139 const MachineBranchProbabilityInfo
&ProbInfo
,
140 ProfileSummaryInfo
*PSI
, unsigned MinTailLength
)
141 : EnableHoistCommonCode(CommonHoist
), MinCommonTailLength(MinTailLength
),
142 MBBFreqInfo(FreqInfo
), MBPI(ProbInfo
), PSI(PSI
) {
143 if (MinCommonTailLength
== 0)
144 MinCommonTailLength
= TailMergeSize
;
145 switch (FlagEnableTailMerge
) {
147 EnableTailMerge
= DefaultEnableTailMerge
;
149 case cl::BOU_TRUE
: EnableTailMerge
= true; break;
150 case cl::BOU_FALSE
: EnableTailMerge
= false; break;
154 void BranchFolder::RemoveDeadBlock(MachineBasicBlock
*MBB
) {
155 assert(MBB
->pred_empty() && "MBB must be dead!");
156 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB
);
158 MachineFunction
*MF
= MBB
->getParent();
159 // drop all successors.
160 while (!MBB
->succ_empty())
161 MBB
->removeSuccessor(MBB
->succ_end()-1);
163 // Avoid matching if this pointer gets reused.
164 TriedMerging
.erase(MBB
);
166 // Update call site info.
167 for (const MachineInstr
&MI
: *MBB
)
168 if (MI
.shouldUpdateCallSiteInfo())
169 MF
->eraseCallSiteInfo(&MI
);
173 EHScopeMembership
.erase(MBB
);
175 MLI
->removeBlock(MBB
);
178 bool BranchFolder::OptimizeFunction(MachineFunction
&MF
,
179 const TargetInstrInfo
*tii
,
180 const TargetRegisterInfo
*tri
,
181 MachineLoopInfo
*mli
, bool AfterPlacement
) {
182 if (!tii
) return false;
184 TriedMerging
.clear();
186 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
187 AfterBlockPlacement
= AfterPlacement
;
193 UpdateLiveIns
= MRI
.tracksLiveness() && TRI
->trackLivenessAfterRegAlloc(MF
);
195 MRI
.invalidateLiveness();
197 bool MadeChange
= false;
199 // Recalculate EH scope membership.
200 EHScopeMembership
= getEHScopeMembership(MF
);
202 bool MadeChangeThisIteration
= true;
203 while (MadeChangeThisIteration
) {
204 MadeChangeThisIteration
= TailMergeBlocks(MF
);
205 // No need to clean up if tail merging does not change anything after the
207 if (!AfterBlockPlacement
|| MadeChangeThisIteration
)
208 MadeChangeThisIteration
|= OptimizeBranches(MF
);
209 if (EnableHoistCommonCode
)
210 MadeChangeThisIteration
|= HoistCommonCode(MF
);
211 MadeChange
|= MadeChangeThisIteration
;
214 // See if any jump tables have become dead as the code generator
216 MachineJumpTableInfo
*JTI
= MF
.getJumpTableInfo();
220 // Walk the function to find jump tables that are live.
221 BitVector
JTIsLive(JTI
->getJumpTables().size());
222 for (const MachineBasicBlock
&BB
: MF
) {
223 for (const MachineInstr
&I
: BB
)
224 for (const MachineOperand
&Op
: I
.operands()) {
225 if (!Op
.isJTI()) continue;
227 // Remember that this JT is live.
228 JTIsLive
.set(Op
.getIndex());
232 // Finally, remove dead jump tables. This happens when the
233 // indirect jump was unreachable (and thus deleted).
234 for (unsigned i
= 0, e
= JTIsLive
.size(); i
!= e
; ++i
)
235 if (!JTIsLive
.test(i
)) {
236 JTI
->RemoveJumpTable(i
);
243 //===----------------------------------------------------------------------===//
244 // Tail Merging of Blocks
245 //===----------------------------------------------------------------------===//
247 /// HashMachineInstr - Compute a hash value for MI and its operands.
248 static unsigned HashMachineInstr(const MachineInstr
&MI
) {
249 unsigned Hash
= MI
.getOpcode();
250 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
251 const MachineOperand
&Op
= MI
.getOperand(i
);
253 // Merge in bits from the operand if easy. We can't use MachineOperand's
254 // hash_code here because it's not deterministic and we sort by hash value
256 unsigned OperandHash
= 0;
257 switch (Op
.getType()) {
258 case MachineOperand::MO_Register
:
259 OperandHash
= Op
.getReg();
261 case MachineOperand::MO_Immediate
:
262 OperandHash
= Op
.getImm();
264 case MachineOperand::MO_MachineBasicBlock
:
265 OperandHash
= Op
.getMBB()->getNumber();
267 case MachineOperand::MO_FrameIndex
:
268 case MachineOperand::MO_ConstantPoolIndex
:
269 case MachineOperand::MO_JumpTableIndex
:
270 OperandHash
= Op
.getIndex();
272 case MachineOperand::MO_GlobalAddress
:
273 case MachineOperand::MO_ExternalSymbol
:
274 // Global address / external symbol are too hard, don't bother, but do
275 // pull in the offset.
276 OperandHash
= Op
.getOffset();
282 Hash
+= ((OperandHash
<< 3) | Op
.getType()) << (i
& 31);
287 /// HashEndOfMBB - Hash the last instruction in the MBB.
288 static unsigned HashEndOfMBB(const MachineBasicBlock
&MBB
) {
289 MachineBasicBlock::const_iterator I
= MBB
.getLastNonDebugInstr(false);
293 return HashMachineInstr(*I
);
296 /// Whether MI should be counted as an instruction when calculating common tail.
297 static bool countsAsInstruction(const MachineInstr
&MI
) {
298 return !(MI
.isDebugInstr() || MI
.isCFIInstruction());
301 /// Iterate backwards from the given iterator \p I, towards the beginning of the
302 /// block. If a MI satisfying 'countsAsInstruction' is found, return an iterator
303 /// pointing to that MI. If no such MI is found, return the end iterator.
304 static MachineBasicBlock::iterator
305 skipBackwardPastNonInstructions(MachineBasicBlock::iterator I
,
306 MachineBasicBlock
*MBB
) {
307 while (I
!= MBB
->begin()) {
309 if (countsAsInstruction(*I
))
315 /// Given two machine basic blocks, return the number of instructions they
316 /// actually have in common together at their end. If a common tail is found (at
317 /// least by one instruction), then iterators for the first shared instruction
318 /// in each block are returned as well.
320 /// Non-instructions according to countsAsInstruction are ignored.
321 static unsigned ComputeCommonTailLength(MachineBasicBlock
*MBB1
,
322 MachineBasicBlock
*MBB2
,
323 MachineBasicBlock::iterator
&I1
,
324 MachineBasicBlock::iterator
&I2
) {
325 MachineBasicBlock::iterator MBBI1
= MBB1
->end();
326 MachineBasicBlock::iterator MBBI2
= MBB2
->end();
328 unsigned TailLen
= 0;
330 MBBI1
= skipBackwardPastNonInstructions(MBBI1
, MBB1
);
331 MBBI2
= skipBackwardPastNonInstructions(MBBI2
, MBB2
);
332 if (MBBI1
== MBB1
->end() || MBBI2
== MBB2
->end())
334 if (!MBBI1
->isIdenticalTo(*MBBI2
) ||
335 // FIXME: This check is dubious. It's used to get around a problem where
336 // people incorrectly expect inline asm directives to remain in the same
337 // relative order. This is untenable because normal compiler
338 // optimizations (like this one) may reorder and/or merge these
340 MBBI1
->isInlineAsm()) {
343 if (MBBI1
->getFlag(MachineInstr::NoMerge
) ||
344 MBBI2
->getFlag(MachineInstr::NoMerge
))
354 void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst
,
355 MachineBasicBlock
&NewDest
) {
357 // OldInst should always point to an instruction.
358 MachineBasicBlock
&OldMBB
= *OldInst
->getParent();
360 LiveRegs
.addLiveOuts(OldMBB
);
361 // Move backward to the place where will insert the jump.
362 MachineBasicBlock::iterator I
= OldMBB
.end();
365 LiveRegs
.stepBackward(*I
);
366 } while (I
!= OldInst
);
368 // Merging the tails may have switched some undef operand to non-undef ones.
369 // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
371 for (MachineBasicBlock::RegisterMaskPair P
: NewDest
.liveins()) {
372 // We computed the liveins with computeLiveIn earlier and should only see
374 assert(P
.LaneMask
== LaneBitmask::getAll() &&
375 "Can only handle full register.");
376 MCPhysReg Reg
= P
.PhysReg
;
377 if (!LiveRegs
.available(*MRI
, Reg
))
380 BuildMI(OldMBB
, OldInst
, DL
, TII
->get(TargetOpcode::IMPLICIT_DEF
), Reg
);
384 TII
->ReplaceTailWithBranchTo(OldInst
, &NewDest
);
388 MachineBasicBlock
*BranchFolder::SplitMBBAt(MachineBasicBlock
&CurMBB
,
389 MachineBasicBlock::iterator BBI1
,
390 const BasicBlock
*BB
) {
391 if (!TII
->isLegalToSplitMBBAt(CurMBB
, BBI1
))
394 MachineFunction
&MF
= *CurMBB
.getParent();
396 // Create the fall-through block.
397 MachineFunction::iterator MBBI
= CurMBB
.getIterator();
398 MachineBasicBlock
*NewMBB
= MF
.CreateMachineBasicBlock(BB
);
399 CurMBB
.getParent()->insert(++MBBI
, NewMBB
);
401 // Move all the successors of this block to the specified block.
402 NewMBB
->transferSuccessors(&CurMBB
);
404 // Add an edge from CurMBB to NewMBB for the fall-through.
405 CurMBB
.addSuccessor(NewMBB
);
407 // Splice the code over.
408 NewMBB
->splice(NewMBB
->end(), &CurMBB
, BBI1
, CurMBB
.end());
410 // NewMBB belongs to the same loop as CurMBB.
412 if (MachineLoop
*ML
= MLI
->getLoopFor(&CurMBB
))
413 ML
->addBasicBlockToLoop(NewMBB
, MLI
->getBase());
415 // NewMBB inherits CurMBB's block frequency.
416 MBBFreqInfo
.setBlockFreq(NewMBB
, MBBFreqInfo
.getBlockFreq(&CurMBB
));
419 computeAndAddLiveIns(LiveRegs
, *NewMBB
);
421 // Add the new block to the EH scope.
422 const auto &EHScopeI
= EHScopeMembership
.find(&CurMBB
);
423 if (EHScopeI
!= EHScopeMembership
.end()) {
424 auto n
= EHScopeI
->second
;
425 EHScopeMembership
[NewMBB
] = n
;
431 /// EstimateRuntime - Make a rough estimate for how long it will take to run
432 /// the specified code.
433 static unsigned EstimateRuntime(MachineBasicBlock::iterator I
,
434 MachineBasicBlock::iterator E
) {
436 for (; I
!= E
; ++I
) {
437 if (!countsAsInstruction(*I
))
441 else if (I
->mayLoadOrStore())
449 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
450 // branches temporarily for tail merging). In the case where CurMBB ends
451 // with a conditional branch to the next block, optimize by reversing the
452 // test and conditionally branching to SuccMBB instead.
453 static void FixTail(MachineBasicBlock
*CurMBB
, MachineBasicBlock
*SuccBB
,
454 const TargetInstrInfo
*TII
) {
455 MachineFunction
*MF
= CurMBB
->getParent();
456 MachineFunction::iterator I
= std::next(MachineFunction::iterator(CurMBB
));
457 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
458 SmallVector
<MachineOperand
, 4> Cond
;
459 DebugLoc dl
= CurMBB
->findBranchDebugLoc();
460 if (I
!= MF
->end() && !TII
->analyzeBranch(*CurMBB
, TBB
, FBB
, Cond
, true)) {
461 MachineBasicBlock
*NextBB
= &*I
;
462 if (TBB
== NextBB
&& !Cond
.empty() && !FBB
) {
463 if (!TII
->reverseBranchCondition(Cond
)) {
464 TII
->removeBranch(*CurMBB
);
465 TII
->insertBranch(*CurMBB
, SuccBB
, nullptr, Cond
, dl
);
470 TII
->insertBranch(*CurMBB
, SuccBB
, nullptr,
471 SmallVector
<MachineOperand
, 0>(), dl
);
475 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt
&o
) const {
476 if (getHash() < o
.getHash())
478 if (getHash() > o
.getHash())
480 if (getBlock()->getNumber() < o
.getBlock()->getNumber())
482 if (getBlock()->getNumber() > o
.getBlock()->getNumber())
484 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
485 // an object with itself.
486 #ifndef _GLIBCXX_DEBUG
487 llvm_unreachable("Predecessor appears twice");
493 /// CountTerminators - Count the number of terminators in the given
494 /// block and set I to the position of the first non-terminator, if there
495 /// is one, or MBB->end() otherwise.
496 static unsigned CountTerminators(MachineBasicBlock
*MBB
,
497 MachineBasicBlock::iterator
&I
) {
499 unsigned NumTerms
= 0;
501 if (I
== MBB
->begin()) {
506 if (!I
->isTerminator()) break;
512 /// A no successor, non-return block probably ends in unreachable and is cold.
513 /// Also consider a block that ends in an indirect branch to be a return block,
514 /// since many targets use plain indirect branches to return.
515 static bool blockEndsInUnreachable(const MachineBasicBlock
*MBB
) {
516 if (!MBB
->succ_empty())
520 return !(MBB
->back().isReturn() || MBB
->back().isIndirectBranch());
523 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
524 /// and decide if it would be profitable to merge those tails. Return the
525 /// length of the common tail and iterators to the first common instruction
527 /// MBB1, MBB2 The blocks to check
528 /// MinCommonTailLength Minimum size of tail block to be merged.
529 /// CommonTailLen Out parameter to record the size of the shared tail between
531 /// I1, I2 Iterator references that will be changed to point to the first
532 /// instruction in the common tail shared by MBB1,MBB2
533 /// SuccBB A common successor of MBB1, MBB2 which are in a canonical form
534 /// relative to SuccBB
535 /// PredBB The layout predecessor of SuccBB, if any.
536 /// EHScopeMembership map from block to EH scope #.
537 /// AfterPlacement True if we are merging blocks after layout. Stricter
538 /// thresholds apply to prevent undoing tail-duplication.
540 ProfitableToMerge(MachineBasicBlock
*MBB1
, MachineBasicBlock
*MBB2
,
541 unsigned MinCommonTailLength
, unsigned &CommonTailLen
,
542 MachineBasicBlock::iterator
&I1
,
543 MachineBasicBlock::iterator
&I2
, MachineBasicBlock
*SuccBB
,
544 MachineBasicBlock
*PredBB
,
545 DenseMap
<const MachineBasicBlock
*, int> &EHScopeMembership
,
547 MBFIWrapper
&MBBFreqInfo
,
548 ProfileSummaryInfo
*PSI
) {
549 // It is never profitable to tail-merge blocks from two different EH scopes.
550 if (!EHScopeMembership
.empty()) {
551 auto EHScope1
= EHScopeMembership
.find(MBB1
);
552 assert(EHScope1
!= EHScopeMembership
.end());
553 auto EHScope2
= EHScopeMembership
.find(MBB2
);
554 assert(EHScope2
!= EHScopeMembership
.end());
555 if (EHScope1
->second
!= EHScope2
->second
)
559 CommonTailLen
= ComputeCommonTailLength(MBB1
, MBB2
, I1
, I2
);
560 if (CommonTailLen
== 0)
562 LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1
)
563 << " and " << printMBBReference(*MBB2
) << " is "
564 << CommonTailLen
<< '\n');
566 // Move the iterators to the beginning of the MBB if we only got debug
567 // instructions before the tail. This is to avoid splitting a block when we
568 // only got debug instructions before the tail (to be invariant on -g).
569 if (skipDebugInstructionsForward(MBB1
->begin(), MBB1
->end(), false) == I1
)
571 if (skipDebugInstructionsForward(MBB2
->begin(), MBB2
->end(), false) == I2
)
574 bool FullBlockTail1
= I1
== MBB1
->begin();
575 bool FullBlockTail2
= I2
== MBB2
->begin();
577 // It's almost always profitable to merge any number of non-terminator
578 // instructions with the block that falls through into the common successor.
579 // This is true only for a single successor. For multiple successors, we are
580 // trading a conditional branch for an unconditional one.
581 // TODO: Re-visit successor size for non-layout tail merging.
582 if ((MBB1
== PredBB
|| MBB2
== PredBB
) &&
583 (!AfterPlacement
|| MBB1
->succ_size() == 1)) {
584 MachineBasicBlock::iterator I
;
585 unsigned NumTerms
= CountTerminators(MBB1
== PredBB
? MBB2
: MBB1
, I
);
586 if (CommonTailLen
> NumTerms
)
590 // If these are identical non-return blocks with no successors, merge them.
591 // Such blocks are typically cold calls to noreturn functions like abort, and
592 // are unlikely to become a fallthrough target after machine block placement.
593 // Tail merging these blocks is unlikely to create additional unconditional
594 // branches, and will reduce the size of this cold code.
595 if (FullBlockTail1
&& FullBlockTail2
&&
596 blockEndsInUnreachable(MBB1
) && blockEndsInUnreachable(MBB2
))
599 // If one of the blocks can be completely merged and happens to be in
600 // a position where the other could fall through into it, merge any number
601 // of instructions, because it can be done without a branch.
602 // TODO: If the blocks are not adjacent, move one of them so that they are?
603 if (MBB1
->isLayoutSuccessor(MBB2
) && FullBlockTail2
)
605 if (MBB2
->isLayoutSuccessor(MBB1
) && FullBlockTail1
)
608 // If both blocks are identical and end in a branch, merge them unless they
609 // both have a fallthrough predecessor and successor.
610 // We can only do this after block placement because it depends on whether
611 // there are fallthroughs, and we don't know until after layout.
612 if (AfterPlacement
&& FullBlockTail1
&& FullBlockTail2
) {
613 auto BothFallThrough
= [](MachineBasicBlock
*MBB
) {
614 if (!MBB
->succ_empty() && !MBB
->canFallThrough())
616 MachineFunction::iterator
I(MBB
);
617 MachineFunction
*MF
= MBB
->getParent();
618 return (MBB
!= &*MF
->begin()) && std::prev(I
)->canFallThrough();
620 if (!BothFallThrough(MBB1
) || !BothFallThrough(MBB2
))
624 // If both blocks have an unconditional branch temporarily stripped out,
625 // count that as an additional common instruction for the following
626 // heuristics. This heuristic is only accurate for single-succ blocks, so to
627 // make sure that during layout merging and duplicating don't crash, we check
628 // for that when merging during layout.
629 unsigned EffectiveTailLen
= CommonTailLen
;
630 if (SuccBB
&& MBB1
!= PredBB
&& MBB2
!= PredBB
&&
631 (MBB1
->succ_size() == 1 || !AfterPlacement
) &&
632 !MBB1
->back().isBarrier() &&
633 !MBB2
->back().isBarrier())
636 // Check if the common tail is long enough to be worthwhile.
637 if (EffectiveTailLen
>= MinCommonTailLength
)
640 // If we are optimizing for code size, 2 instructions in common is enough if
641 // we don't have to split a block. At worst we will be introducing 1 new
642 // branch instruction, which is likely to be smaller than the 2
643 // instructions that would be deleted in the merge.
644 MachineFunction
*MF
= MBB1
->getParent();
646 MF
->getFunction().hasOptSize() ||
647 (llvm::shouldOptimizeForSize(MBB1
, PSI
, &MBBFreqInfo
) &&
648 llvm::shouldOptimizeForSize(MBB2
, PSI
, &MBBFreqInfo
));
649 return EffectiveTailLen
>= 2 && OptForSize
&&
650 (FullBlockTail1
|| FullBlockTail2
);
653 unsigned BranchFolder::ComputeSameTails(unsigned CurHash
,
654 unsigned MinCommonTailLength
,
655 MachineBasicBlock
*SuccBB
,
656 MachineBasicBlock
*PredBB
) {
657 unsigned maxCommonTailLength
= 0U;
659 MachineBasicBlock::iterator TrialBBI1
, TrialBBI2
;
660 MPIterator HighestMPIter
= std::prev(MergePotentials
.end());
661 for (MPIterator CurMPIter
= std::prev(MergePotentials
.end()),
662 B
= MergePotentials
.begin();
663 CurMPIter
!= B
&& CurMPIter
->getHash() == CurHash
; --CurMPIter
) {
664 for (MPIterator I
= std::prev(CurMPIter
); I
->getHash() == CurHash
; --I
) {
665 unsigned CommonTailLen
;
666 if (ProfitableToMerge(CurMPIter
->getBlock(), I
->getBlock(),
668 CommonTailLen
, TrialBBI1
, TrialBBI2
,
671 AfterBlockPlacement
, MBBFreqInfo
, PSI
)) {
672 if (CommonTailLen
> maxCommonTailLength
) {
674 maxCommonTailLength
= CommonTailLen
;
675 HighestMPIter
= CurMPIter
;
676 SameTails
.push_back(SameTailElt(CurMPIter
, TrialBBI1
));
678 if (HighestMPIter
== CurMPIter
&&
679 CommonTailLen
== maxCommonTailLength
)
680 SameTails
.push_back(SameTailElt(I
, TrialBBI2
));
686 return maxCommonTailLength
;
689 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash
,
690 MachineBasicBlock
*SuccBB
,
691 MachineBasicBlock
*PredBB
) {
692 MPIterator CurMPIter
, B
;
693 for (CurMPIter
= std::prev(MergePotentials
.end()),
694 B
= MergePotentials
.begin();
695 CurMPIter
->getHash() == CurHash
; --CurMPIter
) {
696 // Put the unconditional branch back, if we need one.
697 MachineBasicBlock
*CurMBB
= CurMPIter
->getBlock();
698 if (SuccBB
&& CurMBB
!= PredBB
)
699 FixTail(CurMBB
, SuccBB
, TII
);
703 if (CurMPIter
->getHash() != CurHash
)
705 MergePotentials
.erase(CurMPIter
, MergePotentials
.end());
708 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock
*&PredBB
,
709 MachineBasicBlock
*SuccBB
,
710 unsigned maxCommonTailLength
,
711 unsigned &commonTailIndex
) {
713 unsigned TimeEstimate
= ~0U;
714 for (unsigned i
= 0, e
= SameTails
.size(); i
!= e
; ++i
) {
715 // Use PredBB if possible; that doesn't require a new branch.
716 if (SameTails
[i
].getBlock() == PredBB
) {
720 // Otherwise, make a (fairly bogus) choice based on estimate of
721 // how long it will take the various blocks to execute.
722 unsigned t
= EstimateRuntime(SameTails
[i
].getBlock()->begin(),
723 SameTails
[i
].getTailStartPos());
724 if (t
<= TimeEstimate
) {
730 MachineBasicBlock::iterator BBI
=
731 SameTails
[commonTailIndex
].getTailStartPos();
732 MachineBasicBlock
*MBB
= SameTails
[commonTailIndex
].getBlock();
734 LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB
) << ", size "
735 << maxCommonTailLength
);
737 // If the split block unconditionally falls-thru to SuccBB, it will be
738 // merged. In control flow terms it should then take SuccBB's name. e.g. If
739 // SuccBB is an inner loop, the common tail is still part of the inner loop.
740 const BasicBlock
*BB
= (SuccBB
&& MBB
->succ_size() == 1) ?
741 SuccBB
->getBasicBlock() : MBB
->getBasicBlock();
742 MachineBasicBlock
*newMBB
= SplitMBBAt(*MBB
, BBI
, BB
);
744 LLVM_DEBUG(dbgs() << "... failed!");
748 SameTails
[commonTailIndex
].setBlock(newMBB
);
749 SameTails
[commonTailIndex
].setTailStartPos(newMBB
->begin());
751 // If we split PredBB, newMBB is the new predecessor.
759 mergeOperations(MachineBasicBlock::iterator MBBIStartPos
,
760 MachineBasicBlock
&MBBCommon
) {
761 MachineBasicBlock
*MBB
= MBBIStartPos
->getParent();
762 // Note CommonTailLen does not necessarily matches the size of
763 // the common BB nor all its instructions because of debug
764 // instructions differences.
765 unsigned CommonTailLen
= 0;
766 for (auto E
= MBB
->end(); MBBIStartPos
!= E
; ++MBBIStartPos
)
769 MachineBasicBlock::reverse_iterator MBBI
= MBB
->rbegin();
770 MachineBasicBlock::reverse_iterator MBBIE
= MBB
->rend();
771 MachineBasicBlock::reverse_iterator MBBICommon
= MBBCommon
.rbegin();
772 MachineBasicBlock::reverse_iterator MBBIECommon
= MBBCommon
.rend();
774 while (CommonTailLen
--) {
775 assert(MBBI
!= MBBIE
&& "Reached BB end within common tail length!");
778 if (!countsAsInstruction(*MBBI
)) {
783 while ((MBBICommon
!= MBBIECommon
) && !countsAsInstruction(*MBBICommon
))
786 assert(MBBICommon
!= MBBIECommon
&&
787 "Reached BB end within common tail length!");
788 assert(MBBICommon
->isIdenticalTo(*MBBI
) && "Expected matching MIIs!");
790 // Merge MMOs from memory operations in the common block.
791 if (MBBICommon
->mayLoadOrStore())
792 MBBICommon
->cloneMergedMemRefs(*MBB
->getParent(), {&*MBBICommon
, &*MBBI
});
793 // Drop undef flags if they aren't present in all merged instructions.
794 for (unsigned I
= 0, E
= MBBICommon
->getNumOperands(); I
!= E
; ++I
) {
795 MachineOperand
&MO
= MBBICommon
->getOperand(I
);
796 if (MO
.isReg() && MO
.isUndef()) {
797 const MachineOperand
&OtherMO
= MBBI
->getOperand(I
);
798 if (!OtherMO
.isUndef())
799 MO
.setIsUndef(false);
808 void BranchFolder::mergeCommonTails(unsigned commonTailIndex
) {
809 MachineBasicBlock
*MBB
= SameTails
[commonTailIndex
].getBlock();
811 std::vector
<MachineBasicBlock::iterator
> NextCommonInsts(SameTails
.size());
812 for (unsigned int i
= 0 ; i
!= SameTails
.size() ; ++i
) {
813 if (i
!= commonTailIndex
) {
814 NextCommonInsts
[i
] = SameTails
[i
].getTailStartPos();
815 mergeOperations(SameTails
[i
].getTailStartPos(), *MBB
);
817 assert(SameTails
[i
].getTailStartPos() == MBB
->begin() &&
818 "MBB is not a common tail only block");
822 for (auto &MI
: *MBB
) {
823 if (!countsAsInstruction(MI
))
825 DebugLoc DL
= MI
.getDebugLoc();
826 for (unsigned int i
= 0 ; i
< NextCommonInsts
.size() ; i
++) {
827 if (i
== commonTailIndex
)
830 auto &Pos
= NextCommonInsts
[i
];
831 assert(Pos
!= SameTails
[i
].getBlock()->end() &&
832 "Reached BB end within common tail");
833 while (!countsAsInstruction(*Pos
)) {
835 assert(Pos
!= SameTails
[i
].getBlock()->end() &&
836 "Reached BB end within common tail");
838 assert(MI
.isIdenticalTo(*Pos
) && "Expected matching MIIs!");
839 DL
= DILocation::getMergedLocation(DL
, Pos
->getDebugLoc());
840 NextCommonInsts
[i
] = ++Pos
;
846 LivePhysRegs
NewLiveIns(*TRI
);
847 computeLiveIns(NewLiveIns
, *MBB
);
850 // The flag merging may lead to some register uses no longer using the
851 // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
852 for (MachineBasicBlock
*Pred
: MBB
->predecessors()) {
854 LiveRegs
.addLiveOuts(*Pred
);
855 MachineBasicBlock::iterator InsertBefore
= Pred
->getFirstTerminator();
856 for (Register Reg
: NewLiveIns
) {
857 if (!LiveRegs
.available(*MRI
, Reg
))
860 BuildMI(*Pred
, InsertBefore
, DL
, TII
->get(TargetOpcode::IMPLICIT_DEF
),
866 addLiveIns(*MBB
, NewLiveIns
);
870 // See if any of the blocks in MergePotentials (which all have SuccBB as a
871 // successor, or all have no successor if it is null) can be tail-merged.
872 // If there is a successor, any blocks in MergePotentials that are not
873 // tail-merged and are not immediately before Succ must have an unconditional
874 // branch to Succ added (but the predecessor/successor lists need no
875 // adjustment). The lone predecessor of Succ that falls through into Succ,
876 // if any, is given in PredBB.
877 // MinCommonTailLength - Except for the special cases below, tail-merge if
878 // there are at least this many instructions in common.
879 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock
*SuccBB
,
880 MachineBasicBlock
*PredBB
,
881 unsigned MinCommonTailLength
) {
882 bool MadeChange
= false;
885 dbgs() << "\nTryTailMergeBlocks: ";
886 for (unsigned i
= 0, e
= MergePotentials
.size(); i
!= e
; ++i
) dbgs()
887 << printMBBReference(*MergePotentials
[i
].getBlock())
888 << (i
== e
- 1 ? "" : ", ");
889 dbgs() << "\n"; if (SuccBB
) {
890 dbgs() << " with successor " << printMBBReference(*SuccBB
) << '\n';
892 dbgs() << " which has fall-through from "
893 << printMBBReference(*PredBB
) << "\n";
894 } dbgs() << "Looking for common tails of at least "
895 << MinCommonTailLength
<< " instruction"
896 << (MinCommonTailLength
== 1 ? "" : "s") << '\n';);
898 // Sort by hash value so that blocks with identical end sequences sort
900 array_pod_sort(MergePotentials
.begin(), MergePotentials
.end());
902 // Walk through equivalence sets looking for actual exact matches.
903 while (MergePotentials
.size() > 1) {
904 unsigned CurHash
= MergePotentials
.back().getHash();
906 // Build SameTails, identifying the set of blocks with this hash code
907 // and with the maximum number of instructions in common.
908 unsigned maxCommonTailLength
= ComputeSameTails(CurHash
,
912 // If we didn't find any pair that has at least MinCommonTailLength
913 // instructions in common, remove all blocks with this hash code and retry.
914 if (SameTails
.empty()) {
915 RemoveBlocksWithHash(CurHash
, SuccBB
, PredBB
);
919 // If one of the blocks is the entire common tail (and is not the entry
920 // block/an EH pad, which we can't jump to), we can treat all blocks with
921 // this same tail at once. Use PredBB if that is one of the possibilities,
922 // as that will not introduce any extra branches.
923 MachineBasicBlock
*EntryBB
=
924 &MergePotentials
.front().getBlock()->getParent()->front();
925 unsigned commonTailIndex
= SameTails
.size();
926 // If there are two blocks, check to see if one can be made to fall through
928 if (SameTails
.size() == 2 &&
929 SameTails
[0].getBlock()->isLayoutSuccessor(SameTails
[1].getBlock()) &&
930 SameTails
[1].tailIsWholeBlock() && !SameTails
[1].getBlock()->isEHPad())
932 else if (SameTails
.size() == 2 &&
933 SameTails
[1].getBlock()->isLayoutSuccessor(
934 SameTails
[0].getBlock()) &&
935 SameTails
[0].tailIsWholeBlock() &&
936 !SameTails
[0].getBlock()->isEHPad())
939 // Otherwise just pick one, favoring the fall-through predecessor if
941 for (unsigned i
= 0, e
= SameTails
.size(); i
!= e
; ++i
) {
942 MachineBasicBlock
*MBB
= SameTails
[i
].getBlock();
943 if ((MBB
== EntryBB
|| MBB
->isEHPad()) &&
944 SameTails
[i
].tailIsWholeBlock())
950 if (SameTails
[i
].tailIsWholeBlock())
955 if (commonTailIndex
== SameTails
.size() ||
956 (SameTails
[commonTailIndex
].getBlock() == PredBB
&&
957 !SameTails
[commonTailIndex
].tailIsWholeBlock())) {
958 // None of the blocks consist entirely of the common tail.
959 // Split a block so that one does.
960 if (!CreateCommonTailOnlyBlock(PredBB
, SuccBB
,
961 maxCommonTailLength
, commonTailIndex
)) {
962 RemoveBlocksWithHash(CurHash
, SuccBB
, PredBB
);
967 MachineBasicBlock
*MBB
= SameTails
[commonTailIndex
].getBlock();
969 // Recompute common tail MBB's edge weights and block frequency.
970 setCommonTailEdgeWeights(*MBB
);
972 // Merge debug locations, MMOs and undef flags across identical instructions
974 mergeCommonTails(commonTailIndex
);
976 // MBB is common tail. Adjust all other BB's to jump to this one.
977 // Traversal must be forwards so erases work.
978 LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB
)
980 for (unsigned int i
=0, e
= SameTails
.size(); i
!= e
; ++i
) {
981 if (commonTailIndex
== i
)
983 LLVM_DEBUG(dbgs() << printMBBReference(*SameTails
[i
].getBlock())
984 << (i
== e
- 1 ? "" : ", "));
985 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
986 replaceTailWithBranchTo(SameTails
[i
].getTailStartPos(), *MBB
);
987 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
988 MergePotentials
.erase(SameTails
[i
].getMPIter());
990 LLVM_DEBUG(dbgs() << "\n");
991 // We leave commonTailIndex in the worklist in case there are other blocks
992 // that match it with a smaller number of instructions.
998 bool BranchFolder::TailMergeBlocks(MachineFunction
&MF
) {
999 bool MadeChange
= false;
1000 if (!EnableTailMerge
)
1003 // First find blocks with no successors.
1004 // Block placement may create new tail merging opportunities for these blocks.
1005 MergePotentials
.clear();
1006 for (MachineBasicBlock
&MBB
: MF
) {
1007 if (MergePotentials
.size() == TailMergeThreshold
)
1009 if (!TriedMerging
.count(&MBB
) && MBB
.succ_empty())
1010 MergePotentials
.push_back(MergePotentialsElt(HashEndOfMBB(MBB
), &MBB
));
1013 // If this is a large problem, avoid visiting the same basic blocks
1015 if (MergePotentials
.size() == TailMergeThreshold
)
1016 for (const MergePotentialsElt
&Elt
: MergePotentials
)
1017 TriedMerging
.insert(Elt
.getBlock());
1019 // See if we can do any tail merging on those.
1020 if (MergePotentials
.size() >= 2)
1021 MadeChange
|= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength
);
1023 // Look at blocks (IBB) with multiple predecessors (PBB).
1024 // We change each predecessor to a canonical form, by
1025 // (1) temporarily removing any unconditional branch from the predecessor
1027 // (2) alter conditional branches so they branch to the other block
1028 // not IBB; this may require adding back an unconditional branch to IBB
1029 // later, where there wasn't one coming in. E.g.
1031 // fallthrough to QBB
1034 // with a conceptual B to IBB after that, which never actually exists.
1035 // With those changes, we see whether the predecessors' tails match,
1036 // and merge them if so. We change things out of canonical form and
1037 // back to the way they were later in the process. (OptimizeBranches
1038 // would undo some of this, but we can't use it, because we'd get into
1039 // a compile-time infinite loop repeatedly doing and undoing the same
1040 // transformations.)
1042 for (MachineFunction::iterator I
= std::next(MF
.begin()), E
= MF
.end();
1044 if (I
->pred_size() < 2) continue;
1045 SmallPtrSet
<MachineBasicBlock
*, 8> UniquePreds
;
1046 MachineBasicBlock
*IBB
= &*I
;
1047 MachineBasicBlock
*PredBB
= &*std::prev(I
);
1048 MergePotentials
.clear();
1051 // Bail if merging after placement and IBB is the loop header because
1052 // -- If merging predecessors that belong to the same loop as IBB, the
1053 // common tail of merged predecessors may become the loop top if block
1054 // placement is called again and the predecessors may branch to this common
1055 // tail and require more branches. This can be relaxed if
1056 // MachineBlockPlacement::findBestLoopTop is more flexible.
1057 // --If merging predecessors that do not belong to the same loop as IBB, the
1058 // loop info of IBB's loop and the other loops may be affected. Calling the
1059 // block placement again may make big change to the layout and eliminate the
1060 // reason to do tail merging here.
1061 if (AfterBlockPlacement
&& MLI
) {
1062 ML
= MLI
->getLoopFor(IBB
);
1063 if (ML
&& IBB
== ML
->getHeader())
1067 for (MachineBasicBlock
*PBB
: I
->predecessors()) {
1068 if (MergePotentials
.size() == TailMergeThreshold
)
1071 if (TriedMerging
.count(PBB
))
1074 // Skip blocks that loop to themselves, can't tail merge these.
1078 // Visit each predecessor only once.
1079 if (!UniquePreds
.insert(PBB
).second
)
1082 // Skip blocks which may jump to a landing pad or jump from an asm blob.
1083 // Can't tail merge these.
1084 if (PBB
->hasEHPadSuccessor() || PBB
->mayHaveInlineAsmBr())
1087 // After block placement, only consider predecessors that belong to the
1088 // same loop as IBB. The reason is the same as above when skipping loop
1090 if (AfterBlockPlacement
&& MLI
)
1091 if (ML
!= MLI
->getLoopFor(PBB
))
1094 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
1095 SmallVector
<MachineOperand
, 4> Cond
;
1096 if (!TII
->analyzeBranch(*PBB
, TBB
, FBB
, Cond
, true)) {
1097 // Failing case: IBB is the target of a cbr, and we cannot reverse the
1099 SmallVector
<MachineOperand
, 4> NewCond(Cond
);
1100 if (!Cond
.empty() && TBB
== IBB
) {
1101 if (TII
->reverseBranchCondition(NewCond
))
1103 // This is the QBB case described above
1105 auto Next
= ++PBB
->getIterator();
1106 if (Next
!= MF
.end())
1111 // Remove the unconditional branch at the end, if any.
1112 if (TBB
&& (Cond
.empty() || FBB
)) {
1113 DebugLoc dl
= PBB
->findBranchDebugLoc();
1114 TII
->removeBranch(*PBB
);
1116 // reinsert conditional branch only, for now
1117 TII
->insertBranch(*PBB
, (TBB
== IBB
) ? FBB
: TBB
, nullptr,
1121 MergePotentials
.push_back(MergePotentialsElt(HashEndOfMBB(*PBB
), PBB
));
1125 // If this is a large problem, avoid visiting the same basic blocks multiple
1127 if (MergePotentials
.size() == TailMergeThreshold
)
1128 for (MergePotentialsElt
&Elt
: MergePotentials
)
1129 TriedMerging
.insert(Elt
.getBlock());
1131 if (MergePotentials
.size() >= 2)
1132 MadeChange
|= TryTailMergeBlocks(IBB
, PredBB
, MinCommonTailLength
);
1134 // Reinsert an unconditional branch if needed. The 1 below can occur as a
1135 // result of removing blocks in TryTailMergeBlocks.
1136 PredBB
= &*std::prev(I
); // this may have been changed in TryTailMergeBlocks
1137 if (MergePotentials
.size() == 1 &&
1138 MergePotentials
.begin()->getBlock() != PredBB
)
1139 FixTail(MergePotentials
.begin()->getBlock(), IBB
, TII
);
1145 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock
&TailMBB
) {
1146 SmallVector
<BlockFrequency
, 2> EdgeFreqLs(TailMBB
.succ_size());
1147 BlockFrequency AccumulatedMBBFreq
;
1149 // Aggregate edge frequency of successor edge j:
1150 // edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1151 // where bb is a basic block that is in SameTails.
1152 for (const auto &Src
: SameTails
) {
1153 const MachineBasicBlock
*SrcMBB
= Src
.getBlock();
1154 BlockFrequency BlockFreq
= MBBFreqInfo
.getBlockFreq(SrcMBB
);
1155 AccumulatedMBBFreq
+= BlockFreq
;
1157 // It is not necessary to recompute edge weights if TailBB has less than two
1159 if (TailMBB
.succ_size() <= 1)
1162 auto EdgeFreq
= EdgeFreqLs
.begin();
1164 for (auto SuccI
= TailMBB
.succ_begin(), SuccE
= TailMBB
.succ_end();
1165 SuccI
!= SuccE
; ++SuccI
, ++EdgeFreq
)
1166 *EdgeFreq
+= BlockFreq
* MBPI
.getEdgeProbability(SrcMBB
, *SuccI
);
1169 MBBFreqInfo
.setBlockFreq(&TailMBB
, AccumulatedMBBFreq
);
1171 if (TailMBB
.succ_size() <= 1)
1175 std::accumulate(EdgeFreqLs
.begin(), EdgeFreqLs
.end(), BlockFrequency(0))
1177 auto EdgeFreq
= EdgeFreqLs
.begin();
1179 if (SumEdgeFreq
> 0) {
1180 for (auto SuccI
= TailMBB
.succ_begin(), SuccE
= TailMBB
.succ_end();
1181 SuccI
!= SuccE
; ++SuccI
, ++EdgeFreq
) {
1182 auto Prob
= BranchProbability::getBranchProbability(
1183 EdgeFreq
->getFrequency(), SumEdgeFreq
);
1184 TailMBB
.setSuccProbability(SuccI
, Prob
);
1189 //===----------------------------------------------------------------------===//
1190 // Branch Optimization
1191 //===----------------------------------------------------------------------===//
1193 bool BranchFolder::OptimizeBranches(MachineFunction
&MF
) {
1194 bool MadeChange
= false;
1196 // Make sure blocks are numbered in order
1197 MF
.RenumberBlocks();
1198 // Renumbering blocks alters EH scope membership, recalculate it.
1199 EHScopeMembership
= getEHScopeMembership(MF
);
1201 for (MachineBasicBlock
&MBB
:
1202 llvm::make_early_inc_range(llvm::drop_begin(MF
))) {
1203 MadeChange
|= OptimizeBlock(&MBB
);
1205 // If it is dead, remove it.
1206 if (MBB
.pred_empty()) {
1207 RemoveDeadBlock(&MBB
);
1216 // Blocks should be considered empty if they contain only debug info;
1217 // else the debug info would affect codegen.
1218 static bool IsEmptyBlock(MachineBasicBlock
*MBB
) {
1219 return MBB
->getFirstNonDebugInstr(true) == MBB
->end();
1222 // Blocks with only debug info and branches should be considered the same
1223 // as blocks with only branches.
1224 static bool IsBranchOnlyBlock(MachineBasicBlock
*MBB
) {
1225 MachineBasicBlock::iterator I
= MBB
->getFirstNonDebugInstr();
1226 assert(I
!= MBB
->end() && "empty block!");
1227 return I
->isBranch();
1230 /// IsBetterFallthrough - Return true if it would be clearly better to
1231 /// fall-through to MBB1 than to fall through into MBB2. This has to return
1232 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1233 /// result in infinite loops.
1234 static bool IsBetterFallthrough(MachineBasicBlock
*MBB1
,
1235 MachineBasicBlock
*MBB2
) {
1236 assert(MBB1
&& MBB2
&& "Unknown MachineBasicBlock");
1238 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1239 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
1240 // optimize branches that branch to either a return block or an assert block
1241 // into a fallthrough to the return.
1242 MachineBasicBlock::iterator MBB1I
= MBB1
->getLastNonDebugInstr();
1243 MachineBasicBlock::iterator MBB2I
= MBB2
->getLastNonDebugInstr();
1244 if (MBB1I
== MBB1
->end() || MBB2I
== MBB2
->end())
1247 // If there is a clear successor ordering we make sure that one block
1248 // will fall through to the next
1249 if (MBB1
->isSuccessor(MBB2
)) return true;
1250 if (MBB2
->isSuccessor(MBB1
)) return false;
1252 return MBB2I
->isCall() && !MBB1I
->isCall();
1255 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1256 /// instructions on the block.
1257 static DebugLoc
getBranchDebugLoc(MachineBasicBlock
&MBB
) {
1258 MachineBasicBlock::iterator I
= MBB
.getLastNonDebugInstr();
1259 if (I
!= MBB
.end() && I
->isBranch())
1260 return I
->getDebugLoc();
1264 static void copyDebugInfoToPredecessor(const TargetInstrInfo
*TII
,
1265 MachineBasicBlock
&MBB
,
1266 MachineBasicBlock
&PredMBB
) {
1267 auto InsertBefore
= PredMBB
.getFirstTerminator();
1268 for (MachineInstr
&MI
: MBB
.instrs())
1269 if (MI
.isDebugInstr()) {
1270 TII
->duplicate(PredMBB
, InsertBefore
, MI
);
1271 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
1276 static void copyDebugInfoToSuccessor(const TargetInstrInfo
*TII
,
1277 MachineBasicBlock
&MBB
,
1278 MachineBasicBlock
&SuccMBB
) {
1279 auto InsertBefore
= SuccMBB
.SkipPHIsAndLabels(SuccMBB
.begin());
1280 for (MachineInstr
&MI
: MBB
.instrs())
1281 if (MI
.isDebugInstr()) {
1282 TII
->duplicate(SuccMBB
, InsertBefore
, MI
);
1283 LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
1288 // Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
1289 // a basic block is removed we would lose the debug information unless we have
1290 // copied the information to a predecessor/successor.
1292 // TODO: This function only handles some simple cases. An alternative would be
1293 // to run a heavier analysis, such as the LiveDebugValues pass, before we do
1295 static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo
*TII
,
1296 MachineBasicBlock
&MBB
) {
1297 assert(IsEmptyBlock(&MBB
) && "Expected an empty block (except debug info).");
1298 // If this MBB is the only predecessor of a successor it is legal to copy
1299 // DBG_VALUE instructions to the beginning of the successor.
1300 for (MachineBasicBlock
*SuccBB
: MBB
.successors())
1301 if (SuccBB
->pred_size() == 1)
1302 copyDebugInfoToSuccessor(TII
, MBB
, *SuccBB
);
1303 // If this MBB is the only successor of a predecessor it is legal to copy the
1304 // DBG_VALUE instructions to the end of the predecessor (just before the
1305 // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
1306 for (MachineBasicBlock
*PredBB
: MBB
.predecessors())
1307 if (PredBB
->succ_size() == 1)
1308 copyDebugInfoToPredecessor(TII
, MBB
, *PredBB
);
1311 bool BranchFolder::OptimizeBlock(MachineBasicBlock
*MBB
) {
1312 bool MadeChange
= false;
1313 MachineFunction
&MF
= *MBB
->getParent();
1316 MachineFunction::iterator FallThrough
= MBB
->getIterator();
1319 // Make sure MBB and FallThrough belong to the same EH scope.
1320 bool SameEHScope
= true;
1321 if (!EHScopeMembership
.empty() && FallThrough
!= MF
.end()) {
1322 auto MBBEHScope
= EHScopeMembership
.find(MBB
);
1323 assert(MBBEHScope
!= EHScopeMembership
.end());
1324 auto FallThroughEHScope
= EHScopeMembership
.find(&*FallThrough
);
1325 assert(FallThroughEHScope
!= EHScopeMembership
.end());
1326 SameEHScope
= MBBEHScope
->second
== FallThroughEHScope
->second
;
1329 // Analyze the branch in the current block. As a side-effect, this may cause
1330 // the block to become empty.
1331 MachineBasicBlock
*CurTBB
= nullptr, *CurFBB
= nullptr;
1332 SmallVector
<MachineOperand
, 4> CurCond
;
1333 bool CurUnAnalyzable
=
1334 TII
->analyzeBranch(*MBB
, CurTBB
, CurFBB
, CurCond
, true);
1336 // If this block is empty, make everyone use its fall-through, not the block
1337 // explicitly. Landing pads should not do this since the landing-pad table
1338 // points to this block. Blocks with their addresses taken shouldn't be
1340 if (IsEmptyBlock(MBB
) && !MBB
->isEHPad() && !MBB
->hasAddressTaken() &&
1342 salvageDebugInfoFromEmptyBlock(TII
, *MBB
);
1343 // Dead block? Leave for cleanup later.
1344 if (MBB
->pred_empty()) return MadeChange
;
1346 if (FallThrough
== MF
.end()) {
1347 // TODO: Simplify preds to not branch here if possible!
1348 } else if (FallThrough
->isEHPad()) {
1349 // Don't rewrite to a landing pad fallthough. That could lead to the case
1350 // where a BB jumps to more than one landing pad.
1351 // TODO: Is it ever worth rewriting predecessors which don't already
1352 // jump to a landing pad, and so can safely jump to the fallthrough?
1353 } else if (MBB
->isSuccessor(&*FallThrough
)) {
1354 // Rewrite all predecessors of the old block to go to the fallthrough
1356 while (!MBB
->pred_empty()) {
1357 MachineBasicBlock
*Pred
= *(MBB
->pred_end()-1);
1358 Pred
->ReplaceUsesOfBlockWith(MBB
, &*FallThrough
);
1360 // If MBB was the target of a jump table, update jump tables to go to the
1361 // fallthrough instead.
1362 if (MachineJumpTableInfo
*MJTI
= MF
.getJumpTableInfo())
1363 MJTI
->ReplaceMBBInJumpTables(MBB
, &*FallThrough
);
1369 // Check to see if we can simplify the terminator of the block before this
1371 MachineBasicBlock
&PrevBB
= *std::prev(MachineFunction::iterator(MBB
));
1373 MachineBasicBlock
*PriorTBB
= nullptr, *PriorFBB
= nullptr;
1374 SmallVector
<MachineOperand
, 4> PriorCond
;
1375 bool PriorUnAnalyzable
=
1376 TII
->analyzeBranch(PrevBB
, PriorTBB
, PriorFBB
, PriorCond
, true);
1377 if (!PriorUnAnalyzable
) {
1378 // If the previous branch is conditional and both conditions go to the same
1379 // destination, remove the branch, replacing it with an unconditional one or
1381 if (PriorTBB
&& PriorTBB
== PriorFBB
) {
1382 DebugLoc dl
= getBranchDebugLoc(PrevBB
);
1383 TII
->removeBranch(PrevBB
);
1385 if (PriorTBB
!= MBB
)
1386 TII
->insertBranch(PrevBB
, PriorTBB
, nullptr, PriorCond
, dl
);
1389 goto ReoptimizeBlock
;
1392 // If the previous block unconditionally falls through to this block and
1393 // this block has no other predecessors, move the contents of this block
1394 // into the prior block. This doesn't usually happen when SimplifyCFG
1395 // has been used, but it can happen if tail merging splits a fall-through
1396 // predecessor of a block.
1397 // This has to check PrevBB->succ_size() because EH edges are ignored by
1399 if (PriorCond
.empty() && !PriorTBB
&& MBB
->pred_size() == 1 &&
1400 PrevBB
.succ_size() == 1 &&
1401 !MBB
->hasAddressTaken() && !MBB
->isEHPad()) {
1402 LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1403 << "From MBB: " << *MBB
);
1404 // Remove redundant DBG_VALUEs first.
1405 if (!PrevBB
.empty()) {
1406 MachineBasicBlock::iterator PrevBBIter
= PrevBB
.end();
1408 MachineBasicBlock::iterator MBBIter
= MBB
->begin();
1409 // Check if DBG_VALUE at the end of PrevBB is identical to the
1410 // DBG_VALUE at the beginning of MBB.
1411 while (PrevBBIter
!= PrevBB
.begin() && MBBIter
!= MBB
->end()
1412 && PrevBBIter
->isDebugInstr() && MBBIter
->isDebugInstr()) {
1413 if (!MBBIter
->isIdenticalTo(*PrevBBIter
))
1415 MachineInstr
&DuplicateDbg
= *MBBIter
;
1416 ++MBBIter
; -- PrevBBIter
;
1417 DuplicateDbg
.eraseFromParent();
1420 PrevBB
.splice(PrevBB
.end(), MBB
, MBB
->begin(), MBB
->end());
1421 PrevBB
.removeSuccessor(PrevBB
.succ_begin());
1422 assert(PrevBB
.succ_empty());
1423 PrevBB
.transferSuccessors(MBB
);
1428 // If the previous branch *only* branches to *this* block (conditional or
1429 // not) remove the branch.
1430 if (PriorTBB
== MBB
&& !PriorFBB
) {
1431 TII
->removeBranch(PrevBB
);
1434 goto ReoptimizeBlock
;
1437 // If the prior block branches somewhere else on the condition and here if
1438 // the condition is false, remove the uncond second branch.
1439 if (PriorFBB
== MBB
) {
1440 DebugLoc dl
= getBranchDebugLoc(PrevBB
);
1441 TII
->removeBranch(PrevBB
);
1442 TII
->insertBranch(PrevBB
, PriorTBB
, nullptr, PriorCond
, dl
);
1445 goto ReoptimizeBlock
;
1448 // If the prior block branches here on true and somewhere else on false, and
1449 // if the branch condition is reversible, reverse the branch to create a
1451 if (PriorTBB
== MBB
) {
1452 SmallVector
<MachineOperand
, 4> NewPriorCond(PriorCond
);
1453 if (!TII
->reverseBranchCondition(NewPriorCond
)) {
1454 DebugLoc dl
= getBranchDebugLoc(PrevBB
);
1455 TII
->removeBranch(PrevBB
);
1456 TII
->insertBranch(PrevBB
, PriorFBB
, nullptr, NewPriorCond
, dl
);
1459 goto ReoptimizeBlock
;
1463 // If this block has no successors (e.g. it is a return block or ends with
1464 // a call to a no-return function like abort or __cxa_throw) and if the pred
1465 // falls through into this block, and if it would otherwise fall through
1466 // into the block after this, move this block to the end of the function.
1468 // We consider it more likely that execution will stay in the function (e.g.
1469 // due to loops) than it is to exit it. This asserts in loops etc, moving
1470 // the assert condition out of the loop body.
1471 if (MBB
->succ_empty() && !PriorCond
.empty() && !PriorFBB
&&
1472 MachineFunction::iterator(PriorTBB
) == FallThrough
&&
1473 !MBB
->canFallThrough()) {
1474 bool DoTransform
= true;
1476 // We have to be careful that the succs of PredBB aren't both no-successor
1477 // blocks. If neither have successors and if PredBB is the second from
1478 // last block in the function, we'd just keep swapping the two blocks for
1479 // last. Only do the swap if one is clearly better to fall through than
1481 if (FallThrough
== --MF
.end() &&
1482 !IsBetterFallthrough(PriorTBB
, MBB
))
1483 DoTransform
= false;
1486 // Reverse the branch so we will fall through on the previous true cond.
1487 SmallVector
<MachineOperand
, 4> NewPriorCond(PriorCond
);
1488 if (!TII
->reverseBranchCondition(NewPriorCond
)) {
1489 LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1490 << "To make fallthrough to: " << *PriorTBB
<< "\n");
1492 DebugLoc dl
= getBranchDebugLoc(PrevBB
);
1493 TII
->removeBranch(PrevBB
);
1494 TII
->insertBranch(PrevBB
, MBB
, nullptr, NewPriorCond
, dl
);
1496 // Move this block to the end of the function.
1497 MBB
->moveAfter(&MF
.back());
1507 MF
.getFunction().hasOptSize() ||
1508 llvm::shouldOptimizeForSize(MBB
, PSI
, &MBBFreqInfo
);
1509 if (!IsEmptyBlock(MBB
) && MBB
->pred_size() == 1 && OptForSize
) {
1510 // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1511 // direction, thereby defeating careful block placement and regressing
1512 // performance. Therefore, only consider this for optsize functions.
1513 MachineInstr
&TailCall
= *MBB
->getFirstNonDebugInstr();
1514 if (TII
->isUnconditionalTailCall(TailCall
)) {
1515 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
1516 MachineBasicBlock
*PredTBB
= nullptr, *PredFBB
= nullptr;
1517 SmallVector
<MachineOperand
, 4> PredCond
;
1518 bool PredAnalyzable
=
1519 !TII
->analyzeBranch(*Pred
, PredTBB
, PredFBB
, PredCond
, true);
1521 if (PredAnalyzable
&& !PredCond
.empty() && PredTBB
== MBB
&&
1522 PredTBB
!= PredFBB
) {
1523 // The predecessor has a conditional branch to this block which consists
1524 // of only a tail call. Try to fold the tail call into the conditional
1526 if (TII
->canMakeTailCallConditional(PredCond
, TailCall
)) {
1527 // TODO: It would be nice if analyzeBranch() could provide a pointer
1528 // to the branch instruction so replaceBranchWithTailCall() doesn't
1529 // have to search for it.
1530 TII
->replaceBranchWithTailCall(*Pred
, PredCond
, TailCall
);
1532 Pred
->removeSuccessor(MBB
);
1537 // If the predecessor is falling through to this block, we could reverse
1538 // the branch condition and fold the tail call into that. However, after
1539 // that we might have to re-arrange the CFG to fall through to the other
1540 // block and there is a high risk of regressing code size rather than
1545 if (!CurUnAnalyzable
) {
1546 // If this is a two-way branch, and the FBB branches to this block, reverse
1547 // the condition so the single-basic-block loop is faster. Instead of:
1548 // Loop: xxx; jcc Out; jmp Loop
1550 // Loop: xxx; jncc Loop; jmp Out
1551 if (CurTBB
&& CurFBB
&& CurFBB
== MBB
&& CurTBB
!= MBB
) {
1552 SmallVector
<MachineOperand
, 4> NewCond(CurCond
);
1553 if (!TII
->reverseBranchCondition(NewCond
)) {
1554 DebugLoc dl
= getBranchDebugLoc(*MBB
);
1555 TII
->removeBranch(*MBB
);
1556 TII
->insertBranch(*MBB
, CurFBB
, CurTBB
, NewCond
, dl
);
1559 goto ReoptimizeBlock
;
1563 // If this branch is the only thing in its block, see if we can forward
1564 // other blocks across it.
1565 if (CurTBB
&& CurCond
.empty() && !CurFBB
&&
1566 IsBranchOnlyBlock(MBB
) && CurTBB
!= MBB
&&
1567 !MBB
->hasAddressTaken() && !MBB
->isEHPad()) {
1568 DebugLoc dl
= getBranchDebugLoc(*MBB
);
1569 // This block may contain just an unconditional branch. Because there can
1570 // be 'non-branch terminators' in the block, try removing the branch and
1571 // then seeing if the block is empty.
1572 TII
->removeBranch(*MBB
);
1573 // If the only things remaining in the block are debug info, remove these
1574 // as well, so this will behave the same as an empty block in non-debug
1576 if (IsEmptyBlock(MBB
)) {
1577 // Make the block empty, losing the debug info (we could probably
1578 // improve this in some cases.)
1579 MBB
->erase(MBB
->begin(), MBB
->end());
1581 // If this block is just an unconditional branch to CurTBB, we can
1582 // usually completely eliminate the block. The only case we cannot
1583 // completely eliminate the block is when the block before this one
1584 // falls through into MBB and we can't understand the prior block's branch
1587 bool PredHasNoFallThrough
= !PrevBB
.canFallThrough();
1588 if (PredHasNoFallThrough
|| !PriorUnAnalyzable
||
1589 !PrevBB
.isSuccessor(MBB
)) {
1590 // If the prior block falls through into us, turn it into an
1591 // explicit branch to us to make updates simpler.
1592 if (!PredHasNoFallThrough
&& PrevBB
.isSuccessor(MBB
) &&
1593 PriorTBB
!= MBB
&& PriorFBB
!= MBB
) {
1595 assert(PriorCond
.empty() && !PriorFBB
&&
1596 "Bad branch analysis");
1599 assert(!PriorFBB
&& "Machine CFG out of date!");
1602 DebugLoc pdl
= getBranchDebugLoc(PrevBB
);
1603 TII
->removeBranch(PrevBB
);
1604 TII
->insertBranch(PrevBB
, PriorTBB
, PriorFBB
, PriorCond
, pdl
);
1607 // Iterate through all the predecessors, revectoring each in-turn.
1609 bool DidChange
= false;
1610 bool HasBranchToSelf
= false;
1611 while(PI
!= MBB
->pred_size()) {
1612 MachineBasicBlock
*PMBB
= *(MBB
->pred_begin() + PI
);
1614 // If this block has an uncond branch to itself, leave it.
1616 HasBranchToSelf
= true;
1619 PMBB
->ReplaceUsesOfBlockWith(MBB
, CurTBB
);
1620 // If this change resulted in PMBB ending in a conditional
1621 // branch where both conditions go to the same destination,
1622 // change this to an unconditional branch.
1623 MachineBasicBlock
*NewCurTBB
= nullptr, *NewCurFBB
= nullptr;
1624 SmallVector
<MachineOperand
, 4> NewCurCond
;
1625 bool NewCurUnAnalyzable
= TII
->analyzeBranch(
1626 *PMBB
, NewCurTBB
, NewCurFBB
, NewCurCond
, true);
1627 if (!NewCurUnAnalyzable
&& NewCurTBB
&& NewCurTBB
== NewCurFBB
) {
1628 DebugLoc pdl
= getBranchDebugLoc(*PMBB
);
1629 TII
->removeBranch(*PMBB
);
1631 TII
->insertBranch(*PMBB
, NewCurTBB
, nullptr, NewCurCond
, pdl
);
1638 // Change any jumptables to go to the new MBB.
1639 if (MachineJumpTableInfo
*MJTI
= MF
.getJumpTableInfo())
1640 MJTI
->ReplaceMBBInJumpTables(MBB
, CurTBB
);
1644 if (!HasBranchToSelf
) return MadeChange
;
1649 // Add the branch back if the block is more than just an uncond branch.
1650 TII
->insertBranch(*MBB
, CurTBB
, nullptr, CurCond
, dl
);
1654 // If the prior block doesn't fall through into this block, and if this
1655 // block doesn't fall through into some other block, see if we can find a
1656 // place to move this block where a fall-through will happen.
1657 if (!PrevBB
.canFallThrough()) {
1658 // Now we know that there was no fall-through into this block, check to
1659 // see if it has a fall-through into its successor.
1660 bool CurFallsThru
= MBB
->canFallThrough();
1662 if (!MBB
->isEHPad()) {
1663 // Check all the predecessors of this block. If one of them has no fall
1664 // throughs, and analyzeBranch thinks it _could_ fallthrough to this
1665 // block, move this block right after it.
1666 for (MachineBasicBlock
*PredBB
: MBB
->predecessors()) {
1667 // Analyze the branch at the end of the pred.
1668 MachineBasicBlock
*PredTBB
= nullptr, *PredFBB
= nullptr;
1669 SmallVector
<MachineOperand
, 4> PredCond
;
1670 if (PredBB
!= MBB
&& !PredBB
->canFallThrough() &&
1671 !TII
->analyzeBranch(*PredBB
, PredTBB
, PredFBB
, PredCond
, true) &&
1672 (PredTBB
== MBB
|| PredFBB
== MBB
) &&
1673 (!CurFallsThru
|| !CurTBB
|| !CurFBB
) &&
1674 (!CurFallsThru
|| MBB
->getNumber() >= PredBB
->getNumber())) {
1675 // If the current block doesn't fall through, just move it.
1676 // If the current block can fall through and does not end with a
1677 // conditional branch, we need to append an unconditional jump to
1678 // the (current) next block. To avoid a possible compile-time
1679 // infinite loop, move blocks only backward in this case.
1680 // Also, if there are already 2 branches here, we cannot add a third;
1681 // this means we have the case
1686 MachineBasicBlock
*NextBB
= &*std::next(MBB
->getIterator());
1688 TII
->insertBranch(*MBB
, NextBB
, nullptr, CurCond
, DebugLoc());
1690 MBB
->moveAfter(PredBB
);
1692 goto ReoptimizeBlock
;
1697 if (!CurFallsThru
) {
1698 // Check analyzable branch-successors to see if we can move this block
1700 if (!CurUnAnalyzable
) {
1701 for (MachineBasicBlock
*SuccBB
: {CurFBB
, CurTBB
}) {
1704 // Analyze the branch at the end of the block before the succ.
1705 MachineFunction::iterator SuccPrev
= --SuccBB
->getIterator();
1707 // If this block doesn't already fall-through to that successor, and
1708 // if the succ doesn't already have a block that can fall through into
1709 // it, we can arrange for the fallthrough to happen.
1710 if (SuccBB
!= MBB
&& &*SuccPrev
!= MBB
&&
1711 !SuccPrev
->canFallThrough()) {
1712 MBB
->moveBefore(SuccBB
);
1714 goto ReoptimizeBlock
;
1719 // Okay, there is no really great place to put this block. If, however,
1720 // the block before this one would be a fall-through if this block were
1721 // removed, move this block to the end of the function. There is no real
1722 // advantage in "falling through" to an EH block, so we don't want to
1723 // perform this transformation for that case.
1725 // Also, Windows EH introduced the possibility of an arbitrary number of
1726 // successors to a given block. The analyzeBranch call does not consider
1727 // exception handling and so we can get in a state where a block
1728 // containing a call is followed by multiple EH blocks that would be
1729 // rotated infinitely at the end of the function if the transformation
1730 // below were performed for EH "FallThrough" blocks. Therefore, even if
1731 // that appears not to be happening anymore, we should assume that it is
1732 // possible and not remove the "!FallThrough()->isEHPad" condition below.
1733 MachineBasicBlock
*PrevTBB
= nullptr, *PrevFBB
= nullptr;
1734 SmallVector
<MachineOperand
, 4> PrevCond
;
1735 if (FallThrough
!= MF
.end() &&
1736 !FallThrough
->isEHPad() &&
1737 !TII
->analyzeBranch(PrevBB
, PrevTBB
, PrevFBB
, PrevCond
, true) &&
1738 PrevBB
.isSuccessor(&*FallThrough
)) {
1739 MBB
->moveAfter(&MF
.back());
1749 //===----------------------------------------------------------------------===//
1750 // Hoist Common Code
1751 //===----------------------------------------------------------------------===//
1753 bool BranchFolder::HoistCommonCode(MachineFunction
&MF
) {
1754 bool MadeChange
= false;
1755 for (MachineBasicBlock
&MBB
: llvm::make_early_inc_range(MF
))
1756 MadeChange
|= HoistCommonCodeInSuccs(&MBB
);
1761 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1762 /// its 'true' successor.
1763 static MachineBasicBlock
*findFalseBlock(MachineBasicBlock
*BB
,
1764 MachineBasicBlock
*TrueBB
) {
1765 for (MachineBasicBlock
*SuccBB
: BB
->successors())
1766 if (SuccBB
!= TrueBB
)
1771 template <class Container
>
1772 static void addRegAndItsAliases(Register Reg
, const TargetRegisterInfo
*TRI
,
1774 if (Reg
.isPhysical()) {
1775 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
1782 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1783 /// in successors to. The location is usually just before the terminator,
1784 /// however if the terminator is a conditional branch and its previous
1785 /// instruction is the flag setting instruction, the previous instruction is
1786 /// the preferred location. This function also gathers uses and defs of the
1787 /// instructions from the insertion point to the end of the block. The data is
1788 /// used by HoistCommonCodeInSuccs to ensure safety.
1790 MachineBasicBlock::iterator
findHoistingInsertPosAndDeps(MachineBasicBlock
*MBB
,
1791 const TargetInstrInfo
*TII
,
1792 const TargetRegisterInfo
*TRI
,
1793 SmallSet
<Register
, 4> &Uses
,
1794 SmallSet
<Register
, 4> &Defs
) {
1795 MachineBasicBlock::iterator Loc
= MBB
->getFirstTerminator();
1796 if (!TII
->isUnpredicatedTerminator(*Loc
))
1799 for (const MachineOperand
&MO
: Loc
->operands()) {
1802 Register Reg
= MO
.getReg();
1806 addRegAndItsAliases(Reg
, TRI
, Uses
);
1809 // Don't try to hoist code in the rare case the terminator defines a
1810 // register that is later used.
1813 // If the terminator defines a register, make sure we don't hoist
1814 // the instruction whose def might be clobbered by the terminator.
1815 addRegAndItsAliases(Reg
, TRI
, Defs
);
1821 // If the terminator is the only instruction in the block and Uses is not
1822 // empty (or we would have returned above), we can still safely hoist
1823 // instructions just before the terminator as long as the Defs/Uses are not
1824 // violated (which is checked in HoistCommonCodeInSuccs).
1825 if (Loc
== MBB
->begin())
1828 // The terminator is probably a conditional branch, try not to separate the
1829 // branch from condition setting instruction.
1830 MachineBasicBlock::iterator PI
= prev_nodbg(Loc
, MBB
->begin());
1833 for (const MachineOperand
&MO
: PI
->operands()) {
1834 // If PI has a regmask operand, it is probably a call. Separate away.
1837 if (!MO
.isReg() || MO
.isUse())
1839 Register Reg
= MO
.getReg();
1842 if (Uses
.count(Reg
)) {
1848 // The condition setting instruction is not just before the conditional
1852 // Be conservative, don't insert instruction above something that may have
1853 // side-effects. And since it's potentially bad to separate flag setting
1854 // instruction from the conditional branch, just abort the optimization
1856 // Also avoid moving code above predicated instruction since it's hard to
1857 // reason about register liveness with predicated instruction.
1858 bool DontMoveAcrossStore
= true;
1859 if (!PI
->isSafeToMove(nullptr, DontMoveAcrossStore
) || TII
->isPredicated(*PI
))
1862 // Find out what registers are live. Note this routine is ignoring other live
1863 // registers which are only used by instructions in successor blocks.
1864 for (const MachineOperand
&MO
: PI
->operands()) {
1867 Register Reg
= MO
.getReg();
1871 addRegAndItsAliases(Reg
, TRI
, Uses
);
1873 if (Uses
.erase(Reg
)) {
1874 if (Register::isPhysicalRegister(Reg
)) {
1875 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
)
1876 Uses
.erase(*SubRegs
); // Use sub-registers to be conservative
1879 addRegAndItsAliases(Reg
, TRI
, Defs
);
1886 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock
*MBB
) {
1887 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
1888 SmallVector
<MachineOperand
, 4> Cond
;
1889 if (TII
->analyzeBranch(*MBB
, TBB
, FBB
, Cond
, true) || !TBB
|| Cond
.empty())
1892 if (!FBB
) FBB
= findFalseBlock(MBB
, TBB
);
1894 // Malformed bcc? True and false blocks are the same?
1897 // Restrict the optimization to cases where MBB is the only predecessor,
1898 // it is an obvious win.
1899 if (TBB
->pred_size() > 1 || FBB
->pred_size() > 1)
1902 // Find a suitable position to hoist the common instructions to. Also figure
1903 // out which registers are used or defined by instructions from the insertion
1904 // point to the end of the block.
1905 SmallSet
<Register
, 4> Uses
, Defs
;
1906 MachineBasicBlock::iterator Loc
=
1907 findHoistingInsertPosAndDeps(MBB
, TII
, TRI
, Uses
, Defs
);
1908 if (Loc
== MBB
->end())
1911 bool HasDups
= false;
1912 SmallSet
<Register
, 4> ActiveDefsSet
, AllDefsSet
;
1913 MachineBasicBlock::iterator TIB
= TBB
->begin();
1914 MachineBasicBlock::iterator FIB
= FBB
->begin();
1915 MachineBasicBlock::iterator TIE
= TBB
->end();
1916 MachineBasicBlock::iterator FIE
= FBB
->end();
1917 while (TIB
!= TIE
&& FIB
!= FIE
) {
1918 // Skip dbg_value instructions. These do not count.
1919 TIB
= skipDebugInstructionsForward(TIB
, TIE
, false);
1920 FIB
= skipDebugInstructionsForward(FIB
, FIE
, false);
1921 if (TIB
== TIE
|| FIB
== FIE
)
1924 if (!TIB
->isIdenticalTo(*FIB
, MachineInstr::CheckKillDead
))
1927 if (TII
->isPredicated(*TIB
))
1928 // Hard to reason about register liveness with predicated instruction.
1932 for (MachineOperand
&MO
: TIB
->operands()) {
1933 // Don't attempt to hoist instructions with register masks.
1934 if (MO
.isRegMask()) {
1940 Register Reg
= MO
.getReg();
1944 if (Uses
.count(Reg
)) {
1945 // Avoid clobbering a register that's used by the instruction at
1946 // the point of insertion.
1951 if (Defs
.count(Reg
) && !MO
.isDead()) {
1952 // Don't hoist the instruction if the def would be clobber by the
1953 // instruction at the point insertion. FIXME: This is overly
1954 // conservative. It should be possible to hoist the instructions
1955 // in BB2 in the following example:
1957 // r1, eflag = op1 r2, r3
1966 } else if (!ActiveDefsSet
.count(Reg
)) {
1967 if (Defs
.count(Reg
)) {
1968 // Use is defined by the instruction at the point of insertion.
1973 if (MO
.isKill() && Uses
.count(Reg
))
1974 // Kills a register that's read by the instruction at the point of
1975 // insertion. Remove the kill marker.
1976 MO
.setIsKill(false);
1982 bool DontMoveAcrossStore
= true;
1983 if (!TIB
->isSafeToMove(nullptr, DontMoveAcrossStore
))
1986 // Remove kills from ActiveDefsSet, these registers had short live ranges.
1987 for (const MachineOperand
&MO
: TIB
->operands()) {
1988 if (!MO
.isReg() || !MO
.isUse() || !MO
.isKill())
1990 Register Reg
= MO
.getReg();
1993 if (!AllDefsSet
.count(Reg
)) {
1996 if (Reg
.isPhysical()) {
1997 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
1998 ActiveDefsSet
.erase(*AI
);
2000 ActiveDefsSet
.erase(Reg
);
2004 // Track local defs so we can update liveins.
2005 for (const MachineOperand
&MO
: TIB
->operands()) {
2006 if (!MO
.isReg() || !MO
.isDef() || MO
.isDead())
2008 Register Reg
= MO
.getReg();
2009 if (!Reg
|| Reg
.isVirtual())
2011 addRegAndItsAliases(Reg
, TRI
, ActiveDefsSet
);
2012 addRegAndItsAliases(Reg
, TRI
, AllDefsSet
);
2023 MBB
->splice(Loc
, TBB
, TBB
->begin(), TIB
);
2024 FBB
->erase(FBB
->begin(), FIB
);
2026 if (UpdateLiveIns
) {
2027 recomputeLiveIns(*TBB
);
2028 recomputeLiveIns(*FBB
);