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