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