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