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