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