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