1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block.  This pass often results in dead MBB's, which
12 // it then removes.
13 //
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form. It also must handle virtual registers for targets that emit virtual
16 // ISA (e.g. NVPTX).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "BranchFolding.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <algorithm>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "branchfolding"
47 
48 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
49 STATISTIC(NumBranchOpts, "Number of branches optimized");
50 STATISTIC(NumTailMerge , "Number of block tails merged");
51 STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
52 
53 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
54                               cl::init(cl::BOU_UNSET), cl::Hidden);
55 
56 // Throttle for huge numbers of predecessors (compile speed problems)
57 static cl::opt<unsigned>
58 TailMergeThreshold("tail-merge-threshold",
59           cl::desc("Max number of predecessors to consider tail merging"),
60           cl::init(150), cl::Hidden);
61 
62 // Heuristic for tail merging (and, inversely, tail duplication).
63 // TODO: This should be replaced with a target query.
64 static cl::opt<unsigned>
65 TailMergeSize("tail-merge-size",
66           cl::desc("Min number of instructions to consider tail merging"),
67                               cl::init(3), cl::Hidden);
68 
69 namespace {
70   /// BranchFolderPass - Wrap branch folder in a machine function pass.
71   class BranchFolderPass : public MachineFunctionPass {
72   public:
73     static char ID;
74     explicit BranchFolderPass(): MachineFunctionPass(ID) {}
75 
76     bool runOnMachineFunction(MachineFunction &MF) override;
77 
78     void getAnalysisUsage(AnalysisUsage &AU) const override {
79       AU.addRequired<MachineBlockFrequencyInfo>();
80       AU.addRequired<MachineBranchProbabilityInfo>();
81       AU.addRequired<TargetPassConfig>();
82       MachineFunctionPass::getAnalysisUsage(AU);
83     }
84   };
85 }
86 
87 char BranchFolderPass::ID = 0;
88 char &llvm::BranchFolderPassID = BranchFolderPass::ID;
89 
90 INITIALIZE_PASS(BranchFolderPass, "branch-folder",
91                 "Control Flow Optimizer", false, false)
92 
93 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
94   if (skipFunction(*MF.getFunction()))
95     return false;
96 
97   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
98   // TailMerge can create jump into if branches that make CFG irreducible for
99   // HW that requires structurized CFG.
100   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
101                          PassConfig->getEnableTailMerge();
102   BranchFolder::MBFIWrapper MBBFreqInfo(
103       getAnalysis<MachineBlockFrequencyInfo>());
104   BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
105                       getAnalysis<MachineBranchProbabilityInfo>());
106   return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
107                                  MF.getSubtarget().getRegisterInfo(),
108                                  getAnalysisIfAvailable<MachineModuleInfo>());
109 }
110 
111 BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
112                            MBFIWrapper &FreqInfo,
113                            const MachineBranchProbabilityInfo &ProbInfo,
114                            unsigned MinTailLength)
115     : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
116       MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
117   if (MinCommonTailLength == 0)
118     MinCommonTailLength = TailMergeSize;
119   switch (FlagEnableTailMerge) {
120   case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
121   case cl::BOU_TRUE: EnableTailMerge = true; break;
122   case cl::BOU_FALSE: EnableTailMerge = false; break;
123   }
124 }
125 
126 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
127 /// function, updating the CFG.
128 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
129   assert(MBB->pred_empty() && "MBB must be dead!");
130   DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
131 
132   MachineFunction *MF = MBB->getParent();
133   // drop all successors.
134   while (!MBB->succ_empty())
135     MBB->removeSuccessor(MBB->succ_end()-1);
136 
137   // Avoid matching if this pointer gets reused.
138   TriedMerging.erase(MBB);
139 
140   // Remove the block.
141   MF->erase(MBB);
142   FuncletMembership.erase(MBB);
143   if (MLI)
144     MLI->removeBlock(MBB);
145 }
146 
147 /// OptimizeFunction - Perhaps branch folding, tail merging and other
148 /// CFG optimizations on the given function.  Block placement changes the layout
149 /// and may create new tail merging opportunities.
150 bool BranchFolder::OptimizeFunction(MachineFunction &MF,
151                                     const TargetInstrInfo *tii,
152                                     const TargetRegisterInfo *tri,
153                                     MachineModuleInfo *mmi,
154                                     MachineLoopInfo *mli, bool AfterPlacement) {
155   if (!tii) return false;
156 
157   TriedMerging.clear();
158 
159   AfterBlockPlacement = AfterPlacement;
160   TII = tii;
161   TRI = tri;
162   MMI = mmi;
163   MLI = mli;
164 
165   MachineRegisterInfo &MRI = MF.getRegInfo();
166   UpdateLiveIns = MRI.tracksLiveness() && TRI->trackLivenessAfterRegAlloc(MF);
167   if (!UpdateLiveIns)
168     MRI.invalidateLiveness();
169 
170   // Fix CFG.  The later algorithms expect it to be right.
171   bool MadeChange = false;
172   for (MachineBasicBlock &MBB : MF) {
173     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
174     SmallVector<MachineOperand, 4> Cond;
175     if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
176       MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
177   }
178 
179   // Recalculate funclet membership.
180   FuncletMembership = getFuncletMembership(MF);
181 
182   bool MadeChangeThisIteration = true;
183   while (MadeChangeThisIteration) {
184     MadeChangeThisIteration    = TailMergeBlocks(MF);
185     // No need to clean up if tail merging does not change anything after the
186     // block placement.
187     if (!AfterBlockPlacement || MadeChangeThisIteration)
188       MadeChangeThisIteration |= OptimizeBranches(MF);
189     if (EnableHoistCommonCode)
190       MadeChangeThisIteration |= HoistCommonCode(MF);
191     MadeChange |= MadeChangeThisIteration;
192   }
193 
194   // See if any jump tables have become dead as the code generator
195   // did its thing.
196   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
197   if (!JTI)
198     return MadeChange;
199 
200   // Walk the function to find jump tables that are live.
201   BitVector JTIsLive(JTI->getJumpTables().size());
202   for (const MachineBasicBlock &BB : MF) {
203     for (const MachineInstr &I : BB)
204       for (const MachineOperand &Op : I.operands()) {
205         if (!Op.isJTI()) continue;
206 
207         // Remember that this JT is live.
208         JTIsLive.set(Op.getIndex());
209       }
210   }
211 
212   // Finally, remove dead jump tables.  This happens when the
213   // indirect jump was unreachable (and thus deleted).
214   for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
215     if (!JTIsLive.test(i)) {
216       JTI->RemoveJumpTable(i);
217       MadeChange = true;
218     }
219 
220   return MadeChange;
221 }
222 
223 //===----------------------------------------------------------------------===//
224 //  Tail Merging of Blocks
225 //===----------------------------------------------------------------------===//
226 
227 /// HashMachineInstr - Compute a hash value for MI and its operands.
228 static unsigned HashMachineInstr(const MachineInstr &MI) {
229   unsigned Hash = MI.getOpcode();
230   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
231     const MachineOperand &Op = MI.getOperand(i);
232 
233     // Merge in bits from the operand if easy. We can't use MachineOperand's
234     // hash_code here because it's not deterministic and we sort by hash value
235     // later.
236     unsigned OperandHash = 0;
237     switch (Op.getType()) {
238     case MachineOperand::MO_Register:
239       OperandHash = Op.getReg();
240       break;
241     case MachineOperand::MO_Immediate:
242       OperandHash = Op.getImm();
243       break;
244     case MachineOperand::MO_MachineBasicBlock:
245       OperandHash = Op.getMBB()->getNumber();
246       break;
247     case MachineOperand::MO_FrameIndex:
248     case MachineOperand::MO_ConstantPoolIndex:
249     case MachineOperand::MO_JumpTableIndex:
250       OperandHash = Op.getIndex();
251       break;
252     case MachineOperand::MO_GlobalAddress:
253     case MachineOperand::MO_ExternalSymbol:
254       // Global address / external symbol are too hard, don't bother, but do
255       // pull in the offset.
256       OperandHash = Op.getOffset();
257       break;
258     default:
259       break;
260     }
261 
262     Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
263   }
264   return Hash;
265 }
266 
267 /// HashEndOfMBB - Hash the last instruction in the MBB.
268 static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
269   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
270   if (I == MBB.end())
271     return 0;
272 
273   return HashMachineInstr(*I);
274 }
275 
276 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
277 /// of instructions they actually have in common together at their end.  Return
278 /// iterators for the first shared instruction in each block.
279 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
280                                         MachineBasicBlock *MBB2,
281                                         MachineBasicBlock::iterator &I1,
282                                         MachineBasicBlock::iterator &I2) {
283   I1 = MBB1->end();
284   I2 = MBB2->end();
285 
286   unsigned TailLen = 0;
287   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
288     --I1; --I2;
289     // Skip debugging pseudos; necessary to avoid changing the code.
290     while (I1->isDebugValue()) {
291       if (I1==MBB1->begin()) {
292         while (I2->isDebugValue()) {
293           if (I2==MBB2->begin())
294             // I1==DBG at begin; I2==DBG at begin
295             return TailLen;
296           --I2;
297         }
298         ++I2;
299         // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
300         return TailLen;
301       }
302       --I1;
303     }
304     // I1==first (untested) non-DBG preceding known match
305     while (I2->isDebugValue()) {
306       if (I2==MBB2->begin()) {
307         ++I1;
308         // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
309         return TailLen;
310       }
311       --I2;
312     }
313     // I1, I2==first (untested) non-DBGs preceding known match
314     if (!I1->isIdenticalTo(*I2) ||
315         // FIXME: This check is dubious. It's used to get around a problem where
316         // people incorrectly expect inline asm directives to remain in the same
317         // relative order. This is untenable because normal compiler
318         // optimizations (like this one) may reorder and/or merge these
319         // directives.
320         I1->isInlineAsm()) {
321       ++I1; ++I2;
322       break;
323     }
324     ++TailLen;
325   }
326   // Back past possible debugging pseudos at beginning of block.  This matters
327   // when one block differs from the other only by whether debugging pseudos
328   // are present at the beginning. (This way, the various checks later for
329   // I1==MBB1->begin() work as expected.)
330   if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
331     --I2;
332     while (I2->isDebugValue()) {
333       if (I2 == MBB2->begin())
334         return TailLen;
335       --I2;
336     }
337     ++I2;
338   }
339   if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
340     --I1;
341     while (I1->isDebugValue()) {
342       if (I1 == MBB1->begin())
343         return TailLen;
344       --I1;
345     }
346     ++I1;
347   }
348   return TailLen;
349 }
350 
351 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
352 /// after it, replacing it with an unconditional branch to NewDest.
353 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
354                                            MachineBasicBlock *NewDest) {
355   TII->ReplaceTailWithBranchTo(OldInst, NewDest);
356 
357   if (UpdateLiveIns) {
358     NewDest->clearLiveIns();
359     computeLiveIns(LiveRegs, *TRI, *NewDest);
360   }
361 
362   ++NumTailMerge;
363 }
364 
365 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
366 /// MBB so that the part before the iterator falls into the part starting at the
367 /// iterator.  This returns the new MBB.
368 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
369                                             MachineBasicBlock::iterator BBI1,
370                                             const BasicBlock *BB) {
371   if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
372     return nullptr;
373 
374   MachineFunction &MF = *CurMBB.getParent();
375 
376   // Create the fall-through block.
377   MachineFunction::iterator MBBI = CurMBB.getIterator();
378   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(BB);
379   CurMBB.getParent()->insert(++MBBI, NewMBB);
380 
381   // Move all the successors of this block to the specified block.
382   NewMBB->transferSuccessors(&CurMBB);
383 
384   // Add an edge from CurMBB to NewMBB for the fall-through.
385   CurMBB.addSuccessor(NewMBB);
386 
387   // Splice the code over.
388   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
389 
390   // NewMBB belongs to the same loop as CurMBB.
391   if (MLI)
392     if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
393       ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
394 
395   // NewMBB inherits CurMBB's block frequency.
396   MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
397 
398   if (UpdateLiveIns)
399     computeLiveIns(LiveRegs, *TRI, *NewMBB);
400 
401   // Add the new block to the funclet.
402   const auto &FuncletI = FuncletMembership.find(&CurMBB);
403   if (FuncletI != FuncletMembership.end()) {
404     auto n = FuncletI->second;
405     FuncletMembership[NewMBB] = n;
406   }
407 
408   return NewMBB;
409 }
410 
411 /// EstimateRuntime - Make a rough estimate for how long it will take to run
412 /// the specified code.
413 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
414                                 MachineBasicBlock::iterator E) {
415   unsigned Time = 0;
416   for (; I != E; ++I) {
417     if (I->isDebugValue())
418       continue;
419     if (I->isCall())
420       Time += 10;
421     else if (I->mayLoad() || I->mayStore())
422       Time += 2;
423     else
424       ++Time;
425   }
426   return Time;
427 }
428 
429 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
430 // branches temporarily for tail merging).  In the case where CurMBB ends
431 // with a conditional branch to the next block, optimize by reversing the
432 // test and conditionally branching to SuccMBB instead.
433 static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
434                     const TargetInstrInfo *TII) {
435   MachineFunction *MF = CurMBB->getParent();
436   MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
437   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
438   SmallVector<MachineOperand, 4> Cond;
439   DebugLoc dl;  // FIXME: this is nowhere
440   if (I != MF->end() && !TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
441     MachineBasicBlock *NextBB = &*I;
442     if (TBB == NextBB && !Cond.empty() && !FBB) {
443       if (!TII->reverseBranchCondition(Cond)) {
444         TII->removeBranch(*CurMBB);
445         TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
446         return;
447       }
448     }
449   }
450   TII->insertBranch(*CurMBB, SuccBB, nullptr,
451                     SmallVector<MachineOperand, 0>(), dl);
452 }
453 
454 bool
455 BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
456   if (getHash() < o.getHash())
457     return true;
458   if (getHash() > o.getHash())
459     return false;
460   if (getBlock()->getNumber() < o.getBlock()->getNumber())
461     return true;
462   if (getBlock()->getNumber() > o.getBlock()->getNumber())
463     return false;
464   // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
465   // an object with itself.
466 #ifndef _GLIBCXX_DEBUG
467   llvm_unreachable("Predecessor appears twice");
468 #else
469   return false;
470 #endif
471 }
472 
473 BlockFrequency
474 BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
475   auto I = MergedBBFreq.find(MBB);
476 
477   if (I != MergedBBFreq.end())
478     return I->second;
479 
480   return MBFI.getBlockFreq(MBB);
481 }
482 
483 void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
484                                              BlockFrequency F) {
485   MergedBBFreq[MBB] = F;
486 }
487 
488 raw_ostream &
489 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
490                                           const MachineBasicBlock *MBB) const {
491   return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
492 }
493 
494 raw_ostream &
495 BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
496                                           const BlockFrequency Freq) const {
497   return MBFI.printBlockFreq(OS, Freq);
498 }
499 
500 void BranchFolder::MBFIWrapper::view(bool isSimple) { MBFI.view(isSimple); }
501 
502 uint64_t
503 BranchFolder::MBFIWrapper::getEntryFreq() const {
504   return MBFI.getEntryFreq();
505 }
506 
507 /// CountTerminators - Count the number of terminators in the given
508 /// block and set I to the position of the first non-terminator, if there
509 /// is one, or MBB->end() otherwise.
510 static unsigned CountTerminators(MachineBasicBlock *MBB,
511                                  MachineBasicBlock::iterator &I) {
512   I = MBB->end();
513   unsigned NumTerms = 0;
514   for (;;) {
515     if (I == MBB->begin()) {
516       I = MBB->end();
517       break;
518     }
519     --I;
520     if (!I->isTerminator()) break;
521     ++NumTerms;
522   }
523   return NumTerms;
524 }
525 
526 /// A no successor, non-return block probably ends in unreachable and is cold.
527 /// Also consider a block that ends in an indirect branch to be a return block,
528 /// since many targets use plain indirect branches to return.
529 static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
530   if (!MBB->succ_empty())
531     return false;
532   if (MBB->empty())
533     return true;
534   return !(MBB->back().isReturn() || MBB->back().isIndirectBranch());
535 }
536 
537 /// ProfitableToMerge - Check if two machine basic blocks have a common tail
538 /// and decide if it would be profitable to merge those tails.  Return the
539 /// length of the common tail and iterators to the first common instruction
540 /// in each block.
541 /// MBB1, MBB2      The blocks to check
542 /// MinCommonTailLength  Minimum size of tail block to be merged.
543 /// CommonTailLen   Out parameter to record the size of the shared tail between
544 ///                 MBB1 and MBB2
545 /// I1, I2          Iterator references that will be changed to point to the first
546 ///                 instruction in the common tail shared by MBB1,MBB2
547 /// SuccBB          A common successor of MBB1, MBB2 which are in a canonical form
548 ///                 relative to SuccBB
549 /// PredBB          The layout predecessor of SuccBB, if any.
550 /// FuncletMembership  map from block to funclet #.
551 /// AfterPlacement  True if we are merging blocks after layout. Stricter
552 ///                 thresholds apply to prevent undoing tail-duplication.
553 static bool
554 ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
555                   unsigned MinCommonTailLength, unsigned &CommonTailLen,
556                   MachineBasicBlock::iterator &I1,
557                   MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
558                   MachineBasicBlock *PredBB,
559                   DenseMap<const MachineBasicBlock *, int> &FuncletMembership,
560                   bool AfterPlacement) {
561   // It is never profitable to tail-merge blocks from two different funclets.
562   if (!FuncletMembership.empty()) {
563     auto Funclet1 = FuncletMembership.find(MBB1);
564     assert(Funclet1 != FuncletMembership.end());
565     auto Funclet2 = FuncletMembership.find(MBB2);
566     assert(Funclet2 != FuncletMembership.end());
567     if (Funclet1->second != Funclet2->second)
568       return false;
569   }
570 
571   CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
572   if (CommonTailLen == 0)
573     return false;
574   DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
575                << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
576                << '\n');
577 
578   // It's almost always profitable to merge any number of non-terminator
579   // instructions with the block that falls through into the common successor.
580   // This is true only for a single successor. For multiple successors, we are
581   // trading a conditional branch for an unconditional one.
582   // TODO: Re-visit successor size for non-layout tail merging.
583   if ((MBB1 == PredBB || MBB2 == PredBB) &&
584       (!AfterPlacement || MBB1->succ_size() == 1)) {
585     MachineBasicBlock::iterator I;
586     unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
587     if (CommonTailLen > NumTerms)
588       return true;
589   }
590 
591   // If these are identical non-return blocks with no successors, merge them.
592   // Such blocks are typically cold calls to noreturn functions like abort, and
593   // are unlikely to become a fallthrough target after machine block placement.
594   // Tail merging these blocks is unlikely to create additional unconditional
595   // branches, and will reduce the size of this cold code.
596   if (I1 == MBB1->begin() && I2 == MBB2->begin() &&
597       blockEndsInUnreachable(MBB1) && blockEndsInUnreachable(MBB2))
598     return true;
599 
600   // If one of the blocks can be completely merged and happens to be in
601   // a position where the other could fall through into it, merge any number
602   // of instructions, because it can be done without a branch.
603   // TODO: If the blocks are not adjacent, move one of them so that they are?
604   if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
605     return true;
606   if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
607     return true;
608 
609   // If both blocks have an unconditional branch temporarily stripped out,
610   // count that as an additional common instruction for the following
611   // heuristics. This heuristic is only accurate for single-succ blocks, so to
612   // make sure that during layout merging and duplicating don't crash, we check
613   // for that when merging during layout.
614   unsigned EffectiveTailLen = CommonTailLen;
615   if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
616       (MBB1->succ_size() == 1 || !AfterPlacement) &&
617       !MBB1->back().isBarrier() &&
618       !MBB2->back().isBarrier())
619     ++EffectiveTailLen;
620 
621   // Check if the common tail is long enough to be worthwhile.
622   if (EffectiveTailLen >= MinCommonTailLength)
623     return true;
624 
625   // If we are optimizing for code size, 2 instructions in common is enough if
626   // we don't have to split a block.  At worst we will be introducing 1 new
627   // branch instruction, which is likely to be smaller than the 2
628   // instructions that would be deleted in the merge.
629   MachineFunction *MF = MBB1->getParent();
630   return EffectiveTailLen >= 2 && MF->getFunction()->optForSize() &&
631          (I1 == MBB1->begin() || I2 == MBB2->begin());
632 }
633 
634 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
635 /// hash CurHash (guaranteed to match the last element).  Build the vector
636 /// SameTails of all those that have the (same) largest number of instructions
637 /// in common of any pair of these blocks.  SameTails entries contain an
638 /// iterator into MergePotentials (from which the MachineBasicBlock can be
639 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
640 /// instruction where the matching code sequence begins.
641 /// Order of elements in SameTails is the reverse of the order in which
642 /// those blocks appear in MergePotentials (where they are not necessarily
643 /// consecutive).
644 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
645                                         unsigned MinCommonTailLength,
646                                         MachineBasicBlock *SuccBB,
647                                         MachineBasicBlock *PredBB) {
648   unsigned maxCommonTailLength = 0U;
649   SameTails.clear();
650   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
651   MPIterator HighestMPIter = std::prev(MergePotentials.end());
652   for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
653                   B = MergePotentials.begin();
654        CurMPIter != B && CurMPIter->getHash() == CurHash; --CurMPIter) {
655     for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; --I) {
656       unsigned CommonTailLen;
657       if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
658                             MinCommonTailLength,
659                             CommonTailLen, TrialBBI1, TrialBBI2,
660                             SuccBB, PredBB,
661                             FuncletMembership,
662                             AfterBlockPlacement)) {
663         if (CommonTailLen > maxCommonTailLength) {
664           SameTails.clear();
665           maxCommonTailLength = CommonTailLen;
666           HighestMPIter = CurMPIter;
667           SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
668         }
669         if (HighestMPIter == CurMPIter &&
670             CommonTailLen == maxCommonTailLength)
671           SameTails.push_back(SameTailElt(I, TrialBBI2));
672       }
673       if (I == B)
674         break;
675     }
676   }
677   return maxCommonTailLength;
678 }
679 
680 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
681 /// MergePotentials, restoring branches at ends of blocks as appropriate.
682 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
683                                         MachineBasicBlock *SuccBB,
684                                         MachineBasicBlock *PredBB) {
685   MPIterator CurMPIter, B;
686   for (CurMPIter = std::prev(MergePotentials.end()),
687       B = MergePotentials.begin();
688        CurMPIter->getHash() == CurHash; --CurMPIter) {
689     // Put the unconditional branch back, if we need one.
690     MachineBasicBlock *CurMBB = CurMPIter->getBlock();
691     if (SuccBB && CurMBB != PredBB)
692       FixTail(CurMBB, SuccBB, TII);
693     if (CurMPIter == B)
694       break;
695   }
696   if (CurMPIter->getHash() != CurHash)
697     CurMPIter++;
698   MergePotentials.erase(CurMPIter, MergePotentials.end());
699 }
700 
701 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
702 /// only of the common tail.  Create a block that does by splitting one.
703 bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
704                                              MachineBasicBlock *SuccBB,
705                                              unsigned maxCommonTailLength,
706                                              unsigned &commonTailIndex) {
707   commonTailIndex = 0;
708   unsigned TimeEstimate = ~0U;
709   for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
710     // Use PredBB if possible; that doesn't require a new branch.
711     if (SameTails[i].getBlock() == PredBB) {
712       commonTailIndex = i;
713       break;
714     }
715     // Otherwise, make a (fairly bogus) choice based on estimate of
716     // how long it will take the various blocks to execute.
717     unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
718                                  SameTails[i].getTailStartPos());
719     if (t <= TimeEstimate) {
720       TimeEstimate = t;
721       commonTailIndex = i;
722     }
723   }
724 
725   MachineBasicBlock::iterator BBI =
726     SameTails[commonTailIndex].getTailStartPos();
727   MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
728 
729   DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
730                << maxCommonTailLength);
731 
732   // If the split block unconditionally falls-thru to SuccBB, it will be
733   // merged. In control flow terms it should then take SuccBB's name. e.g. If
734   // SuccBB is an inner loop, the common tail is still part of the inner loop.
735   const BasicBlock *BB = (SuccBB && MBB->succ_size() == 1) ?
736     SuccBB->getBasicBlock() : MBB->getBasicBlock();
737   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
738   if (!newMBB) {
739     DEBUG(dbgs() << "... failed!");
740     return false;
741   }
742 
743   SameTails[commonTailIndex].setBlock(newMBB);
744   SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
745 
746   // If we split PredBB, newMBB is the new predecessor.
747   if (PredBB == MBB)
748     PredBB = newMBB;
749 
750   return true;
751 }
752 
753 static void
754 mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
755                 MachineBasicBlock &MBBCommon) {
756   MachineBasicBlock *MBB = MBBIStartPos->getParent();
757   // Note CommonTailLen does not necessarily matches the size of
758   // the common BB nor all its instructions because of debug
759   // instructions differences.
760   unsigned CommonTailLen = 0;
761   for (auto E = MBB->end(); MBBIStartPos != E; ++MBBIStartPos)
762     ++CommonTailLen;
763 
764   MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
765   MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
766   MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
767   MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
768 
769   while (CommonTailLen--) {
770     assert(MBBI != MBBIE && "Reached BB end within common tail length!");
771     (void)MBBIE;
772 
773     if (MBBI->isDebugValue()) {
774       ++MBBI;
775       continue;
776     }
777 
778     while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
779       ++MBBICommon;
780 
781     assert(MBBICommon != MBBIECommon &&
782            "Reached BB end within common tail length!");
783     assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
784 
785     // Merge MMOs from memory operations in the common block.
786     if (MBBICommon->mayLoad() || MBBICommon->mayStore())
787       MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
788     // Drop undef flags if they aren't present in all merged instructions.
789     for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; ++I) {
790       MachineOperand &MO = MBBICommon->getOperand(I);
791       if (MO.isReg() && MO.isUndef()) {
792         const MachineOperand &OtherMO = MBBI->getOperand(I);
793         if (!OtherMO.isUndef())
794           MO.setIsUndef(false);
795       }
796     }
797 
798     ++MBBI;
799     ++MBBICommon;
800   }
801 }
802 
803 // See if any of the blocks in MergePotentials (which all have SuccBB as a
804 // successor, or all have no successor if it is null) can be tail-merged.
805 // If there is a successor, any blocks in MergePotentials that are not
806 // tail-merged and are not immediately before Succ must have an unconditional
807 // branch to Succ added (but the predecessor/successor lists need no
808 // adjustment). The lone predecessor of Succ that falls through into Succ,
809 // if any, is given in PredBB.
810 // MinCommonTailLength - Except for the special cases below, tail-merge if
811 // there are at least this many instructions in common.
812 bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
813                                       MachineBasicBlock *PredBB,
814                                       unsigned MinCommonTailLength) {
815   bool MadeChange = false;
816 
817   DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
818         for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
819           dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
820                  << (i == e-1 ? "" : ", ");
821         dbgs() << "\n";
822         if (SuccBB) {
823           dbgs() << "  with successor BB#" << SuccBB->getNumber() << '\n';
824           if (PredBB)
825             dbgs() << "  which has fall-through from BB#"
826                    << PredBB->getNumber() << "\n";
827         }
828         dbgs() << "Looking for common tails of at least "
829                << MinCommonTailLength << " instruction"
830                << (MinCommonTailLength == 1 ? "" : "s") << '\n';
831        );
832 
833   // Sort by hash value so that blocks with identical end sequences sort
834   // together.
835   array_pod_sort(MergePotentials.begin(), MergePotentials.end());
836 
837   // Walk through equivalence sets looking for actual exact matches.
838   while (MergePotentials.size() > 1) {
839     unsigned CurHash = MergePotentials.back().getHash();
840 
841     // Build SameTails, identifying the set of blocks with this hash code
842     // and with the maximum number of instructions in common.
843     unsigned maxCommonTailLength = ComputeSameTails(CurHash,
844                                                     MinCommonTailLength,
845                                                     SuccBB, PredBB);
846 
847     // If we didn't find any pair that has at least MinCommonTailLength
848     // instructions in common, remove all blocks with this hash code and retry.
849     if (SameTails.empty()) {
850       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
851       continue;
852     }
853 
854     // If one of the blocks is the entire common tail (and not the entry
855     // block, which we can't jump to), we can treat all blocks with this same
856     // tail at once.  Use PredBB if that is one of the possibilities, as that
857     // will not introduce any extra branches.
858     MachineBasicBlock *EntryBB =
859         &MergePotentials.front().getBlock()->getParent()->front();
860     unsigned commonTailIndex = SameTails.size();
861     // If there are two blocks, check to see if one can be made to fall through
862     // into the other.
863     if (SameTails.size() == 2 &&
864         SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
865         SameTails[1].tailIsWholeBlock())
866       commonTailIndex = 1;
867     else if (SameTails.size() == 2 &&
868              SameTails[1].getBlock()->isLayoutSuccessor(
869                                                      SameTails[0].getBlock()) &&
870              SameTails[0].tailIsWholeBlock())
871       commonTailIndex = 0;
872     else {
873       // Otherwise just pick one, favoring the fall-through predecessor if
874       // there is one.
875       for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
876         MachineBasicBlock *MBB = SameTails[i].getBlock();
877         if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
878           continue;
879         if (MBB == PredBB) {
880           commonTailIndex = i;
881           break;
882         }
883         if (SameTails[i].tailIsWholeBlock())
884           commonTailIndex = i;
885       }
886     }
887 
888     if (commonTailIndex == SameTails.size() ||
889         (SameTails[commonTailIndex].getBlock() == PredBB &&
890          !SameTails[commonTailIndex].tailIsWholeBlock())) {
891       // None of the blocks consist entirely of the common tail.
892       // Split a block so that one does.
893       if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
894                                      maxCommonTailLength, commonTailIndex)) {
895         RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
896         continue;
897       }
898     }
899 
900     MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
901 
902     // Recompute common tail MBB's edge weights and block frequency.
903     setCommonTailEdgeWeights(*MBB);
904 
905     // Remove the original debug location from the common tail.
906     for (auto &MI : *MBB)
907       if (!MI.isDebugValue())
908         MI.setDebugLoc(DebugLoc());
909 
910     // MBB is common tail.  Adjust all other BB's to jump to this one.
911     // Traversal must be forwards so erases work.
912     DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
913                  << " for ");
914     for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
915       if (commonTailIndex == i)
916         continue;
917       DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
918                    << (i == e-1 ? "" : ", "));
919       // Merge operations (MMOs, undef flags)
920       mergeOperations(SameTails[i].getTailStartPos(), *MBB);
921       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
922       ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
923       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
924       MergePotentials.erase(SameTails[i].getMPIter());
925     }
926     DEBUG(dbgs() << "\n");
927     // We leave commonTailIndex in the worklist in case there are other blocks
928     // that match it with a smaller number of instructions.
929     MadeChange = true;
930   }
931   return MadeChange;
932 }
933 
934 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
935   bool MadeChange = false;
936   if (!EnableTailMerge) return MadeChange;
937 
938   // First find blocks with no successors.
939   // Block placement does not create new tail merging opportunities for these
940   // blocks.
941   if (!AfterBlockPlacement) {
942     MergePotentials.clear();
943     for (MachineBasicBlock &MBB : MF) {
944       if (MergePotentials.size() == TailMergeThreshold)
945         break;
946       if (!TriedMerging.count(&MBB) && MBB.succ_empty())
947         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
948     }
949 
950     // If this is a large problem, avoid visiting the same basic blocks
951     // multiple times.
952     if (MergePotentials.size() == TailMergeThreshold)
953       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
954         TriedMerging.insert(MergePotentials[i].getBlock());
955 
956     // See if we can do any tail merging on those.
957     if (MergePotentials.size() >= 2)
958       MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
959   }
960 
961   // Look at blocks (IBB) with multiple predecessors (PBB).
962   // We change each predecessor to a canonical form, by
963   // (1) temporarily removing any unconditional branch from the predecessor
964   // to IBB, and
965   // (2) alter conditional branches so they branch to the other block
966   // not IBB; this may require adding back an unconditional branch to IBB
967   // later, where there wasn't one coming in.  E.g.
968   //   Bcc IBB
969   //   fallthrough to QBB
970   // here becomes
971   //   Bncc QBB
972   // with a conceptual B to IBB after that, which never actually exists.
973   // With those changes, we see whether the predecessors' tails match,
974   // and merge them if so.  We change things out of canonical form and
975   // back to the way they were later in the process.  (OptimizeBranches
976   // would undo some of this, but we can't use it, because we'd get into
977   // a compile-time infinite loop repeatedly doing and undoing the same
978   // transformations.)
979 
980   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
981        I != E; ++I) {
982     if (I->pred_size() < 2) continue;
983     SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
984     MachineBasicBlock *IBB = &*I;
985     MachineBasicBlock *PredBB = &*std::prev(I);
986     MergePotentials.clear();
987     MachineLoop *ML;
988 
989     // Bail if merging after placement and IBB is the loop header because
990     // -- If merging predecessors that belong to the same loop as IBB, the
991     // common tail of merged predecessors may become the loop top if block
992     // placement is called again and the predecessors may branch to this common
993     // tail and require more branches. This can be relaxed if
994     // MachineBlockPlacement::findBestLoopTop is more flexible.
995     // --If merging predecessors that do not belong to the same loop as IBB, the
996     // loop info of IBB's loop and the other loops may be affected. Calling the
997     // block placement again may make big change to the layout and eliminate the
998     // reason to do tail merging here.
999     if (AfterBlockPlacement && MLI) {
1000       ML = MLI->getLoopFor(IBB);
1001       if (ML && IBB == ML->getHeader())
1002         continue;
1003     }
1004 
1005     for (MachineBasicBlock *PBB : I->predecessors()) {
1006       if (MergePotentials.size() == TailMergeThreshold)
1007         break;
1008 
1009       if (TriedMerging.count(PBB))
1010         continue;
1011 
1012       // Skip blocks that loop to themselves, can't tail merge these.
1013       if (PBB == IBB)
1014         continue;
1015 
1016       // Visit each predecessor only once.
1017       if (!UniquePreds.insert(PBB).second)
1018         continue;
1019 
1020       // Skip blocks which may jump to a landing pad. Can't tail merge these.
1021       if (PBB->hasEHPadSuccessor())
1022         continue;
1023 
1024       // After block placement, only consider predecessors that belong to the
1025       // same loop as IBB.  The reason is the same as above when skipping loop
1026       // header.
1027       if (AfterBlockPlacement && MLI)
1028         if (ML != MLI->getLoopFor(PBB))
1029           continue;
1030 
1031       MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1032       SmallVector<MachineOperand, 4> Cond;
1033       if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1034         // Failing case: IBB is the target of a cbr, and we cannot reverse the
1035         // branch.
1036         SmallVector<MachineOperand, 4> NewCond(Cond);
1037         if (!Cond.empty() && TBB == IBB) {
1038           if (TII->reverseBranchCondition(NewCond))
1039             continue;
1040           // This is the QBB case described above
1041           if (!FBB) {
1042             auto Next = ++PBB->getIterator();
1043             if (Next != MF.end())
1044               FBB = &*Next;
1045           }
1046         }
1047 
1048         // Failing case: the only way IBB can be reached from PBB is via
1049         // exception handling.  Happens for landing pads.  Would be nice to have
1050         // a bit in the edge so we didn't have to do all this.
1051         if (IBB->isEHPad()) {
1052           MachineFunction::iterator IP = ++PBB->getIterator();
1053           MachineBasicBlock *PredNextBB = nullptr;
1054           if (IP != MF.end())
1055             PredNextBB = &*IP;
1056           if (!TBB) {
1057             if (IBB != PredNextBB)      // fallthrough
1058               continue;
1059           } else if (FBB) {
1060             if (TBB != IBB && FBB != IBB)   // cbr then ubr
1061               continue;
1062           } else if (Cond.empty()) {
1063             if (TBB != IBB)               // ubr
1064               continue;
1065           } else {
1066             if (TBB != IBB && IBB != PredNextBB)  // cbr
1067               continue;
1068           }
1069         }
1070 
1071         // Remove the unconditional branch at the end, if any.
1072         if (TBB && (Cond.empty() || FBB)) {
1073           DebugLoc dl;  // FIXME: this is nowhere
1074           TII->removeBranch(*PBB);
1075           if (!Cond.empty())
1076             // reinsert conditional branch only, for now
1077             TII->insertBranch(*PBB, (TBB == IBB) ? FBB : TBB, nullptr,
1078                               NewCond, dl);
1079         }
1080 
1081         MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1082       }
1083     }
1084 
1085     // If this is a large problem, avoid visiting the same basic blocks multiple
1086     // times.
1087     if (MergePotentials.size() == TailMergeThreshold)
1088       for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1089         TriedMerging.insert(MergePotentials[i].getBlock());
1090 
1091     if (MergePotentials.size() >= 2)
1092       MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1093 
1094     // Reinsert an unconditional branch if needed. The 1 below can occur as a
1095     // result of removing blocks in TryTailMergeBlocks.
1096     PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1097     if (MergePotentials.size() == 1 &&
1098         MergePotentials.begin()->getBlock() != PredBB)
1099       FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1100   }
1101 
1102   return MadeChange;
1103 }
1104 
1105 void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1106   SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1107   BlockFrequency AccumulatedMBBFreq;
1108 
1109   // Aggregate edge frequency of successor edge j:
1110   //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1111   //  where bb is a basic block that is in SameTails.
1112   for (const auto &Src : SameTails) {
1113     const MachineBasicBlock *SrcMBB = Src.getBlock();
1114     BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1115     AccumulatedMBBFreq += BlockFreq;
1116 
1117     // It is not necessary to recompute edge weights if TailBB has less than two
1118     // successors.
1119     if (TailMBB.succ_size() <= 1)
1120       continue;
1121 
1122     auto EdgeFreq = EdgeFreqLs.begin();
1123 
1124     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1125          SuccI != SuccE; ++SuccI, ++EdgeFreq)
1126       *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1127   }
1128 
1129   MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1130 
1131   if (TailMBB.succ_size() <= 1)
1132     return;
1133 
1134   auto SumEdgeFreq =
1135       std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1136           .getFrequency();
1137   auto EdgeFreq = EdgeFreqLs.begin();
1138 
1139   if (SumEdgeFreq > 0) {
1140     for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1141          SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1142       auto Prob = BranchProbability::getBranchProbability(
1143           EdgeFreq->getFrequency(), SumEdgeFreq);
1144       TailMBB.setSuccProbability(SuccI, Prob);
1145     }
1146   }
1147 }
1148 
1149 //===----------------------------------------------------------------------===//
1150 //  Branch Optimization
1151 //===----------------------------------------------------------------------===//
1152 
1153 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1154   bool MadeChange = false;
1155 
1156   // Make sure blocks are numbered in order
1157   MF.RenumberBlocks();
1158   // Renumbering blocks alters funclet membership, recalculate it.
1159   FuncletMembership = getFuncletMembership(MF);
1160 
1161   for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1162        I != E; ) {
1163     MachineBasicBlock *MBB = &*I++;
1164     MadeChange |= OptimizeBlock(MBB);
1165 
1166     // If it is dead, remove it.
1167     if (MBB->pred_empty()) {
1168       RemoveDeadBlock(MBB);
1169       MadeChange = true;
1170       ++NumDeadBlocks;
1171     }
1172   }
1173 
1174   return MadeChange;
1175 }
1176 
1177 // Blocks should be considered empty if they contain only debug info;
1178 // else the debug info would affect codegen.
1179 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1180   return MBB->getFirstNonDebugInstr() == MBB->end();
1181 }
1182 
1183 // Blocks with only debug info and branches should be considered the same
1184 // as blocks with only branches.
1185 static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1186   MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1187   assert(I != MBB->end() && "empty block!");
1188   return I->isBranch();
1189 }
1190 
1191 /// IsBetterFallthrough - Return true if it would be clearly better to
1192 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
1193 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1194 /// result in infinite loops.
1195 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1196                                 MachineBasicBlock *MBB2) {
1197   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
1198   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
1199   // optimize branches that branch to either a return block or an assert block
1200   // into a fallthrough to the return.
1201   MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1202   MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1203   if (MBB1I == MBB1->end() || MBB2I == MBB2->end())
1204     return false;
1205 
1206   // If there is a clear successor ordering we make sure that one block
1207   // will fall through to the next
1208   if (MBB1->isSuccessor(MBB2)) return true;
1209   if (MBB2->isSuccessor(MBB1)) return false;
1210 
1211   return MBB2I->isCall() && !MBB1I->isCall();
1212 }
1213 
1214 /// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1215 /// instructions on the block.
1216 static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1217   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1218   if (I != MBB.end() && I->isBranch())
1219     return I->getDebugLoc();
1220   return DebugLoc();
1221 }
1222 
1223 /// OptimizeBlock - Analyze and optimize control flow related to the specified
1224 /// block.  This is never called on the entry block.
1225 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1226   bool MadeChange = false;
1227   MachineFunction &MF = *MBB->getParent();
1228 ReoptimizeBlock:
1229 
1230   MachineFunction::iterator FallThrough = MBB->getIterator();
1231   ++FallThrough;
1232 
1233   // Make sure MBB and FallThrough belong to the same funclet.
1234   bool SameFunclet = true;
1235   if (!FuncletMembership.empty() && FallThrough != MF.end()) {
1236     auto MBBFunclet = FuncletMembership.find(MBB);
1237     assert(MBBFunclet != FuncletMembership.end());
1238     auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1239     assert(FallThroughFunclet != FuncletMembership.end());
1240     SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1241   }
1242 
1243   // If this block is empty, make everyone use its fall-through, not the block
1244   // explicitly.  Landing pads should not do this since the landing-pad table
1245   // points to this block.  Blocks with their addresses taken shouldn't be
1246   // optimized away.
1247   if (IsEmptyBlock(MBB) && !MBB->isEHPad() && !MBB->hasAddressTaken() &&
1248       SameFunclet) {
1249     // Dead block?  Leave for cleanup later.
1250     if (MBB->pred_empty()) return MadeChange;
1251 
1252     if (FallThrough == MF.end()) {
1253       // TODO: Simplify preds to not branch here if possible!
1254     } else if (FallThrough->isEHPad()) {
1255       // Don't rewrite to a landing pad fallthough.  That could lead to the case
1256       // where a BB jumps to more than one landing pad.
1257       // TODO: Is it ever worth rewriting predecessors which don't already
1258       // jump to a landing pad, and so can safely jump to the fallthrough?
1259     } else if (MBB->isSuccessor(&*FallThrough)) {
1260       // Rewrite all predecessors of the old block to go to the fallthrough
1261       // instead.
1262       while (!MBB->pred_empty()) {
1263         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1264         Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1265       }
1266       // If MBB was the target of a jump table, update jump tables to go to the
1267       // fallthrough instead.
1268       if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1269         MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1270       MadeChange = true;
1271     }
1272     return MadeChange;
1273   }
1274 
1275   // Check to see if we can simplify the terminator of the block before this
1276   // one.
1277   MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1278 
1279   MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1280   SmallVector<MachineOperand, 4> PriorCond;
1281   bool PriorUnAnalyzable =
1282       TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1283   if (!PriorUnAnalyzable) {
1284     // If the CFG for the prior block has extra edges, remove them.
1285     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1286                                               !PriorCond.empty());
1287 
1288     // If the previous branch is conditional and both conditions go to the same
1289     // destination, remove the branch, replacing it with an unconditional one or
1290     // a fall-through.
1291     if (PriorTBB && PriorTBB == PriorFBB) {
1292       DebugLoc dl = getBranchDebugLoc(PrevBB);
1293       TII->removeBranch(PrevBB);
1294       PriorCond.clear();
1295       if (PriorTBB != MBB)
1296         TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1297       MadeChange = true;
1298       ++NumBranchOpts;
1299       goto ReoptimizeBlock;
1300     }
1301 
1302     // If the previous block unconditionally falls through to this block and
1303     // this block has no other predecessors, move the contents of this block
1304     // into the prior block. This doesn't usually happen when SimplifyCFG
1305     // has been used, but it can happen if tail merging splits a fall-through
1306     // predecessor of a block.
1307     // This has to check PrevBB->succ_size() because EH edges are ignored by
1308     // AnalyzeBranch.
1309     if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1310         PrevBB.succ_size() == 1 &&
1311         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1312       DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1313                    << "From MBB: " << *MBB);
1314       // Remove redundant DBG_VALUEs first.
1315       if (PrevBB.begin() != PrevBB.end()) {
1316         MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1317         --PrevBBIter;
1318         MachineBasicBlock::iterator MBBIter = MBB->begin();
1319         // Check if DBG_VALUE at the end of PrevBB is identical to the
1320         // DBG_VALUE at the beginning of MBB.
1321         while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1322                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1323           if (!MBBIter->isIdenticalTo(*PrevBBIter))
1324             break;
1325           MachineInstr &DuplicateDbg = *MBBIter;
1326           ++MBBIter; -- PrevBBIter;
1327           DuplicateDbg.eraseFromParent();
1328         }
1329       }
1330       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1331       PrevBB.removeSuccessor(PrevBB.succ_begin());
1332       assert(PrevBB.succ_empty());
1333       PrevBB.transferSuccessors(MBB);
1334       MadeChange = true;
1335       return MadeChange;
1336     }
1337 
1338     // If the previous branch *only* branches to *this* block (conditional or
1339     // not) remove the branch.
1340     if (PriorTBB == MBB && !PriorFBB) {
1341       TII->removeBranch(PrevBB);
1342       MadeChange = true;
1343       ++NumBranchOpts;
1344       goto ReoptimizeBlock;
1345     }
1346 
1347     // If the prior block branches somewhere else on the condition and here if
1348     // the condition is false, remove the uncond second branch.
1349     if (PriorFBB == MBB) {
1350       DebugLoc dl = getBranchDebugLoc(PrevBB);
1351       TII->removeBranch(PrevBB);
1352       TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1353       MadeChange = true;
1354       ++NumBranchOpts;
1355       goto ReoptimizeBlock;
1356     }
1357 
1358     // If the prior block branches here on true and somewhere else on false, and
1359     // if the branch condition is reversible, reverse the branch to create a
1360     // fall-through.
1361     if (PriorTBB == MBB) {
1362       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1363       if (!TII->reverseBranchCondition(NewPriorCond)) {
1364         DebugLoc dl = getBranchDebugLoc(PrevBB);
1365         TII->removeBranch(PrevBB);
1366         TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1367         MadeChange = true;
1368         ++NumBranchOpts;
1369         goto ReoptimizeBlock;
1370       }
1371     }
1372 
1373     // If this block has no successors (e.g. it is a return block or ends with
1374     // a call to a no-return function like abort or __cxa_throw) and if the pred
1375     // falls through into this block, and if it would otherwise fall through
1376     // into the block after this, move this block to the end of the function.
1377     //
1378     // We consider it more likely that execution will stay in the function (e.g.
1379     // due to loops) than it is to exit it.  This asserts in loops etc, moving
1380     // the assert condition out of the loop body.
1381     if (MBB->succ_empty() && !PriorCond.empty() && !PriorFBB &&
1382         MachineFunction::iterator(PriorTBB) == FallThrough &&
1383         !MBB->canFallThrough()) {
1384       bool DoTransform = true;
1385 
1386       // We have to be careful that the succs of PredBB aren't both no-successor
1387       // blocks.  If neither have successors and if PredBB is the second from
1388       // last block in the function, we'd just keep swapping the two blocks for
1389       // last.  Only do the swap if one is clearly better to fall through than
1390       // the other.
1391       if (FallThrough == --MF.end() &&
1392           !IsBetterFallthrough(PriorTBB, MBB))
1393         DoTransform = false;
1394 
1395       if (DoTransform) {
1396         // Reverse the branch so we will fall through on the previous true cond.
1397         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1398         if (!TII->reverseBranchCondition(NewPriorCond)) {
1399           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1400                        << "To make fallthrough to: " << *PriorTBB << "\n");
1401 
1402           DebugLoc dl = getBranchDebugLoc(PrevBB);
1403           TII->removeBranch(PrevBB);
1404           TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1405 
1406           // Move this block to the end of the function.
1407           MBB->moveAfter(&MF.back());
1408           MadeChange = true;
1409           ++NumBranchOpts;
1410           return MadeChange;
1411         }
1412       }
1413     }
1414   }
1415 
1416   // Analyze the branch in the current block.
1417   MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1418   SmallVector<MachineOperand, 4> CurCond;
1419   bool CurUnAnalyzable =
1420       TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1421   if (!CurUnAnalyzable) {
1422     // If the CFG for the prior block has extra edges, remove them.
1423     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1424 
1425     // If this is a two-way branch, and the FBB branches to this block, reverse
1426     // the condition so the single-basic-block loop is faster.  Instead of:
1427     //    Loop: xxx; jcc Out; jmp Loop
1428     // we want:
1429     //    Loop: xxx; jncc Loop; jmp Out
1430     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1431       SmallVector<MachineOperand, 4> NewCond(CurCond);
1432       if (!TII->reverseBranchCondition(NewCond)) {
1433         DebugLoc dl = getBranchDebugLoc(*MBB);
1434         TII->removeBranch(*MBB);
1435         TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1436         MadeChange = true;
1437         ++NumBranchOpts;
1438         goto ReoptimizeBlock;
1439       }
1440     }
1441 
1442     // If this branch is the only thing in its block, see if we can forward
1443     // other blocks across it.
1444     if (CurTBB && CurCond.empty() && !CurFBB &&
1445         IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
1446         !MBB->hasAddressTaken() && !MBB->isEHPad()) {
1447       DebugLoc dl = getBranchDebugLoc(*MBB);
1448       // This block may contain just an unconditional branch.  Because there can
1449       // be 'non-branch terminators' in the block, try removing the branch and
1450       // then seeing if the block is empty.
1451       TII->removeBranch(*MBB);
1452       // If the only things remaining in the block are debug info, remove these
1453       // as well, so this will behave the same as an empty block in non-debug
1454       // mode.
1455       if (IsEmptyBlock(MBB)) {
1456         // Make the block empty, losing the debug info (we could probably
1457         // improve this in some cases.)
1458         MBB->erase(MBB->begin(), MBB->end());
1459       }
1460       // If this block is just an unconditional branch to CurTBB, we can
1461       // usually completely eliminate the block.  The only case we cannot
1462       // completely eliminate the block is when the block before this one
1463       // falls through into MBB and we can't understand the prior block's branch
1464       // condition.
1465       if (MBB->empty()) {
1466         bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1467         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1468             !PrevBB.isSuccessor(MBB)) {
1469           // If the prior block falls through into us, turn it into an
1470           // explicit branch to us to make updates simpler.
1471           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1472               PriorTBB != MBB && PriorFBB != MBB) {
1473             if (!PriorTBB) {
1474               assert(PriorCond.empty() && !PriorFBB &&
1475                      "Bad branch analysis");
1476               PriorTBB = MBB;
1477             } else {
1478               assert(!PriorFBB && "Machine CFG out of date!");
1479               PriorFBB = MBB;
1480             }
1481             DebugLoc pdl = getBranchDebugLoc(PrevBB);
1482             TII->removeBranch(PrevBB);
1483             TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1484           }
1485 
1486           // Iterate through all the predecessors, revectoring each in-turn.
1487           size_t PI = 0;
1488           bool DidChange = false;
1489           bool HasBranchToSelf = false;
1490           while(PI != MBB->pred_size()) {
1491             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1492             if (PMBB == MBB) {
1493               // If this block has an uncond branch to itself, leave it.
1494               ++PI;
1495               HasBranchToSelf = true;
1496             } else {
1497               DidChange = true;
1498               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1499               // If this change resulted in PMBB ending in a conditional
1500               // branch where both conditions go to the same destination,
1501               // change this to an unconditional branch (and fix the CFG).
1502               MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1503               SmallVector<MachineOperand, 4> NewCurCond;
1504               bool NewCurUnAnalyzable = TII->analyzeBranch(
1505                   *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1506               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1507                 DebugLoc pdl = getBranchDebugLoc(*PMBB);
1508                 TII->removeBranch(*PMBB);
1509                 NewCurCond.clear();
1510                 TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1511                 MadeChange = true;
1512                 ++NumBranchOpts;
1513                 PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1514               }
1515             }
1516           }
1517 
1518           // Change any jumptables to go to the new MBB.
1519           if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1520             MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1521           if (DidChange) {
1522             ++NumBranchOpts;
1523             MadeChange = true;
1524             if (!HasBranchToSelf) return MadeChange;
1525           }
1526         }
1527       }
1528 
1529       // Add the branch back if the block is more than just an uncond branch.
1530       TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1531     }
1532   }
1533 
1534   // If the prior block doesn't fall through into this block, and if this
1535   // block doesn't fall through into some other block, see if we can find a
1536   // place to move this block where a fall-through will happen.
1537   if (!PrevBB.canFallThrough()) {
1538 
1539     // Now we know that there was no fall-through into this block, check to
1540     // see if it has a fall-through into its successor.
1541     bool CurFallsThru = MBB->canFallThrough();
1542 
1543     if (!MBB->isEHPad()) {
1544       // Check all the predecessors of this block.  If one of them has no fall
1545       // throughs, move this block right after it.
1546       for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1547         // Analyze the branch at the end of the pred.
1548         MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1549         SmallVector<MachineOperand, 4> PredCond;
1550         if (PredBB != MBB && !PredBB->canFallThrough() &&
1551             !TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true) &&
1552             (!CurFallsThru || !CurTBB || !CurFBB) &&
1553             (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1554           // If the current block doesn't fall through, just move it.
1555           // If the current block can fall through and does not end with a
1556           // conditional branch, we need to append an unconditional jump to
1557           // the (current) next block.  To avoid a possible compile-time
1558           // infinite loop, move blocks only backward in this case.
1559           // Also, if there are already 2 branches here, we cannot add a third;
1560           // this means we have the case
1561           // Bcc next
1562           // B elsewhere
1563           // next:
1564           if (CurFallsThru) {
1565             MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1566             CurCond.clear();
1567             TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1568           }
1569           MBB->moveAfter(PredBB);
1570           MadeChange = true;
1571           goto ReoptimizeBlock;
1572         }
1573       }
1574     }
1575 
1576     if (!CurFallsThru) {
1577       // Check all successors to see if we can move this block before it.
1578       for (MachineBasicBlock *SuccBB : MBB->successors()) {
1579         // Analyze the branch at the end of the block before the succ.
1580         MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1581 
1582         // If this block doesn't already fall-through to that successor, and if
1583         // the succ doesn't already have a block that can fall through into it,
1584         // and if the successor isn't an EH destination, we can arrange for the
1585         // fallthrough to happen.
1586         if (SuccBB != MBB && &*SuccPrev != MBB &&
1587             !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1588             !SuccBB->isEHPad()) {
1589           MBB->moveBefore(SuccBB);
1590           MadeChange = true;
1591           goto ReoptimizeBlock;
1592         }
1593       }
1594 
1595       // Okay, there is no really great place to put this block.  If, however,
1596       // the block before this one would be a fall-through if this block were
1597       // removed, move this block to the end of the function. There is no real
1598       // advantage in "falling through" to an EH block, so we don't want to
1599       // perform this transformation for that case.
1600       //
1601       // Also, Windows EH introduced the possibility of an arbitrary number of
1602       // successors to a given block.  The analyzeBranch call does not consider
1603       // exception handling and so we can get in a state where a block
1604       // containing a call is followed by multiple EH blocks that would be
1605       // rotated infinitely at the end of the function if the transformation
1606       // below were performed for EH "FallThrough" blocks.  Therefore, even if
1607       // that appears not to be happening anymore, we should assume that it is
1608       // possible and not remove the "!FallThrough()->isEHPad" condition below.
1609       MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1610       SmallVector<MachineOperand, 4> PrevCond;
1611       if (FallThrough != MF.end() &&
1612           !FallThrough->isEHPad() &&
1613           !TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
1614           PrevBB.isSuccessor(&*FallThrough)) {
1615         MBB->moveAfter(&MF.back());
1616         MadeChange = true;
1617         return MadeChange;
1618       }
1619     }
1620   }
1621 
1622   return MadeChange;
1623 }
1624 
1625 //===----------------------------------------------------------------------===//
1626 //  Hoist Common Code
1627 //===----------------------------------------------------------------------===//
1628 
1629 /// HoistCommonCode - Hoist common instruction sequences at the start of basic
1630 /// blocks to their common predecessor.
1631 bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1632   bool MadeChange = false;
1633   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1634     MachineBasicBlock *MBB = &*I++;
1635     MadeChange |= HoistCommonCodeInSuccs(MBB);
1636   }
1637 
1638   return MadeChange;
1639 }
1640 
1641 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1642 /// its 'true' successor.
1643 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1644                                          MachineBasicBlock *TrueBB) {
1645   for (MachineBasicBlock *SuccBB : BB->successors())
1646     if (SuccBB != TrueBB)
1647       return SuccBB;
1648   return nullptr;
1649 }
1650 
1651 template <class Container>
1652 static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1653                                 Container &Set) {
1654   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1655     for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1656       Set.insert(*AI);
1657   } else {
1658     Set.insert(Reg);
1659   }
1660 }
1661 
1662 /// findHoistingInsertPosAndDeps - Find the location to move common instructions
1663 /// in successors to. The location is usually just before the terminator,
1664 /// however if the terminator is a conditional branch and its previous
1665 /// instruction is the flag setting instruction, the previous instruction is
1666 /// the preferred location. This function also gathers uses and defs of the
1667 /// instructions from the insertion point to the end of the block. The data is
1668 /// used by HoistCommonCodeInSuccs to ensure safety.
1669 static
1670 MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1671                                                   const TargetInstrInfo *TII,
1672                                                   const TargetRegisterInfo *TRI,
1673                                                   SmallSet<unsigned,4> &Uses,
1674                                                   SmallSet<unsigned,4> &Defs) {
1675   MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1676   if (!TII->isUnpredicatedTerminator(*Loc))
1677     return MBB->end();
1678 
1679   for (const MachineOperand &MO : Loc->operands()) {
1680     if (!MO.isReg())
1681       continue;
1682     unsigned Reg = MO.getReg();
1683     if (!Reg)
1684       continue;
1685     if (MO.isUse()) {
1686       addRegAndItsAliases(Reg, TRI, Uses);
1687     } else {
1688       if (!MO.isDead())
1689         // Don't try to hoist code in the rare case the terminator defines a
1690         // register that is later used.
1691         return MBB->end();
1692 
1693       // If the terminator defines a register, make sure we don't hoist
1694       // the instruction whose def might be clobbered by the terminator.
1695       addRegAndItsAliases(Reg, TRI, Defs);
1696     }
1697   }
1698 
1699   if (Uses.empty())
1700     return Loc;
1701   if (Loc == MBB->begin())
1702     return MBB->end();
1703 
1704   // The terminator is probably a conditional branch, try not to separate the
1705   // branch from condition setting instruction.
1706   MachineBasicBlock::iterator PI =
1707     skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1708 
1709   bool IsDef = false;
1710   for (const MachineOperand &MO : PI->operands()) {
1711     // If PI has a regmask operand, it is probably a call. Separate away.
1712     if (MO.isRegMask())
1713       return Loc;
1714     if (!MO.isReg() || MO.isUse())
1715       continue;
1716     unsigned Reg = MO.getReg();
1717     if (!Reg)
1718       continue;
1719     if (Uses.count(Reg)) {
1720       IsDef = true;
1721       break;
1722     }
1723   }
1724   if (!IsDef)
1725     // The condition setting instruction is not just before the conditional
1726     // branch.
1727     return Loc;
1728 
1729   // Be conservative, don't insert instruction above something that may have
1730   // side-effects. And since it's potentially bad to separate flag setting
1731   // instruction from the conditional branch, just abort the optimization
1732   // completely.
1733   // Also avoid moving code above predicated instruction since it's hard to
1734   // reason about register liveness with predicated instruction.
1735   bool DontMoveAcrossStore = true;
1736   if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || TII->isPredicated(*PI))
1737     return MBB->end();
1738 
1739 
1740   // Find out what registers are live. Note this routine is ignoring other live
1741   // registers which are only used by instructions in successor blocks.
1742   for (const MachineOperand &MO : PI->operands()) {
1743     if (!MO.isReg())
1744       continue;
1745     unsigned Reg = MO.getReg();
1746     if (!Reg)
1747       continue;
1748     if (MO.isUse()) {
1749       addRegAndItsAliases(Reg, TRI, Uses);
1750     } else {
1751       if (Uses.erase(Reg)) {
1752         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1753           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1754             Uses.erase(*SubRegs); // Use sub-registers to be conservative
1755         }
1756       }
1757       addRegAndItsAliases(Reg, TRI, Defs);
1758     }
1759   }
1760 
1761   return PI;
1762 }
1763 
1764 /// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1765 /// sequence at the start of the function, move the instructions before MBB
1766 /// terminator if it's legal.
1767 bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1768   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1769   SmallVector<MachineOperand, 4> Cond;
1770   if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1771     return false;
1772 
1773   if (!FBB) FBB = findFalseBlock(MBB, TBB);
1774   if (!FBB)
1775     // Malformed bcc? True and false blocks are the same?
1776     return false;
1777 
1778   // Restrict the optimization to cases where MBB is the only predecessor,
1779   // it is an obvious win.
1780   if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1781     return false;
1782 
1783   // Find a suitable position to hoist the common instructions to. Also figure
1784   // out which registers are used or defined by instructions from the insertion
1785   // point to the end of the block.
1786   SmallSet<unsigned, 4> Uses, Defs;
1787   MachineBasicBlock::iterator Loc =
1788     findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1789   if (Loc == MBB->end())
1790     return false;
1791 
1792   bool HasDups = false;
1793   SmallVector<unsigned, 4> LocalDefs;
1794   SmallSet<unsigned, 4> LocalDefsSet;
1795   MachineBasicBlock::iterator TIB = TBB->begin();
1796   MachineBasicBlock::iterator FIB = FBB->begin();
1797   MachineBasicBlock::iterator TIE = TBB->end();
1798   MachineBasicBlock::iterator FIE = FBB->end();
1799   while (TIB != TIE && FIB != FIE) {
1800     // Skip dbg_value instructions. These do not count.
1801     TIB = skipDebugInstructionsForward(TIB, TIE);
1802     FIB = skipDebugInstructionsForward(FIB, FIE);
1803     if (TIB == TIE || FIB == FIE)
1804       break;
1805 
1806     if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1807       break;
1808 
1809     if (TII->isPredicated(*TIB))
1810       // Hard to reason about register liveness with predicated instruction.
1811       break;
1812 
1813     bool IsSafe = true;
1814     for (MachineOperand &MO : TIB->operands()) {
1815       // Don't attempt to hoist instructions with register masks.
1816       if (MO.isRegMask()) {
1817         IsSafe = false;
1818         break;
1819       }
1820       if (!MO.isReg())
1821         continue;
1822       unsigned Reg = MO.getReg();
1823       if (!Reg)
1824         continue;
1825       if (MO.isDef()) {
1826         if (Uses.count(Reg)) {
1827           // Avoid clobbering a register that's used by the instruction at
1828           // the point of insertion.
1829           IsSafe = false;
1830           break;
1831         }
1832 
1833         if (Defs.count(Reg) && !MO.isDead()) {
1834           // Don't hoist the instruction if the def would be clobber by the
1835           // instruction at the point insertion. FIXME: This is overly
1836           // conservative. It should be possible to hoist the instructions
1837           // in BB2 in the following example:
1838           // BB1:
1839           // r1, eflag = op1 r2, r3
1840           // brcc eflag
1841           //
1842           // BB2:
1843           // r1 = op2, ...
1844           //    = op3, r1<kill>
1845           IsSafe = false;
1846           break;
1847         }
1848       } else if (!LocalDefsSet.count(Reg)) {
1849         if (Defs.count(Reg)) {
1850           // Use is defined by the instruction at the point of insertion.
1851           IsSafe = false;
1852           break;
1853         }
1854 
1855         if (MO.isKill() && Uses.count(Reg))
1856           // Kills a register that's read by the instruction at the point of
1857           // insertion. Remove the kill marker.
1858           MO.setIsKill(false);
1859       }
1860     }
1861     if (!IsSafe)
1862       break;
1863 
1864     bool DontMoveAcrossStore = true;
1865     if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
1866       break;
1867 
1868     // Remove kills from LocalDefsSet, these registers had short live ranges.
1869     for (const MachineOperand &MO : TIB->operands()) {
1870       if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1871         continue;
1872       unsigned Reg = MO.getReg();
1873       if (!Reg || !LocalDefsSet.count(Reg))
1874         continue;
1875       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1876         for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1877           LocalDefsSet.erase(*AI);
1878       } else {
1879         LocalDefsSet.erase(Reg);
1880       }
1881     }
1882 
1883     // Track local defs so we can update liveins.
1884     for (const MachineOperand &MO : TIB->operands()) {
1885       if (!MO.isReg() || !MO.isDef() || MO.isDead())
1886         continue;
1887       unsigned Reg = MO.getReg();
1888       if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
1889         continue;
1890       LocalDefs.push_back(Reg);
1891       addRegAndItsAliases(Reg, TRI, LocalDefsSet);
1892     }
1893 
1894     HasDups = true;
1895     ++TIB;
1896     ++FIB;
1897   }
1898 
1899   if (!HasDups)
1900     return false;
1901 
1902   MBB->splice(Loc, TBB, TBB->begin(), TIB);
1903   FBB->erase(FBB->begin(), FIB);
1904 
1905   // Update livein's.
1906   bool AddedLiveIns = false;
1907   for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1908     unsigned Def = LocalDefs[i];
1909     if (LocalDefsSet.count(Def)) {
1910       TBB->addLiveIn(Def);
1911       FBB->addLiveIn(Def);
1912       AddedLiveIns = true;
1913     }
1914   }
1915 
1916   if (AddedLiveIns) {
1917     TBB->sortUniqueLiveIns();
1918     FBB->sortUniqueLiveIns();
1919   }
1920 
1921   ++NumHoist;
1922   return true;
1923 }
1924