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