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