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