1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
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 file implements the machine instruction level if-conversion pass, which
11 // tries to convert conditional branches into predicated instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/Passes.h"
16 #include "BranchFolding.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/ScopeExit.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/LivePhysRegs.h"
22 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetSchedule.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include <algorithm>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "ifcvt"
43 
44 // Hidden options for help debugging.
45 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
48 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
49                                    cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
51                                     cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
53                                      cl::init(false), cl::Hidden);
54 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
55                                       cl::init(false), cl::Hidden);
56 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
57                                       cl::init(false), cl::Hidden);
58 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
59                                        cl::init(false), cl::Hidden);
60 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
61                                     cl::init(false), cl::Hidden);
62 static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
63                                         cl::init(false), cl::Hidden);
64 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
65                                      cl::init(true), cl::Hidden);
66 
67 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
68 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
69 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
70 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
71 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
72 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
73 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
74 STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
75 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
76 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
77 STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
78 
79 namespace {
80   class IfConverter : public MachineFunctionPass {
81     enum IfcvtKind {
82       ICNotClassfied,  // BB data valid, but not classified.
83       ICSimpleFalse,   // Same as ICSimple, but on the false path.
84       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
85       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
86       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
87       ICTriangleFalse, // Same as ICTriangle, but on the false path.
88       ICTriangle,      // BB is entry of a triangle sub-CFG.
89       ICDiamond,       // BB is entry of a diamond sub-CFG.
90       ICForkedDiamond  // BB is entry of an almost diamond sub-CFG, with a
91                        // common tail that can be shared.
92     };
93 
94     /// One per MachineBasicBlock, this is used to cache the result
95     /// if-conversion feasibility analysis. This includes results from
96     /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
97     /// classification, and common tail block of its successors (if it's a
98     /// diamond shape), its size, whether it's predicable, and whether any
99     /// instruction can clobber the 'would-be' predicate.
100     ///
101     /// IsDone          - True if BB is not to be considered for ifcvt.
102     /// IsBeingAnalyzed - True if BB is currently being analyzed.
103     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
104     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
105     /// IsBrAnalyzable  - True if analyzeBranch() returns false.
106     /// HasFallThrough  - True if BB may fallthrough to the following BB.
107     /// IsUnpredicable  - True if BB is known to be unpredicable.
108     /// ClobbersPred    - True if BB could modify predicates (e.g. has
109     ///                   cmp, call, etc.)
110     /// NonPredSize     - Number of non-predicated instructions.
111     /// ExtraCost       - Extra cost for multi-cycle instructions.
112     /// ExtraCost2      - Some instructions are slower when predicated
113     /// BB              - Corresponding MachineBasicBlock.
114     /// TrueBB / FalseBB- See analyzeBranch().
115     /// BrCond          - Conditions for end of block conditional branches.
116     /// Predicate       - Predicate used in the BB.
117     struct BBInfo {
118       bool IsDone          : 1;
119       bool IsBeingAnalyzed : 1;
120       bool IsAnalyzed      : 1;
121       bool IsEnqueued      : 1;
122       bool IsBrAnalyzable  : 1;
123       bool IsBrReversible  : 1;
124       bool HasFallThrough  : 1;
125       bool IsUnpredicable  : 1;
126       bool CannotBeCopied  : 1;
127       bool ClobbersPred    : 1;
128       unsigned NonPredSize;
129       unsigned ExtraCost;
130       unsigned ExtraCost2;
131       MachineBasicBlock *BB;
132       MachineBasicBlock *TrueBB;
133       MachineBasicBlock *FalseBB;
134       SmallVector<MachineOperand, 4> BrCond;
135       SmallVector<MachineOperand, 4> Predicate;
136       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
137                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
138                  IsBrReversible(false), HasFallThrough(false),
139                  IsUnpredicable(false), CannotBeCopied(false),
140                  ClobbersPred(false), NonPredSize(0), ExtraCost(0),
141                  ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
142                  FalseBB(nullptr) {}
143     };
144 
145     /// Record information about pending if-conversions to attempt:
146     /// BBI             - Corresponding BBInfo.
147     /// Kind            - Type of block. See IfcvtKind.
148     /// NeedSubsumption - True if the to-be-predicated BB has already been
149     ///                   predicated.
150     /// NumDups      - Number of instructions that would be duplicated due
151     ///                   to this if-conversion. (For diamonds, the number of
152     ///                   identical instructions at the beginnings of both
153     ///                   paths).
154     /// NumDups2     - For diamonds, the number of identical instructions
155     ///                   at the ends of both paths.
156     struct IfcvtToken {
157       BBInfo &BBI;
158       IfcvtKind Kind;
159       unsigned NumDups;
160       unsigned NumDups2;
161       bool NeedSubsumption : 1;
162       bool TClobbersPred : 1;
163       bool FClobbersPred : 1;
164       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
165                  bool tc = false, bool fc = false)
166         : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
167           TClobbersPred(tc), FClobbersPred(fc) {}
168     };
169 
170     /// Results of if-conversion feasibility analysis indexed by basic block
171     /// number.
172     std::vector<BBInfo> BBAnalysis;
173     TargetSchedModel SchedModel;
174 
175     const TargetLoweringBase *TLI;
176     const TargetInstrInfo *TII;
177     const TargetRegisterInfo *TRI;
178     const MachineBranchProbabilityInfo *MBPI;
179     MachineRegisterInfo *MRI;
180 
181     LivePhysRegs Redefs;
182     LivePhysRegs DontKill;
183 
184     bool PreRegAlloc;
185     bool MadeChange;
186     int FnNum;
187     std::function<bool(const Function &)> PredicateFtor;
188 
189   public:
190     static char ID;
191     IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
192         : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
193       initializeIfConverterPass(*PassRegistry::getPassRegistry());
194     }
195 
196     void getAnalysisUsage(AnalysisUsage &AU) const override {
197       AU.addRequired<MachineBlockFrequencyInfo>();
198       AU.addRequired<MachineBranchProbabilityInfo>();
199       MachineFunctionPass::getAnalysisUsage(AU);
200     }
201 
202     bool runOnMachineFunction(MachineFunction &MF) override;
203 
204     MachineFunctionProperties getRequiredProperties() const override {
205       return MachineFunctionProperties().set(
206           MachineFunctionProperties::Property::NoVRegs);
207     }
208 
209   private:
210     bool ReverseBranchCondition(BBInfo &BBI) const;
211     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
212                      BranchProbability Prediction) const;
213     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
214                        bool FalseBranch, unsigned &Dups,
215                        BranchProbability Prediction) const;
216     bool CountDuplicatedInstructions(
217         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
218         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
219         unsigned &Dups1, unsigned &Dups2,
220         MachineBasicBlock &TBB, MachineBasicBlock &FBB,
221         bool SkipUnconditionalBranches) const;
222     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
223                       unsigned &Dups1, unsigned &Dups2,
224                       BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
225     bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
226                             unsigned &Dups1, unsigned &Dups2,
227                             BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
228     void AnalyzeBranches(BBInfo &BBI);
229     void ScanInstructions(BBInfo &BBI,
230                           MachineBasicBlock::iterator &Begin,
231                           MachineBasicBlock::iterator &End,
232                           bool BranchUnpredicable = false) const;
233     bool RescanInstructions(
234         MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
235         MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
236         BBInfo &TrueBBI, BBInfo &FalseBBI) const;
237     void AnalyzeBlock(MachineBasicBlock &MBB,
238                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
239     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
240                              bool isTriangle = false, bool RevBranch = false,
241                              bool hasCommonTail = false);
242     void AnalyzeBlocks(MachineFunction &MF,
243                        std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
244     void InvalidatePreds(MachineBasicBlock &MBB);
245     void RemoveExtraEdges(BBInfo &BBI);
246     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
247     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
248     bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
249                                 unsigned NumDups1, unsigned NumDups2,
250                                 bool TClobbersPred, bool FClobbersPred,
251                                 bool RemoveTrueBranch, bool RemoveFalseBranch,
252                                 bool MergeAddEdges);
253     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
254                           unsigned NumDups1, unsigned NumDups2,
255                           bool TClobbers, bool FClobbers);
256     bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
257                               unsigned NumDups1, unsigned NumDups2,
258                               bool TClobbers, bool FClobbers);
259     void PredicateBlock(BBInfo &BBI,
260                         MachineBasicBlock::iterator E,
261                         SmallVectorImpl<MachineOperand> &Cond,
262                         SmallSet<unsigned, 4> *LaterRedefs = nullptr);
263     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
264                                SmallVectorImpl<MachineOperand> &Cond,
265                                bool IgnoreBr = false);
266     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
267 
268     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
269                             unsigned Cycle, unsigned Extra,
270                             BranchProbability Prediction) const {
271       return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
272                                                    Prediction);
273     }
274 
275     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
276                             unsigned TCycle, unsigned TExtra,
277                             MachineBasicBlock &FBB,
278                             unsigned FCycle, unsigned FExtra,
279                             BranchProbability Prediction) const {
280       return TCycle > 0 && FCycle > 0 &&
281         TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
282                                  Prediction);
283     }
284 
285     /// Returns true if Block ends without a terminator.
286     bool blockAlwaysFallThrough(BBInfo &BBI) const {
287       return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
288     }
289 
290     /// Used to sort if-conversion candidates.
291     static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
292                               const std::unique_ptr<IfcvtToken> &C2) {
293       int Incr1 = (C1->Kind == ICDiamond)
294         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
295       int Incr2 = (C2->Kind == ICDiamond)
296         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
297       if (Incr1 > Incr2)
298         return true;
299       else if (Incr1 == Incr2) {
300         // Favors subsumption.
301         if (!C1->NeedSubsumption && C2->NeedSubsumption)
302           return true;
303         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
304           // Favors diamond over triangle, etc.
305           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
306             return true;
307           else if (C1->Kind == C2->Kind)
308             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
309         }
310       }
311       return false;
312     }
313   };
314 
315   char IfConverter::ID = 0;
316 }
317 
318 char &llvm::IfConverterID = IfConverter::ID;
319 
320 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
321 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
322 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
323 
324 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
325   if (skipFunction(*MF.getFunction()) ||
326       (PredicateFtor && !PredicateFtor(*MF.getFunction())))
327     return false;
328 
329   const TargetSubtargetInfo &ST = MF.getSubtarget();
330   TLI = ST.getTargetLowering();
331   TII = ST.getInstrInfo();
332   TRI = ST.getRegisterInfo();
333   BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
334   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
335   MRI = &MF.getRegInfo();
336   SchedModel.init(ST.getSchedModel(), &ST, TII);
337 
338   if (!TII) return false;
339 
340   PreRegAlloc = MRI->isSSA();
341 
342   bool BFChange = false;
343   if (!PreRegAlloc) {
344     // Tail merge tend to expose more if-conversion opportunities.
345     BranchFolder BF(true, false, MBFI, *MBPI);
346     BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
347                                    getAnalysisIfAvailable<MachineModuleInfo>());
348   }
349 
350   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
351                << MF.getName() << "\'");
352 
353   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
354     DEBUG(dbgs() << " skipped\n");
355     return false;
356   }
357   DEBUG(dbgs() << "\n");
358 
359   MF.RenumberBlocks();
360   BBAnalysis.resize(MF.getNumBlockIDs());
361 
362   std::vector<std::unique_ptr<IfcvtToken>> Tokens;
363   MadeChange = false;
364   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
365     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
366   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
367     // Do an initial analysis for each basic block and find all the potential
368     // candidates to perform if-conversion.
369     bool Change = false;
370     AnalyzeBlocks(MF, Tokens);
371     while (!Tokens.empty()) {
372       std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
373       Tokens.pop_back();
374       BBInfo &BBI = Token->BBI;
375       IfcvtKind Kind = Token->Kind;
376       unsigned NumDups = Token->NumDups;
377       unsigned NumDups2 = Token->NumDups2;
378 
379       // If the block has been evicted out of the queue or it has already been
380       // marked dead (due to it being predicated), then skip it.
381       if (BBI.IsDone)
382         BBI.IsEnqueued = false;
383       if (!BBI.IsEnqueued)
384         continue;
385 
386       BBI.IsEnqueued = false;
387 
388       bool RetVal = false;
389       switch (Kind) {
390       default: llvm_unreachable("Unexpected!");
391       case ICSimple:
392       case ICSimpleFalse: {
393         bool isFalse = Kind == ICSimpleFalse;
394         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
395         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
396                                             " false" : "")
397                      << "): BB#" << BBI.BB->getNumber() << " ("
398                      << ((Kind == ICSimpleFalse)
399                          ? BBI.FalseBB->getNumber()
400                          : BBI.TrueBB->getNumber()) << ") ");
401         RetVal = IfConvertSimple(BBI, Kind);
402         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
403         if (RetVal) {
404           if (isFalse) ++NumSimpleFalse;
405           else         ++NumSimple;
406         }
407        break;
408       }
409       case ICTriangle:
410       case ICTriangleRev:
411       case ICTriangleFalse:
412       case ICTriangleFRev: {
413         bool isFalse = Kind == ICTriangleFalse;
414         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
415         if (DisableTriangle && !isFalse && !isRev) break;
416         if (DisableTriangleR && !isFalse && isRev) break;
417         if (DisableTriangleF && isFalse && !isRev) break;
418         if (DisableTriangleFR && isFalse && isRev) break;
419         DEBUG(dbgs() << "Ifcvt (Triangle");
420         if (isFalse)
421           DEBUG(dbgs() << " false");
422         if (isRev)
423           DEBUG(dbgs() << " rev");
424         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
425                      << BBI.TrueBB->getNumber() << ",F:"
426                      << BBI.FalseBB->getNumber() << ") ");
427         RetVal = IfConvertTriangle(BBI, Kind);
428         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
429         if (RetVal) {
430           if (isFalse) {
431             if (isRev) ++NumTriangleFRev;
432             else       ++NumTriangleFalse;
433           } else {
434             if (isRev) ++NumTriangleRev;
435             else       ++NumTriangle;
436           }
437         }
438         break;
439       }
440       case ICDiamond: {
441         if (DisableDiamond) break;
442         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
443                      << BBI.TrueBB->getNumber() << ",F:"
444                      << BBI.FalseBB->getNumber() << ") ");
445         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
446                                   Token->TClobbersPred,
447                                   Token->FClobbersPred);
448         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
449         if (RetVal) ++NumDiamonds;
450         break;
451       }
452       case ICForkedDiamond: {
453         if (DisableForkedDiamond) break;
454         DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
455                      << BBI.BB->getNumber() << " (T:"
456                      << BBI.TrueBB->getNumber() << ",F:"
457                      << BBI.FalseBB->getNumber() << ") ");
458         RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
459                                       Token->TClobbersPred,
460                                       Token->FClobbersPred);
461         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
462         if (RetVal) ++NumForkedDiamonds;
463         break;
464       }
465       }
466 
467       Change |= RetVal;
468 
469       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
470         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
471       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
472         break;
473     }
474 
475     if (!Change)
476       break;
477     MadeChange |= Change;
478   }
479 
480   Tokens.clear();
481   BBAnalysis.clear();
482 
483   if (MadeChange && IfCvtBranchFold) {
484     BranchFolder BF(false, false, MBFI, *MBPI);
485     BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
486                         getAnalysisIfAvailable<MachineModuleInfo>());
487   }
488 
489   MadeChange |= BFChange;
490   return MadeChange;
491 }
492 
493 /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
494 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
495                                          MachineBasicBlock *TrueBB) {
496   for (MachineBasicBlock *SuccBB : BB->successors()) {
497     if (SuccBB != TrueBB)
498       return SuccBB;
499   }
500   return nullptr;
501 }
502 
503 /// Reverse the condition of the end of the block branch. Swap block's 'true'
504 /// and 'false' successors.
505 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
506   DebugLoc dl;  // FIXME: this is nowhere
507   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
508     TII->RemoveBranch(*BBI.BB);
509     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
510     std::swap(BBI.TrueBB, BBI.FalseBB);
511     return true;
512   }
513   return false;
514 }
515 
516 /// Returns the next block in the function blocks ordering. If it is the end,
517 /// returns NULL.
518 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
519   MachineFunction::iterator I = MBB.getIterator();
520   MachineFunction::iterator E = MBB.getParent()->end();
521   if (++I == E)
522     return nullptr;
523   return &*I;
524 }
525 
526 /// Returns true if the 'true' block (along with its predecessor) forms a valid
527 /// simple shape for ifcvt. It also returns the number of instructions that the
528 /// ifcvt would need to duplicate if performed in Dups.
529 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
530                               BranchProbability Prediction) const {
531   Dups = 0;
532   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
533     return false;
534 
535   if (TrueBBI.IsBrAnalyzable)
536     return false;
537 
538   if (TrueBBI.BB->pred_size() > 1) {
539     if (TrueBBI.CannotBeCopied ||
540         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
541                                         Prediction))
542       return false;
543     Dups = TrueBBI.NonPredSize;
544   }
545 
546   return true;
547 }
548 
549 /// Returns true if the 'true' and 'false' blocks (along with their common
550 /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
551 /// true, it checks if 'true' block's false branch branches to the 'false' block
552 /// rather than the other way around. It also returns the number of instructions
553 /// that the ifcvt would need to duplicate if performed in 'Dups'.
554 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
555                                 bool FalseBranch, unsigned &Dups,
556                                 BranchProbability Prediction) const {
557   Dups = 0;
558   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
559     return false;
560 
561   if (TrueBBI.BB->pred_size() > 1) {
562     if (TrueBBI.CannotBeCopied)
563       return false;
564 
565     unsigned Size = TrueBBI.NonPredSize;
566     if (TrueBBI.IsBrAnalyzable) {
567       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
568         // Ends with an unconditional branch. It will be removed.
569         --Size;
570       else {
571         MachineBasicBlock *FExit = FalseBranch
572           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
573         if (FExit)
574           // Require a conditional branch
575           ++Size;
576       }
577     }
578     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
579       return false;
580     Dups = Size;
581   }
582 
583   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
584   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
585     MachineFunction::iterator I = TrueBBI.BB->getIterator();
586     if (++I == TrueBBI.BB->getParent()->end())
587       return false;
588     TExit = &*I;
589   }
590   return TExit && TExit == FalseBBI.BB;
591 }
592 
593 /// Increment \p It until it points to a non-debug instruction or to \p End.
594 /// @param It Iterator to increment
595 /// @param End Iterator that points to end. Will be compared to It
596 /// @returns true if It == End, false otherwise.
597 static inline bool skipDebugInstructionsForward(
598     MachineBasicBlock::iterator &It,
599     MachineBasicBlock::iterator &End) {
600   while (It != End && It->isDebugValue())
601     It++;
602   return It == End;
603 }
604 
605 /// Shrink the provided inclusive range by one instruction.
606 /// If the range was one instruction (\p It == \p Begin), It is not modified,
607 /// but \p Empty is set to true.
608 static inline void shrinkInclusiveRange(
609     MachineBasicBlock::iterator &Begin,
610     MachineBasicBlock::iterator &It,
611     bool &Empty) {
612   if (It == Begin)
613     Empty = true;
614   else
615     It--;
616 }
617 
618 /// Decrement \p It until it points to a non-debug instruction or the range is
619 /// empty.
620 /// @param It Iterator to decrement.
621 /// @param Begin Iterator that points to beginning. Will be compared to It
622 /// @param Empty Set to true if the resulting range is Empty
623 /// @returns the value of Empty as a convenience.
624 static inline bool skipDebugInstructionsBackward(
625     MachineBasicBlock::iterator &Begin,
626     MachineBasicBlock::iterator &It,
627     bool &Empty) {
628   while (!Empty && It->isDebugValue())
629     shrinkInclusiveRange(Begin, It, Empty);
630   return Empty;
631 }
632 
633 /// Count duplicated instructions and move the iterators to show where they
634 /// are.
635 /// @param TIB True Iterator Begin
636 /// @param FIB False Iterator Begin
637 /// These two iterators initially point to the first instruction of the two
638 /// blocks, and finally point to the first non-shared instruction.
639 /// @param TIE True Iterator End
640 /// @param FIE False Iterator End
641 /// These two iterators initially point to End() for the two blocks() and
642 /// finally point to the first shared instruction in the tail.
643 /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
644 /// two blocks.
645 /// @param Dups1 count of duplicated instructions at the beginning of the 2
646 /// blocks.
647 /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
648 /// @param SkipUnconditionalBranches if true, Don't make sure that
649 /// unconditional branches at the end of the blocks are the same. True is
650 /// passed when the blocks are analyzable to allow for fallthrough to be
651 /// handled.
652 /// @return false if the shared portion prevents if conversion.
653 bool IfConverter::CountDuplicatedInstructions(
654     MachineBasicBlock::iterator &TIB,
655     MachineBasicBlock::iterator &FIB,
656     MachineBasicBlock::iterator &TIE,
657     MachineBasicBlock::iterator &FIE,
658     unsigned &Dups1, unsigned &Dups2,
659     MachineBasicBlock &TBB, MachineBasicBlock &FBB,
660     bool SkipUnconditionalBranches) const {
661 
662   while (TIB != TIE && FIB != FIE) {
663     // Skip dbg_value instructions. These do not count.
664     if(skipDebugInstructionsForward(TIB, TIE))
665       break;
666     if(skipDebugInstructionsForward(FIB, FIE))
667       break;
668     if (!TIB->isIdenticalTo(*FIB))
669       break;
670     // A pred-clobbering instruction in the shared portion prevents
671     // if-conversion.
672     std::vector<MachineOperand> PredDefs;
673     if (TII->DefinesPredicate(*TIB, PredDefs))
674       return false;
675     ++Dups1;
676     ++TIB;
677     ++FIB;
678   }
679 
680   // Check for already containing all of the block.
681   if (TIB == TIE || FIB == FIE)
682     return true;
683   // Now, in preparation for counting duplicate instructions at the ends of the
684   // blocks, move the end iterators up past any branch instructions.
685   --TIE;
686   --FIE;
687 
688   // After this point TIB and TIE define an inclusive range, which means that
689   // TIB == TIE is true when there is one more instruction to consider, not at
690   // the end. Because we may not be able to go before TIB, we need a flag to
691   // indicate a completely empty range.
692   bool TEmpty = false, FEmpty = false;
693 
694   // Upon exit TIE and FIE will both point at the last non-shared instruction.
695   // They need to be moved forward to point past the last non-shared
696   // instruction if the range they delimit is non-empty.
697   auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
698     if (!TEmpty)
699       ++TIE;
700     if (!FEmpty)
701       ++FIE;
702   });
703 
704   if (!TBB.succ_empty() || !FBB.succ_empty()) {
705     if (SkipUnconditionalBranches) {
706       while (!TEmpty && TIE->isUnconditionalBranch())
707         shrinkInclusiveRange(TIB, TIE, TEmpty);
708       while (!FEmpty && FIE->isUnconditionalBranch())
709         shrinkInclusiveRange(FIB, FIE, FEmpty);
710     }
711   }
712 
713   // If Dups1 includes all of a block, then don't count duplicate
714   // instructions at the end of the blocks.
715   if (TEmpty || FEmpty)
716     return true;
717 
718   // Count duplicate instructions at the ends of the blocks.
719   while (!TEmpty && !FEmpty) {
720     // Skip dbg_value instructions. These do not count.
721     if (skipDebugInstructionsBackward(TIB, TIE, TEmpty))
722       break;
723     if (skipDebugInstructionsBackward(FIB, FIE, FEmpty))
724       break;
725     if (!TIE->isIdenticalTo(*FIE))
726       break;
727     // We have to verify that any branch instructions are the same, and then we
728     // don't count them toward the # of duplicate instructions.
729     if (!TIE->isBranch())
730       ++Dups2;
731     shrinkInclusiveRange(TIB, TIE, TEmpty);
732     shrinkInclusiveRange(FIB, FIE, FEmpty);
733   }
734   return true;
735 }
736 
737 /// RescanInstructions - Run ScanInstructions on a pair of blocks.
738 /// @param TIB - True Iterator Begin, points to first non-shared instruction
739 /// @param FIB - False Iterator Begin, points to first non-shared instruction
740 /// @param TIE - True Iterator End, points past last non-shared instruction
741 /// @param FIE - False Iterator End, points past last non-shared instruction
742 /// @param TrueBBI  - BBInfo to update for the true block.
743 /// @param FalseBBI - BBInfo to update for the false block.
744 /// @returns - false if either block cannot be predicated or if both blocks end
745 ///   with a predicate-clobbering instruction.
746 bool IfConverter::RescanInstructions(
747     MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
748     MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
749     BBInfo &TrueBBI, BBInfo &FalseBBI) const {
750   bool BranchUnpredicable = true;
751   TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
752   ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
753   if (TrueBBI.IsUnpredicable)
754     return false;
755   ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
756   if (FalseBBI.IsUnpredicable)
757     return false;
758   if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
759     return false;
760   return true;
761 }
762 
763 /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
764 /// with their common predecessor) form a diamond if a common tail block is
765 /// extracted.
766 /// While not strictly a diamond, this pattern would form a diamond if
767 /// tail-merging had merged the shared tails.
768 ///           EBB
769 ///         _/   \_
770 ///         |     |
771 ///        TBB   FBB
772 ///        /  \ /   \
773 ///  FalseBB TrueBB FalseBB
774 /// Currently only handles analyzable branches.
775 /// Specifically excludes actual diamonds to avoid overlap.
776 bool IfConverter::ValidForkedDiamond(
777     BBInfo &TrueBBI, BBInfo &FalseBBI,
778     unsigned &Dups1, unsigned &Dups2,
779     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
780   Dups1 = Dups2 = 0;
781   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
782       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
783     return false;
784 
785   if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
786     return false;
787   // Don't IfConvert blocks that can't be folded into their predecessor.
788   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
789     return false;
790 
791   // This function is specifically looking for conditional tails, as
792   // unconditional tails are already handled by the standard diamond case.
793   if (TrueBBI.BrCond.size() == 0 ||
794       FalseBBI.BrCond.size() == 0)
795     return false;
796 
797   MachineBasicBlock *TT = TrueBBI.TrueBB;
798   MachineBasicBlock *TF = TrueBBI.FalseBB;
799   MachineBasicBlock *FT = FalseBBI.TrueBB;
800   MachineBasicBlock *FF = FalseBBI.FalseBB;
801 
802   if (!TT)
803     TT = getNextBlock(*TrueBBI.BB);
804   if (!TF)
805     TF = getNextBlock(*TrueBBI.BB);
806   if (!FT)
807     FT = getNextBlock(*FalseBBI.BB);
808   if (!FF)
809     FF = getNextBlock(*FalseBBI.BB);
810 
811   if (!TT || !TF)
812     return false;
813 
814   // Check successors. If they don't match, bail.
815   if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
816     return false;
817 
818   bool FalseReversed = false;
819   if (TF == FT && TT == FF) {
820     // If the branches are opposing, but we can't reverse, don't do it.
821     if (!FalseBBI.IsBrReversible)
822       return false;
823     FalseReversed = true;
824     ReverseBranchCondition(FalseBBI);
825   }
826   auto UnReverseOnExit = make_scope_exit([&]() {
827     if (FalseReversed)
828       ReverseBranchCondition(FalseBBI);
829   });
830 
831   // Count duplicate instructions at the beginning of the true and false blocks.
832   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
833   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
834   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
835   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
836   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
837                                   *TrueBBI.BB, *FalseBBI.BB,
838                                   /* SkipUnconditionalBranches */ true))
839     return false;
840 
841   TrueBBICalc.BB = TrueBBI.BB;
842   FalseBBICalc.BB = FalseBBI.BB;
843   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
844     return false;
845 
846   // The size is used to decide whether to if-convert, and the shared portions
847   // are subtracted off. Because of the subtraction, we just use the size that
848   // was calculated by the original ScanInstructions, as it is correct.
849   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
850   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
851   return true;
852 }
853 
854 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
855 /// with their common predecessor) forms a valid diamond shape for ifcvt.
856 bool IfConverter::ValidDiamond(
857     BBInfo &TrueBBI, BBInfo &FalseBBI,
858     unsigned &Dups1, unsigned &Dups2,
859     BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
860   Dups1 = Dups2 = 0;
861   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
862       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
863     return false;
864 
865   MachineBasicBlock *TT = TrueBBI.TrueBB;
866   MachineBasicBlock *FT = FalseBBI.TrueBB;
867 
868   if (!TT && blockAlwaysFallThrough(TrueBBI))
869     TT = getNextBlock(*TrueBBI.BB);
870   if (!FT && blockAlwaysFallThrough(FalseBBI))
871     FT = getNextBlock(*FalseBBI.BB);
872   if (TT != FT)
873     return false;
874   if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
875     return false;
876   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
877     return false;
878 
879   // FIXME: Allow true block to have an early exit?
880   if (TrueBBI.FalseBB || FalseBBI.FalseBB)
881     return false;
882 
883   // Count duplicate instructions at the beginning and end of the true and
884   // false blocks.
885   // Skip unconditional branches only if we are considering an analyzable
886   // diamond. Otherwise the branches must be the same.
887   bool SkipUnconditionalBranches =
888       TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
889   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
890   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
891   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
892   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
893   if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
894                                   *TrueBBI.BB, *FalseBBI.BB,
895                                   SkipUnconditionalBranches))
896     return false;
897 
898   TrueBBICalc.BB = TrueBBI.BB;
899   FalseBBICalc.BB = FalseBBI.BB;
900   if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
901     return false;
902   // The size is used to decide whether to if-convert, and the shared portions
903   // are subtracted off. Because of the subtraction, we just use the size that
904   // was calculated by the original ScanInstructions, as it is correct.
905   TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
906   FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
907   return true;
908 }
909 
910 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
911 /// the block is predicable.
912 void IfConverter::AnalyzeBranches(BBInfo &BBI) {
913   if (BBI.IsDone)
914     return;
915 
916   BBI.TrueBB = BBI.FalseBB = nullptr;
917   BBI.BrCond.clear();
918   BBI.IsBrAnalyzable =
919       !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
920   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
921   BBI.IsBrReversible = (RevCond.size() == 0) ||
922       !TII->ReverseBranchCondition(RevCond);
923   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
924 
925   if (BBI.BrCond.size()) {
926     // No false branch. This BB must end with a conditional branch and a
927     // fallthrough.
928     if (!BBI.FalseBB)
929       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
930     if (!BBI.FalseBB) {
931       // Malformed bcc? True and false blocks are the same?
932       BBI.IsUnpredicable = true;
933     }
934   }
935 }
936 
937 /// ScanInstructions - Scan all the instructions in the block to determine if
938 /// the block is predicable. In most cases, that means all the instructions
939 /// in the block are isPredicable(). Also checks if the block contains any
940 /// instruction which can clobber a predicate (e.g. condition code register).
941 /// If so, the block is not predicable unless it's the last instruction.
942 void IfConverter::ScanInstructions(BBInfo &BBI,
943                                    MachineBasicBlock::iterator &Begin,
944                                    MachineBasicBlock::iterator &End,
945                                    bool BranchUnpredicable) const {
946   if (BBI.IsDone || BBI.IsUnpredicable)
947     return;
948 
949   bool AlreadyPredicated = !BBI.Predicate.empty();
950 
951   BBI.NonPredSize = 0;
952   BBI.ExtraCost = 0;
953   BBI.ExtraCost2 = 0;
954   BBI.ClobbersPred = false;
955   for (MachineInstr &MI : make_range(Begin, End)) {
956     if (MI.isDebugValue())
957       continue;
958 
959     // It's unsafe to duplicate convergent instructions in this context, so set
960     // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
961     // following CFG, which is subject to our "simple" transformation.
962     //
963     //    BB0     // if (c1) goto BB1; else goto BB2;
964     //   /   \
965     //  BB1   |
966     //   |   BB2  // if (c2) goto TBB; else goto FBB;
967     //   |   / |
968     //   |  /  |
969     //   TBB   |
970     //    |    |
971     //    |   FBB
972     //    |
973     //    exit
974     //
975     // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
976     // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
977     // TBB contains a convergent instruction.  This is safe iff doing so does
978     // not add a control-flow dependency to the convergent instruction -- i.e.,
979     // it's safe iff the set of control flows that leads us to the convergent
980     // instruction does not get smaller after the transformation.
981     //
982     // Originally we executed TBB if c1 || c2.  After the transformation, there
983     // are two copies of TBB's instructions.  We get to the first if c1, and we
984     // get to the second if !c1 && c2.
985     //
986     // There are clearly fewer ways to satisfy the condition "c1" than
987     // "c1 || c2".  Since we've shrunk the set of control flows which lead to
988     // our convergent instruction, the transformation is unsafe.
989     if (MI.isNotDuplicable() || MI.isConvergent())
990       BBI.CannotBeCopied = true;
991 
992     bool isPredicated = TII->isPredicated(MI);
993     bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
994 
995     if (BranchUnpredicable && MI.isBranch()) {
996       BBI.IsUnpredicable = true;
997       return;
998     }
999 
1000     // A conditional branch is not predicable, but it may be eliminated.
1001     if (isCondBr)
1002       continue;
1003 
1004     if (!isPredicated) {
1005       BBI.NonPredSize++;
1006       unsigned ExtraPredCost = TII->getPredicationCost(MI);
1007       unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1008       if (NumCycles > 1)
1009         BBI.ExtraCost += NumCycles-1;
1010       BBI.ExtraCost2 += ExtraPredCost;
1011     } else if (!AlreadyPredicated) {
1012       // FIXME: This instruction is already predicated before the
1013       // if-conversion pass. It's probably something like a conditional move.
1014       // Mark this block unpredicable for now.
1015       BBI.IsUnpredicable = true;
1016       return;
1017     }
1018 
1019     if (BBI.ClobbersPred && !isPredicated) {
1020       // Predicate modification instruction should end the block (except for
1021       // already predicated instructions and end of block branches).
1022       // Predicate may have been modified, the subsequent (currently)
1023       // unpredicated instructions cannot be correctly predicated.
1024       BBI.IsUnpredicable = true;
1025       return;
1026     }
1027 
1028     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1029     // still potentially predicable.
1030     std::vector<MachineOperand> PredDefs;
1031     if (TII->DefinesPredicate(MI, PredDefs))
1032       BBI.ClobbersPred = true;
1033 
1034     if (!TII->isPredicable(MI)) {
1035       BBI.IsUnpredicable = true;
1036       return;
1037     }
1038   }
1039 }
1040 
1041 /// Determine if the block is a suitable candidate to be predicated by the
1042 /// specified predicate.
1043 /// @param BBI BBInfo for the block to check
1044 /// @param Pred Predicate array for the branch that leads to BBI
1045 /// @param isTriangle true if the Analysis is for a triangle
1046 /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1047 ///        case
1048 /// @param hasCommonTail true if BBI shares a tail with a sibling block that
1049 ///        contains any instruction that would make the block unpredicable.
1050 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1051                                       SmallVectorImpl<MachineOperand> &Pred,
1052                                       bool isTriangle, bool RevBranch,
1053                                       bool hasCommonTail) {
1054   // If the block is dead or unpredicable, then it cannot be predicated.
1055   // Two blocks may share a common unpredicable tail, but this doesn't prevent
1056   // them from being if-converted. The non-shared portion is assumed to have
1057   // been checked
1058   if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1059     return false;
1060 
1061   // If it is already predicated but we couldn't analyze its terminator, the
1062   // latter might fallthrough, but we can't determine where to.
1063   // Conservatively avoid if-converting again.
1064   if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1065     return false;
1066 
1067   // If it is already predicated, check if the new predicate subsumes
1068   // its predicate.
1069   if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1070     return false;
1071 
1072   if (!hasCommonTail && BBI.BrCond.size()) {
1073     if (!isTriangle)
1074       return false;
1075 
1076     // Test predicate subsumption.
1077     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1078     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1079     if (RevBranch) {
1080       if (TII->ReverseBranchCondition(Cond))
1081         return false;
1082     }
1083     if (TII->ReverseBranchCondition(RevPred) ||
1084         !TII->SubsumesPredicate(Cond, RevPred))
1085       return false;
1086   }
1087 
1088   return true;
1089 }
1090 
1091 /// Analyze the structure of the sub-CFG starting from the specified block.
1092 /// Record its successors and whether it looks like an if-conversion candidate.
1093 void IfConverter::AnalyzeBlock(
1094     MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1095   struct BBState {
1096     BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
1097     MachineBasicBlock *MBB;
1098 
1099     /// This flag is true if MBB's successors have been analyzed.
1100     bool SuccsAnalyzed;
1101   };
1102 
1103   // Push MBB to the stack.
1104   SmallVector<BBState, 16> BBStack(1, MBB);
1105 
1106   while (!BBStack.empty()) {
1107     BBState &State = BBStack.back();
1108     MachineBasicBlock *BB = State.MBB;
1109     BBInfo &BBI = BBAnalysis[BB->getNumber()];
1110 
1111     if (!State.SuccsAnalyzed) {
1112       if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1113         BBStack.pop_back();
1114         continue;
1115       }
1116 
1117       BBI.BB = BB;
1118       BBI.IsBeingAnalyzed = true;
1119 
1120       AnalyzeBranches(BBI);
1121       MachineBasicBlock::iterator Begin = BBI.BB->begin();
1122       MachineBasicBlock::iterator End = BBI.BB->end();
1123       ScanInstructions(BBI, Begin, End);
1124 
1125       // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1126       // not considered for ifcvt anymore.
1127       if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1128         BBI.IsBeingAnalyzed = false;
1129         BBI.IsAnalyzed = true;
1130         BBStack.pop_back();
1131         continue;
1132       }
1133 
1134       // Do not ifcvt if either path is a back edge to the entry block.
1135       if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1136         BBI.IsBeingAnalyzed = false;
1137         BBI.IsAnalyzed = true;
1138         BBStack.pop_back();
1139         continue;
1140       }
1141 
1142       // Do not ifcvt if true and false fallthrough blocks are the same.
1143       if (!BBI.FalseBB) {
1144         BBI.IsBeingAnalyzed = false;
1145         BBI.IsAnalyzed = true;
1146         BBStack.pop_back();
1147         continue;
1148       }
1149 
1150       // Push the False and True blocks to the stack.
1151       State.SuccsAnalyzed = true;
1152       BBStack.push_back(*BBI.FalseBB);
1153       BBStack.push_back(*BBI.TrueBB);
1154       continue;
1155     }
1156 
1157     BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1158     BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1159 
1160     if (TrueBBI.IsDone && FalseBBI.IsDone) {
1161       BBI.IsBeingAnalyzed = false;
1162       BBI.IsAnalyzed = true;
1163       BBStack.pop_back();
1164       continue;
1165     }
1166 
1167     SmallVector<MachineOperand, 4>
1168         RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1169     bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1170 
1171     unsigned Dups = 0;
1172     unsigned Dups2 = 0;
1173     bool TNeedSub = !TrueBBI.Predicate.empty();
1174     bool FNeedSub = !FalseBBI.Predicate.empty();
1175     bool Enqueued = false;
1176 
1177     BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1178 
1179     if (CanRevCond) {
1180       BBInfo TrueBBICalc, FalseBBICalc;
1181       auto feasibleDiamond = [&]() {
1182         bool MeetsSize = MeetIfcvtSizeLimit(
1183             *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1184                           TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1185             *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1186                            FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1187             Prediction);
1188         bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1189                                                 /* IsTriangle */ false, /* RevCond */ false,
1190                                                 /* hasCommonTail */ true);
1191         bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1192                                                  /* IsTriangle */ false, /* RevCond */ false,
1193                                                  /* hasCommonTail */ true);
1194         return MeetsSize && TrueFeasible && FalseFeasible;
1195       };
1196 
1197       if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1198                        TrueBBICalc, FalseBBICalc)) {
1199         if (feasibleDiamond()) {
1200           // Diamond:
1201           //   EBB
1202           //   / \_
1203           //  |   |
1204           // TBB FBB
1205           //   \ /
1206           //  TailBB
1207           // Note TailBB can be empty.
1208           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1209               BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1210               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1211           Enqueued = true;
1212         }
1213       } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1214                                     TrueBBICalc, FalseBBICalc)) {
1215         if (feasibleDiamond()) {
1216           // ForkedDiamond:
1217           // if TBB and FBB have a common tail that includes their conditional
1218           // branch instructions, then we can If Convert this pattern.
1219           //          EBB
1220           //         _/ \_
1221           //         |   |
1222           //        TBB  FBB
1223           //        / \ /   \
1224           //  FalseBB TrueBB FalseBB
1225           //
1226           Tokens.push_back(llvm::make_unique<IfcvtToken>(
1227               BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1228               (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1229           Enqueued = true;
1230         }
1231       }
1232     }
1233 
1234     if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1235         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1236                            TrueBBI.ExtraCost2, Prediction) &&
1237         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1238       // Triangle:
1239       //   EBB
1240       //   | \_
1241       //   |  |
1242       //   | TBB
1243       //   |  /
1244       //   FBB
1245       Tokens.push_back(
1246           llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1247       Enqueued = true;
1248     }
1249 
1250     if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1251         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1252                            TrueBBI.ExtraCost2, Prediction) &&
1253         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1254       Tokens.push_back(
1255           llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1256       Enqueued = true;
1257     }
1258 
1259     if (ValidSimple(TrueBBI, Dups, Prediction) &&
1260         MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1261                            TrueBBI.ExtraCost2, Prediction) &&
1262         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1263       // Simple (split, no rejoin):
1264       //   EBB
1265       //   | \_
1266       //   |  |
1267       //   | TBB---> exit
1268       //   |
1269       //   FBB
1270       Tokens.push_back(
1271           llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1272       Enqueued = true;
1273     }
1274 
1275     if (CanRevCond) {
1276       // Try the other path...
1277       if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1278                         Prediction.getCompl()) &&
1279           MeetIfcvtSizeLimit(*FalseBBI.BB,
1280                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1281                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1282           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1283         Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1284                                                        FNeedSub, Dups));
1285         Enqueued = true;
1286       }
1287 
1288       if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1289                         Prediction.getCompl()) &&
1290           MeetIfcvtSizeLimit(*FalseBBI.BB,
1291                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1292                            FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1293         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1294         Tokens.push_back(
1295             llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1296         Enqueued = true;
1297       }
1298 
1299       if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1300           MeetIfcvtSizeLimit(*FalseBBI.BB,
1301                              FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1302                              FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1303           FeasibilityAnalysis(FalseBBI, RevCond)) {
1304         Tokens.push_back(
1305             llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1306         Enqueued = true;
1307       }
1308     }
1309 
1310     BBI.IsEnqueued = Enqueued;
1311     BBI.IsBeingAnalyzed = false;
1312     BBI.IsAnalyzed = true;
1313     BBStack.pop_back();
1314   }
1315 }
1316 
1317 /// Analyze all blocks and find entries for all if-conversion candidates.
1318 void IfConverter::AnalyzeBlocks(
1319     MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1320   for (MachineBasicBlock &MBB : MF)
1321     AnalyzeBlock(MBB, Tokens);
1322 
1323   // Sort to favor more complex ifcvt scheme.
1324   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
1325 }
1326 
1327 /// Returns true either if ToMBB is the next block after MBB or that all the
1328 /// intervening blocks are empty (given MBB can fall through to its next block).
1329 static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1330   MachineFunction::iterator PI = MBB.getIterator();
1331   MachineFunction::iterator I = std::next(PI);
1332   MachineFunction::iterator TI = ToMBB.getIterator();
1333   MachineFunction::iterator E = MBB.getParent()->end();
1334   while (I != TI) {
1335     // Check isSuccessor to avoid case where the next block is empty, but
1336     // it's not a successor.
1337     if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1338       return false;
1339     PI = I++;
1340   }
1341   return true;
1342 }
1343 
1344 /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1345 /// can be if-converted. If predecessor is already enqueued, dequeue it!
1346 void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1347   for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1348     BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1349     if (PBBI.IsDone || PBBI.BB == &MBB)
1350       continue;
1351     PBBI.IsAnalyzed = false;
1352     PBBI.IsEnqueued = false;
1353   }
1354 }
1355 
1356 /// Inserts an unconditional branch from \p MBB to \p ToMBB.
1357 static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
1358                                const TargetInstrInfo *TII) {
1359   DebugLoc dl;  // FIXME: this is nowhere
1360   SmallVector<MachineOperand, 0> NoCond;
1361   TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1362 }
1363 
1364 /// Remove true / false edges if either / both are no longer successors.
1365 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
1366   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1367   SmallVector<MachineOperand, 4> Cond;
1368   if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
1369     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
1370 }
1371 
1372 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1373 /// values defined in MI which are also live/used by MI.
1374 static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1375   const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1376     ->getSubtarget().getRegisterInfo();
1377 
1378   // Before stepping forward past MI, remember which regs were live
1379   // before MI. This is needed to set the Undef flag only when reg is
1380   // dead.
1381   SparseSet<unsigned> LiveBeforeMI;
1382   LiveBeforeMI.setUniverse(TRI->getNumRegs());
1383   for (unsigned Reg : Redefs)
1384     LiveBeforeMI.insert(Reg);
1385 
1386   SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1387   Redefs.stepForward(MI, Clobbers);
1388 
1389   // Now add the implicit uses for each of the clobbered values.
1390   for (auto Clobber : Clobbers) {
1391     // FIXME: Const cast here is nasty, but better than making StepForward
1392     // take a mutable instruction instead of const.
1393     unsigned Reg = Clobber.first;
1394     MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1395     MachineInstr *OpMI = Op.getParent();
1396     MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1397     if (Op.isRegMask()) {
1398       // First handle regmasks.  They clobber any entries in the mask which
1399       // means that we need a def for those registers.
1400       if (LiveBeforeMI.count(Reg))
1401         MIB.addReg(Reg, RegState::Implicit);
1402 
1403       // We also need to add an implicit def of this register for the later
1404       // use to read from.
1405       // For the register allocator to have allocated a register clobbered
1406       // by the call which is used later, it must be the case that
1407       // the call doesn't return.
1408       MIB.addReg(Reg, RegState::Implicit | RegState::Define);
1409       continue;
1410     }
1411     assert(Op.isReg() && "Register operand required");
1412     if (Op.isDead()) {
1413       // If we found a dead def, but it needs to be live, then remove the dead
1414       // flag.
1415       if (Redefs.contains(Op.getReg()))
1416         Op.setIsDead(false);
1417     }
1418     if (LiveBeforeMI.count(Reg))
1419       MIB.addReg(Reg, RegState::Implicit);
1420   }
1421 }
1422 
1423 /// Remove kill flags from operands with a registers in the \p DontKill set.
1424 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
1425   for (MIBundleOperands O(MI); O.isValid(); ++O) {
1426     if (!O->isReg() || !O->isKill())
1427       continue;
1428     if (DontKill.contains(O->getReg()))
1429       O->setIsKill(false);
1430   }
1431 }
1432 
1433 /// Walks a range of machine instructions and removes kill flags for registers
1434 /// in the \p DontKill set.
1435 static void RemoveKills(MachineBasicBlock::iterator I,
1436                         MachineBasicBlock::iterator E,
1437                         const LivePhysRegs &DontKill,
1438                         const MCRegisterInfo &MCRI) {
1439   for (MachineInstr &MI : make_range(I, E))
1440     RemoveKills(MI, DontKill);
1441 }
1442 
1443 /// If convert a simple (split, no rejoin) sub-CFG.
1444 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1445   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1446   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1447   BBInfo *CvtBBI = &TrueBBI;
1448   BBInfo *NextBBI = &FalseBBI;
1449 
1450   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1451   if (Kind == ICSimpleFalse)
1452     std::swap(CvtBBI, NextBBI);
1453 
1454   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1455   MachineBasicBlock &NextMBB = *NextBBI->BB;
1456   if (CvtBBI->IsDone ||
1457       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1458     // Something has changed. It's no longer safe to predicate this block.
1459     BBI.IsAnalyzed = false;
1460     CvtBBI->IsAnalyzed = false;
1461     return false;
1462   }
1463 
1464   if (CvtMBB.hasAddressTaken())
1465     // Conservatively abort if-conversion if BB's address is taken.
1466     return false;
1467 
1468   if (Kind == ICSimpleFalse)
1469     if (TII->ReverseBranchCondition(Cond))
1470       llvm_unreachable("Unable to reverse branch condition!");
1471 
1472   // Initialize liveins to the first BB. These are potentiall redefined by
1473   // predicated instructions.
1474   Redefs.init(TRI);
1475   Redefs.addLiveIns(CvtMBB);
1476   Redefs.addLiveIns(NextMBB);
1477 
1478   // Compute a set of registers which must not be killed by instructions in
1479   // BB1: This is everything live-in to BB2.
1480   DontKill.init(TRI);
1481   DontKill.addLiveIns(NextMBB);
1482 
1483   if (CvtMBB.pred_size() > 1) {
1484     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1485     // Copy instructions in the true block, predicate them, and add them to
1486     // the entry block.
1487     CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1488 
1489     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1490     // explicitly remove CvtBBI as a successor.
1491     BBI.BB->removeSuccessor(&CvtMBB, true);
1492   } else {
1493     RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1494     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1495 
1496     // Merge converted block into entry block.
1497     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1498     MergeBlocks(BBI, *CvtBBI);
1499   }
1500 
1501   bool IterIfcvt = true;
1502   if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1503     InsertUncondBranch(*BBI.BB, NextMBB, TII);
1504     BBI.HasFallThrough = false;
1505     // Now ifcvt'd block will look like this:
1506     // BB:
1507     // ...
1508     // t, f = cmp
1509     // if t op
1510     // b BBf
1511     //
1512     // We cannot further ifcvt this block because the unconditional branch
1513     // will have to be predicated on the new condition, that will not be
1514     // available if cmp executes.
1515     IterIfcvt = false;
1516   }
1517 
1518   RemoveExtraEdges(BBI);
1519 
1520   // Update block info. BB can be iteratively if-converted.
1521   if (!IterIfcvt)
1522     BBI.IsDone = true;
1523   InvalidatePreds(*BBI.BB);
1524   CvtBBI->IsDone = true;
1525 
1526   // FIXME: Must maintain LiveIns.
1527   return true;
1528 }
1529 
1530 /// If convert a triangle sub-CFG.
1531 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1532   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1533   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1534   BBInfo *CvtBBI = &TrueBBI;
1535   BBInfo *NextBBI = &FalseBBI;
1536   DebugLoc dl;  // FIXME: this is nowhere
1537 
1538   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1539   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1540     std::swap(CvtBBI, NextBBI);
1541 
1542   MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1543   MachineBasicBlock &NextMBB = *NextBBI->BB;
1544   if (CvtBBI->IsDone ||
1545       (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1546     // Something has changed. It's no longer safe to predicate this block.
1547     BBI.IsAnalyzed = false;
1548     CvtBBI->IsAnalyzed = false;
1549     return false;
1550   }
1551 
1552   if (CvtMBB.hasAddressTaken())
1553     // Conservatively abort if-conversion if BB's address is taken.
1554     return false;
1555 
1556   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1557     if (TII->ReverseBranchCondition(Cond))
1558       llvm_unreachable("Unable to reverse branch condition!");
1559 
1560   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1561     if (ReverseBranchCondition(*CvtBBI)) {
1562       // BB has been changed, modify its predecessors (except for this
1563       // one) so they don't get ifcvt'ed based on bad intel.
1564       for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1565         if (PBB == BBI.BB)
1566           continue;
1567         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1568         if (PBBI.IsEnqueued) {
1569           PBBI.IsAnalyzed = false;
1570           PBBI.IsEnqueued = false;
1571         }
1572       }
1573     }
1574   }
1575 
1576   // Initialize liveins to the first BB. These are potentially redefined by
1577   // predicated instructions.
1578   Redefs.init(TRI);
1579   Redefs.addLiveIns(CvtMBB);
1580   Redefs.addLiveIns(NextMBB);
1581 
1582   DontKill.clear();
1583 
1584   bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1585   BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1586 
1587   if (HasEarlyExit) {
1588     // Get probabilities before modifying CvtMBB and BBI.BB.
1589     CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1590     CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1591     BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1592     BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1593   }
1594 
1595   if (CvtMBB.pred_size() > 1) {
1596     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1597     // Copy instructions in the true block, predicate them, and add them to
1598     // the entry block.
1599     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1600 
1601     // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1602     // explicitly remove CvtBBI as a successor.
1603     BBI.BB->removeSuccessor(&CvtMBB, true);
1604   } else {
1605     // Predicate the 'true' block after removing its branch.
1606     CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1607     PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1608 
1609     // Now merge the entry of the triangle with the true block.
1610     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1611     MergeBlocks(BBI, *CvtBBI, false);
1612   }
1613 
1614   // If 'true' block has a 'false' successor, add an exit branch to it.
1615   if (HasEarlyExit) {
1616     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1617                                            CvtBBI->BrCond.end());
1618     if (TII->ReverseBranchCondition(RevCond))
1619       llvm_unreachable("Unable to reverse branch condition!");
1620 
1621     // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1622     // NewNext = New_Prob(BBI.BB, NextMBB) =
1623     //   Prob(BBI.BB, NextMBB) +
1624     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1625     // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1626     //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1627     auto NewTrueBB = getNextBlock(*BBI.BB);
1628     auto NewNext = BBNext + BBCvt * CvtNext;
1629     auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1630     if (NewTrueBBIter != BBI.BB->succ_end())
1631       BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1632 
1633     auto NewFalse = BBCvt * CvtFalse;
1634     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1635     BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1636   }
1637 
1638   // Merge in the 'false' block if the 'false' block has no other
1639   // predecessors. Otherwise, add an unconditional branch to 'false'.
1640   bool FalseBBDead = false;
1641   bool IterIfcvt = true;
1642   bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1643   if (!isFallThrough) {
1644     // Only merge them if the true block does not fallthrough to the false
1645     // block. By not merging them, we make it possible to iteratively
1646     // ifcvt the blocks.
1647     if (!HasEarlyExit &&
1648         NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1649         !NextMBB.hasAddressTaken()) {
1650       MergeBlocks(BBI, *NextBBI);
1651       FalseBBDead = true;
1652     } else {
1653       InsertUncondBranch(*BBI.BB, NextMBB, TII);
1654       BBI.HasFallThrough = false;
1655     }
1656     // Mixed predicated and unpredicated code. This cannot be iteratively
1657     // predicated.
1658     IterIfcvt = false;
1659   }
1660 
1661   RemoveExtraEdges(BBI);
1662 
1663   // Update block info. BB can be iteratively if-converted.
1664   if (!IterIfcvt)
1665     BBI.IsDone = true;
1666   InvalidatePreds(*BBI.BB);
1667   CvtBBI->IsDone = true;
1668   if (FalseBBDead)
1669     NextBBI->IsDone = true;
1670 
1671   // FIXME: Must maintain LiveIns.
1672   return true;
1673 }
1674 
1675 /// Common code shared between diamond conversions.
1676 /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1677 /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1678 ///               and FalseBBI
1679 /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1680 ///               and \p FalseBBI
1681 /// \p RemoveTrueBranch - Remove the branch of the true block before predicating
1682 ///                       Only false for unanalyzable fallthrough cases.
1683 /// \p RemoveFalseBranch - Remove the branch of the false block before
1684 ///                        predicating Only false for unanalyzable fallthrough
1685 ///                        cases.
1686 /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1687 ///                    unanalyzable fallthrough
1688 bool IfConverter::IfConvertDiamondCommon(
1689     BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1690     unsigned NumDups1, unsigned NumDups2,
1691     bool TClobbersPred, bool FClobbersPred,
1692     bool RemoveTrueBranch, bool RemoveFalseBranch,
1693     bool MergeAddEdges) {
1694 
1695   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1696       TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1697     // Something has changed. It's no longer safe to predicate these blocks.
1698     BBI.IsAnalyzed = false;
1699     TrueBBI.IsAnalyzed = false;
1700     FalseBBI.IsAnalyzed = false;
1701     return false;
1702   }
1703 
1704   if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1705     // Conservatively abort if-conversion if either BB has its address taken.
1706     return false;
1707 
1708   // Put the predicated instructions from the 'true' block before the
1709   // instructions from the 'false' block, unless the true block would clobber
1710   // the predicate, in which case, do the opposite.
1711   BBInfo *BBI1 = &TrueBBI;
1712   BBInfo *BBI2 = &FalseBBI;
1713   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1714   if (TII->ReverseBranchCondition(RevCond))
1715     llvm_unreachable("Unable to reverse branch condition!");
1716   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1717   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1718 
1719   // Figure out the more profitable ordering.
1720   bool DoSwap = false;
1721   if (TClobbersPred && !FClobbersPred)
1722     DoSwap = true;
1723   else if (TClobbersPred == FClobbersPred) {
1724     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1725       DoSwap = true;
1726   }
1727   if (DoSwap) {
1728     std::swap(BBI1, BBI2);
1729     std::swap(Cond1, Cond2);
1730     std::swap(RemoveTrueBranch, RemoveFalseBranch);
1731   }
1732 
1733   // Remove the conditional branch from entry to the blocks.
1734   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1735 
1736   MachineBasicBlock &MBB1 = *BBI1->BB;
1737   MachineBasicBlock &MBB2 = *BBI2->BB;
1738 
1739   // Initialize the Redefs:
1740   // - BB2 live-in regs need implicit uses before being redefined by BB1
1741   //   instructions.
1742   // - BB1 live-out regs need implicit uses before being redefined by BB2
1743   //   instructions. We start with BB1 live-ins so we have the live-out regs
1744   //   after tracking the BB1 instructions.
1745   Redefs.init(TRI);
1746   Redefs.addLiveIns(MBB1);
1747   Redefs.addLiveIns(MBB2);
1748 
1749   // Remove the duplicated instructions at the beginnings of both paths.
1750   // Skip dbg_value instructions
1751   MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1752   MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
1753   BBI1->NonPredSize -= NumDups1;
1754   BBI2->NonPredSize -= NumDups1;
1755 
1756   // Skip past the dups on each side separately since there may be
1757   // differing dbg_value entries.
1758   for (unsigned i = 0; i < NumDups1; ++DI1) {
1759     if (!DI1->isDebugValue())
1760       ++i;
1761   }
1762   while (NumDups1 != 0) {
1763     ++DI2;
1764     if (!DI2->isDebugValue())
1765       --NumDups1;
1766   }
1767 
1768   // Compute a set of registers which must not be killed by instructions in BB1:
1769   // This is everything used+live in BB2 after the duplicated instructions. We
1770   // can compute this set by simulating liveness backwards from the end of BB2.
1771   DontKill.init(TRI);
1772   for (const MachineInstr &MI :
1773        make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
1774     DontKill.stepBackward(MI);
1775 
1776   for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1777     SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1778     Redefs.stepForward(MI, IgnoredClobbers);
1779   }
1780   BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1781   MBB2.erase(MBB2.begin(), DI2);
1782 
1783   if (RemoveTrueBranch)
1784     BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1785   // Remove duplicated instructions.
1786   DI1 = MBB1.end();
1787   for (unsigned i = 0; i != NumDups2; ) {
1788     // NumDups2 only counted non-dbg_value instructions, so this won't
1789     // run off the head of the list.
1790     assert(DI1 != MBB1.begin());
1791     --DI1;
1792     // skip dbg_value instructions
1793     if (!DI1->isDebugValue())
1794       ++i;
1795   }
1796   MBB1.erase(DI1, MBB1.end());
1797 
1798   // Kill flags in the true block for registers living into the false block
1799   // must be removed.
1800   RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
1801 
1802   // Remove 'false' block branch, and find the last instruction to predicate.
1803   // Save the debug location.
1804   if (RemoveFalseBranch)
1805     BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1806   DI2 = BBI2->BB->end();
1807   while (NumDups2 != 0) {
1808     // NumDups2 only counted non-dbg_value instructions, so this won't
1809     // run off the head of the list.
1810     assert(DI2 != MBB2.begin());
1811     --DI2;
1812     // skip dbg_value instructions
1813     if (!DI2->isDebugValue())
1814       --NumDups2;
1815   }
1816 
1817   // Remember which registers would later be defined by the false block.
1818   // This allows us not to predicate instructions in the true block that would
1819   // later be re-defined. That is, rather than
1820   //   subeq  r0, r1, #1
1821   //   addne  r0, r1, #1
1822   // generate:
1823   //   sub    r0, r1, #1
1824   //   addne  r0, r1, #1
1825   SmallSet<unsigned, 4> RedefsByFalse;
1826   SmallSet<unsigned, 4> ExtUses;
1827   if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1828     for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1829       if (FI.isDebugValue())
1830         continue;
1831       SmallVector<unsigned, 4> Defs;
1832       for (const MachineOperand &MO : FI.operands()) {
1833         if (!MO.isReg())
1834           continue;
1835         unsigned Reg = MO.getReg();
1836         if (!Reg)
1837           continue;
1838         if (MO.isDef()) {
1839           Defs.push_back(Reg);
1840         } else if (!RedefsByFalse.count(Reg)) {
1841           // These are defined before ctrl flow reach the 'false' instructions.
1842           // They cannot be modified by the 'true' instructions.
1843           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1844                SubRegs.isValid(); ++SubRegs)
1845             ExtUses.insert(*SubRegs);
1846         }
1847       }
1848 
1849       for (unsigned Reg : Defs) {
1850         if (!ExtUses.count(Reg)) {
1851           for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1852                SubRegs.isValid(); ++SubRegs)
1853             RedefsByFalse.insert(*SubRegs);
1854         }
1855       }
1856     }
1857   }
1858 
1859   // Predicate the 'true' block.
1860   PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1861 
1862   // After predicating BBI1, if there is a predicated terminator in BBI1 and
1863   // a non-predicated in BBI2, then we don't want to predicate the one from
1864   // BBI2. The reason is that if we merged these blocks, we would end up with
1865   // two predicated terminators in the same block.
1866   if (!MBB2.empty() && (DI2 == MBB2.end())) {
1867     MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1868     MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1869     if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1870         BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
1871       --DI2;
1872   }
1873 
1874   // Predicate the 'false' block.
1875   PredicateBlock(*BBI2, DI2, *Cond2);
1876 
1877   // Merge the true block into the entry of the diamond.
1878   MergeBlocks(BBI, *BBI1, MergeAddEdges);
1879   MergeBlocks(BBI, *BBI2, MergeAddEdges);
1880   return true;
1881 }
1882 
1883 /// If convert an almost-diamond sub-CFG where the true
1884 /// and false blocks share a common tail.
1885 bool IfConverter::IfConvertForkedDiamond(
1886     BBInfo &BBI, IfcvtKind Kind,
1887     unsigned NumDups1, unsigned NumDups2,
1888     bool TClobbersPred, bool FClobbersPred) {
1889   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1890   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1891 
1892   // Save the debug location for later.
1893   DebugLoc dl;
1894   MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1895   if (TIE != TrueBBI.BB->end())
1896     dl = TIE->getDebugLoc();
1897   // Removing branches from both blocks is safe, because we have already
1898   // determined that both blocks have the same branch instructions. The branch
1899   // will be added back at the end, unpredicated.
1900   if (!IfConvertDiamondCommon(
1901       BBI, TrueBBI, FalseBBI,
1902       NumDups1, NumDups2,
1903       TClobbersPred, FClobbersPred,
1904       /* RemoveTrueBranch */ true, /* RemoveFalseBranch */ true,
1905       /* MergeAddEdges */ true))
1906     return false;
1907 
1908   // Add back the branch.
1909   // Debug location saved above when removing the branch from BBI2
1910   TII->InsertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1911                     TrueBBI.BrCond, dl);
1912 
1913   RemoveExtraEdges(BBI);
1914 
1915   // Update block info.
1916   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1917   InvalidatePreds(*BBI.BB);
1918 
1919   // FIXME: Must maintain LiveIns.
1920   return true;
1921 }
1922 
1923 /// If convert a diamond sub-CFG.
1924 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1925                                    unsigned NumDups1, unsigned NumDups2,
1926                                    bool TClobbersPred, bool FClobbersPred) {
1927   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1928   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1929   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1930 
1931   // True block must fall through or end with an unanalyzable terminator.
1932   if (!TailBB) {
1933     if (blockAlwaysFallThrough(TrueBBI))
1934       TailBB = FalseBBI.TrueBB;
1935     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1936   }
1937 
1938   if (!IfConvertDiamondCommon(
1939       BBI, TrueBBI, FalseBBI,
1940       NumDups1, NumDups2,
1941       TrueBBI.ClobbersPred, FalseBBI.ClobbersPred,
1942       /* RemoveTrueBranch */ TrueBBI.IsBrAnalyzable,
1943       /* RemoveFalseBranch */ FalseBBI.IsBrAnalyzable,
1944       /* MergeAddEdges */ TailBB == nullptr))
1945     return false;
1946 
1947   // If the if-converted block falls through or unconditionally branches into
1948   // the tail block, and the tail block does not have other predecessors, then
1949   // fold the tail block in as well. Otherwise, unless it falls through to the
1950   // tail, add a unconditional branch to it.
1951   if (TailBB) {
1952     BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1953     bool CanMergeTail = !TailBBI.HasFallThrough &&
1954       !TailBBI.BB->hasAddressTaken();
1955     // The if-converted block can still have a predicated terminator
1956     // (e.g. a predicated return). If that is the case, we cannot merge
1957     // it with the tail block.
1958     MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1959     if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1960       CanMergeTail = false;
1961     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1962     // check if there are any other predecessors besides those.
1963     unsigned NumPreds = TailBB->pred_size();
1964     if (NumPreds > 1)
1965       CanMergeTail = false;
1966     else if (NumPreds == 1 && CanMergeTail) {
1967       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1968       if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
1969         CanMergeTail = false;
1970     }
1971     if (CanMergeTail) {
1972       MergeBlocks(BBI, TailBBI);
1973       TailBBI.IsDone = true;
1974     } else {
1975       BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1976       InsertUncondBranch(*BBI.BB, *TailBB, TII);
1977       BBI.HasFallThrough = false;
1978     }
1979   }
1980 
1981   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1982   // which can happen here if TailBB is unanalyzable and is merged, so
1983   // explicitly remove BBI1 and BBI2 as successors.
1984   BBI.BB->removeSuccessor(TrueBBI.BB);
1985   BBI.BB->removeSuccessor(FalseBBI.BB, /* NormalizeSuccessProbs */ true);
1986   RemoveExtraEdges(BBI);
1987 
1988   // Update block info.
1989   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1990   InvalidatePreds(*BBI.BB);
1991 
1992   // FIXME: Must maintain LiveIns.
1993   return true;
1994 }
1995 
1996 static bool MaySpeculate(const MachineInstr &MI,
1997                          SmallSet<unsigned, 4> &LaterRedefs) {
1998   bool SawStore = true;
1999   if (!MI.isSafeToMove(nullptr, SawStore))
2000     return false;
2001 
2002   for (const MachineOperand &MO : MI.operands()) {
2003     if (!MO.isReg())
2004       continue;
2005     unsigned Reg = MO.getReg();
2006     if (!Reg)
2007       continue;
2008     if (MO.isDef() && !LaterRedefs.count(Reg))
2009       return false;
2010   }
2011 
2012   return true;
2013 }
2014 
2015 /// Predicate instructions from the start of the block to the specified end with
2016 /// the specified condition.
2017 void IfConverter::PredicateBlock(BBInfo &BBI,
2018                                  MachineBasicBlock::iterator E,
2019                                  SmallVectorImpl<MachineOperand> &Cond,
2020                                  SmallSet<unsigned, 4> *LaterRedefs) {
2021   bool AnyUnpred = false;
2022   bool MaySpec = LaterRedefs != nullptr;
2023   for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2024     if (I.isDebugValue() || TII->isPredicated(I))
2025       continue;
2026     // It may be possible not to predicate an instruction if it's the 'true'
2027     // side of a diamond and the 'false' side may re-define the instruction's
2028     // defs.
2029     if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
2030       AnyUnpred = true;
2031       continue;
2032     }
2033     // If any instruction is predicated, then every instruction after it must
2034     // be predicated.
2035     MaySpec = false;
2036     if (!TII->PredicateInstruction(I, Cond)) {
2037 #ifndef NDEBUG
2038       dbgs() << "Unable to predicate " << I << "!\n";
2039 #endif
2040       llvm_unreachable(nullptr);
2041     }
2042 
2043     // If the predicated instruction now redefines a register as the result of
2044     // if-conversion, add an implicit kill.
2045     UpdatePredRedefs(I, Redefs);
2046   }
2047 
2048   BBI.Predicate.append(Cond.begin(), Cond.end());
2049 
2050   BBI.IsAnalyzed = false;
2051   BBI.NonPredSize = 0;
2052 
2053   ++NumIfConvBBs;
2054   if (AnyUnpred)
2055     ++NumUnpred;
2056 }
2057 
2058 /// Copy and predicate instructions from source BB to the destination block.
2059 /// Skip end of block branches if IgnoreBr is true.
2060 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2061                                         SmallVectorImpl<MachineOperand> &Cond,
2062                                         bool IgnoreBr) {
2063   MachineFunction &MF = *ToBBI.BB->getParent();
2064 
2065   MachineBasicBlock &FromMBB = *FromBBI.BB;
2066   for (MachineInstr &I : FromMBB) {
2067     // Do not copy the end of the block branches.
2068     if (IgnoreBr && I.isBranch())
2069       break;
2070 
2071     MachineInstr *MI = MF.CloneMachineInstr(&I);
2072     ToBBI.BB->insert(ToBBI.BB->end(), MI);
2073     ToBBI.NonPredSize++;
2074     unsigned ExtraPredCost = TII->getPredicationCost(I);
2075     unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2076     if (NumCycles > 1)
2077       ToBBI.ExtraCost += NumCycles-1;
2078     ToBBI.ExtraCost2 += ExtraPredCost;
2079 
2080     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
2081       if (!TII->PredicateInstruction(*MI, Cond)) {
2082 #ifndef NDEBUG
2083         dbgs() << "Unable to predicate " << I << "!\n";
2084 #endif
2085         llvm_unreachable(nullptr);
2086       }
2087     }
2088 
2089     // If the predicated instruction now redefines a register as the result of
2090     // if-conversion, add an implicit kill.
2091     UpdatePredRedefs(*MI, Redefs);
2092 
2093     // Some kill flags may not be correct anymore.
2094     if (!DontKill.empty())
2095       RemoveKills(*MI, DontKill);
2096   }
2097 
2098   if (!IgnoreBr) {
2099     std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2100                                            FromMBB.succ_end());
2101     MachineBasicBlock *NBB = getNextBlock(FromMBB);
2102     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2103 
2104     for (MachineBasicBlock *Succ : Succs) {
2105       // Fallthrough edge can't be transferred.
2106       if (Succ == FallThrough)
2107         continue;
2108       ToBBI.BB->addSuccessor(Succ);
2109     }
2110   }
2111 
2112   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2113   ToBBI.Predicate.append(Cond.begin(), Cond.end());
2114 
2115   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2116   ToBBI.IsAnalyzed = false;
2117 
2118   ++NumDupBBs;
2119 }
2120 
2121 /// Move all instructions from FromBB to the end of ToBB.  This will leave
2122 /// FromBB as an empty block, so remove all of its successor edges except for
2123 /// the fall-through edge.  If AddEdges is true, i.e., when FromBBI's branch is
2124 /// being moved, add those successor edges to ToBBI.
2125 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2126   MachineBasicBlock &FromMBB = *FromBBI.BB;
2127   assert(!FromMBB.hasAddressTaken() &&
2128          "Removing a BB whose address is taken!");
2129 
2130   // In case FromMBB contains terminators (e.g. return instruction),
2131   // first move the non-terminator instructions, then the terminators.
2132   MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
2133   MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2134   ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2135 
2136   // If FromBB has non-predicated terminator we should copy it at the end.
2137   if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
2138     ToTI = ToBBI.BB->end();
2139   ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2140 
2141   // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2142   // unknown probabilities into known ones.
2143   // FIXME: This usage is too tricky and in the future we would like to
2144   // eliminate all unknown probabilities in MBB.
2145   ToBBI.BB->normalizeSuccProbs();
2146 
2147   SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2148                                                 FromMBB.succ_end());
2149   MachineBasicBlock *NBB = getNextBlock(FromMBB);
2150   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2151   // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2152   // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2153   auto To2FromProb = BranchProbability::getZero();
2154   if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2155     To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2156     // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
2157     // edge probability being merged to other edges when this edge is removed
2158     // later.
2159     ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
2160                                  BranchProbability::getZero());
2161   }
2162 
2163   for (MachineBasicBlock *Succ : FromSuccs) {
2164     // Fallthrough edge can't be transferred.
2165     if (Succ == FallThrough)
2166       continue;
2167 
2168     auto NewProb = BranchProbability::getZero();
2169     if (AddEdges) {
2170       // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2171       // which is a portion of the edge probability from FromMBB to Succ. The
2172       // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2173       // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
2174       NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2175 
2176       // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2177       // only happens when if-converting a diamond CFG and FromMBB is the
2178       // tail BB.  In this case FromMBB post-dominates ToBBI.BB and hence we
2179       // could just use the probabilities on FromMBB's out-edges when adding
2180       // new successors.
2181       if (!To2FromProb.isZero())
2182         NewProb *= To2FromProb;
2183     }
2184 
2185     FromMBB.removeSuccessor(Succ);
2186 
2187     if (AddEdges) {
2188       // If the edge from ToBBI.BB to Succ already exists, update the
2189       // probability of this edge by adding NewProb to it. An example is shown
2190       // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2191       // don't have to set C as A's successor as it already is. We only need to
2192       // update the edge probability on A->C. Note that B will not be
2193       // immediately removed from A's successors. It is possible that B->D is
2194       // not removed either if D is a fallthrough of B. Later the edge A->D
2195       // (generated here) and B->D will be combined into one edge. To maintain
2196       // correct edge probability of this combined edge, we need to set the edge
2197       // probability of A->B to zero, which is already done above. The edge
2198       // probability on A->D is calculated by scaling the original probability
2199       // on A->B by the probability of B->D.
2200       //
2201       // Before ifcvt:      After ifcvt (assume B->D is kept):
2202       //
2203       //       A                A
2204       //      /|               /|\
2205       //     / B              / B|
2206       //    | /|             |  ||
2207       //    |/ |             |  |/
2208       //    C  D             C  D
2209       //
2210       if (ToBBI.BB->isSuccessor(Succ))
2211         ToBBI.BB->setSuccProbability(
2212             find(ToBBI.BB->successors(), Succ),
2213             MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2214       else
2215         ToBBI.BB->addSuccessor(Succ, NewProb);
2216     }
2217   }
2218 
2219   // Now FromBBI always falls through to the next block!
2220   if (NBB && !FromMBB.isSuccessor(NBB))
2221     FromMBB.addSuccessor(NBB);
2222 
2223   // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2224   // we've done above.
2225   ToBBI.BB->normalizeSuccProbs();
2226 
2227   ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2228   FromBBI.Predicate.clear();
2229 
2230   ToBBI.NonPredSize += FromBBI.NonPredSize;
2231   ToBBI.ExtraCost += FromBBI.ExtraCost;
2232   ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2233   FromBBI.NonPredSize = 0;
2234   FromBBI.ExtraCost = 0;
2235   FromBBI.ExtraCost2 = 0;
2236 
2237   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2238   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2239   ToBBI.IsAnalyzed = false;
2240   FromBBI.IsAnalyzed = false;
2241 }
2242 
2243 FunctionPass *
2244 llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
2245   return new IfConverter(std::move(Ftor));
2246 }
2247