OSDN Git Service

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