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