Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/IfConversion.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- IfConversion.cpp - Machine code if conversion pass -----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the machine instruction level if-conversion pass, which
10
// tries to convert conditional branches into predicated instructions.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "BranchFolding.h"
15
#include "llvm/ADT/STLExtras.h"
16
#include "llvm/ADT/ScopeExit.h"
17
#include "llvm/ADT/SmallSet.h"
18
#include "llvm/ADT/SmallVector.h"
19
#include "llvm/ADT/SparseSet.h"
20
#include "llvm/ADT/Statistic.h"
21
#include "llvm/ADT/iterator_range.h"
22
#include "llvm/CodeGen/LivePhysRegs.h"
23
#include "llvm/CodeGen/MachineBasicBlock.h"
24
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
26
#include "llvm/CodeGen/MachineFunction.h"
27
#include "llvm/CodeGen/MachineFunctionPass.h"
28
#include "llvm/CodeGen/MachineInstr.h"
29
#include "llvm/CodeGen/MachineInstrBuilder.h"
30
#include "llvm/CodeGen/MachineModuleInfo.h"
31
#include "llvm/CodeGen/MachineOperand.h"
32
#include "llvm/CodeGen/MachineRegisterInfo.h"
33
#include "llvm/CodeGen/TargetInstrInfo.h"
34
#include "llvm/CodeGen/TargetLowering.h"
35
#include "llvm/CodeGen/TargetRegisterInfo.h"
36
#include "llvm/CodeGen/TargetSchedule.h"
37
#include "llvm/CodeGen/TargetSubtargetInfo.h"
38
#include "llvm/IR/DebugLoc.h"
39
#include "llvm/MC/MCRegisterInfo.h"
40
#include "llvm/Pass.h"
41
#include "llvm/Support/BranchProbability.h"
42
#include "llvm/Support/CommandLine.h"
43
#include "llvm/Support/Debug.h"
44
#include "llvm/Support/ErrorHandling.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <algorithm>
47
#include <cassert>
48
#include <functional>
49
#include <iterator>
50
#include <memory>
51
#include <utility>
52
#include <vector>
53
54
using namespace llvm;
55
56
#define DEBUG_TYPE "if-converter"
57
58
// Hidden options for help debugging.
59
static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
60
static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
61
static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
62
static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
63
                                   cl::init(false), cl::Hidden);
64
static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
65
                                    cl::init(false), cl::Hidden);
66
static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
67
                                     cl::init(false), cl::Hidden);
68
static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
69
                                      cl::init(false), cl::Hidden);
70
static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
71
                                      cl::init(false), cl::Hidden);
72
static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
73
                                       cl::init(false), cl::Hidden);
74
static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
75
                                    cl::init(false), cl::Hidden);
76
static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
77
                                        cl::init(false), cl::Hidden);
78
static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
79
                                     cl::init(true), cl::Hidden);
80
81
STATISTIC(NumSimple,       "Number of simple if-conversions performed");
82
STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
83
STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
84
STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
85
STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
86
STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
87
STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
88
STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
89
STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
90
STATISTIC(NumDupBBs,       "Number of duplicated blocks");
91
STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated");
92
93
namespace {
94
95
  class IfConverter : public MachineFunctionPass {
96
    enum IfcvtKind {
97
      ICNotClassfied,  // BB data valid, but not classified.
98
      ICSimpleFalse,   // Same as ICSimple, but on the false path.
99
      ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
100
      ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
101
      ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
102
      ICTriangleFalse, // Same as ICTriangle, but on the false path.
103
      ICTriangle,      // BB is entry of a triangle sub-CFG.
104
      ICDiamond,       // BB is entry of a diamond sub-CFG.
105
      ICForkedDiamond  // BB is entry of an almost diamond sub-CFG, with a
106
                       // common tail that can be shared.
107
    };
108
109
    /// One per MachineBasicBlock, this is used to cache the result
110
    /// if-conversion feasibility analysis. This includes results from
111
    /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
112
    /// classification, and common tail block of its successors (if it's a
113
    /// diamond shape), its size, whether it's predicable, and whether any
114
    /// instruction can clobber the 'would-be' predicate.
115
    ///
116
    /// IsDone          - True if BB is not to be considered for ifcvt.
117
    /// IsBeingAnalyzed - True if BB is currently being analyzed.
118
    /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
119
    /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
120
    /// IsBrAnalyzable  - True if analyzeBranch() returns false.
121
    /// HasFallThrough  - True if BB may fallthrough to the following BB.
122
    /// IsUnpredicable  - True if BB is known to be unpredicable.
123
    /// ClobbersPred    - True if BB could modify predicates (e.g. has
124
    ///                   cmp, call, etc.)
125
    /// NonPredSize     - Number of non-predicated instructions.
126
    /// ExtraCost       - Extra cost for multi-cycle instructions.
127
    /// ExtraCost2      - Some instructions are slower when predicated
128
    /// BB              - Corresponding MachineBasicBlock.
129
    /// TrueBB / FalseBB- See analyzeBranch().
130
    /// BrCond          - Conditions for end of block conditional branches.
131
    /// Predicate       - Predicate used in the BB.
132
    struct BBInfo {
133
      bool IsDone          : 1;
134
      bool IsBeingAnalyzed : 1;
135
      bool IsAnalyzed      : 1;
136
      bool IsEnqueued      : 1;
137
      bool IsBrAnalyzable  : 1;
138
      bool IsBrReversible  : 1;
139
      bool HasFallThrough  : 1;
140
      bool IsUnpredicable  : 1;
141
      bool CannotBeCopied  : 1;
142
      bool ClobbersPred    : 1;
143
      unsigned NonPredSize = 0;
144
      unsigned ExtraCost = 0;
145
      unsigned ExtraCost2 = 0;
146
      MachineBasicBlock *BB = nullptr;
147
      MachineBasicBlock *TrueBB = nullptr;
148
      MachineBasicBlock *FalseBB = nullptr;
149
      SmallVector<MachineOperand, 4> BrCond;
150
      SmallVector<MachineOperand, 4> Predicate;
151
152
      BBInfo() : IsDone(false), IsBeingAnalyzed(false),
153
                 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
154
                 IsBrReversible(false), HasFallThrough(false),
155
                 IsUnpredicable(false), CannotBeCopied(false),
156
246k
                 ClobbersPred(false) {}
157
    };
158
159
    /// Record information about pending if-conversions to attempt:
160
    /// BBI             - Corresponding BBInfo.
161
    /// Kind            - Type of block. See IfcvtKind.
162
    /// NeedSubsumption - True if the to-be-predicated BB has already been
163
    ///                   predicated.
164
    /// NumDups      - Number of instructions that would be duplicated due
165
    ///                   to this if-conversion. (For diamonds, the number of
166
    ///                   identical instructions at the beginnings of both
167
    ///                   paths).
168
    /// NumDups2     - For diamonds, the number of identical instructions
169
    ///                   at the ends of both paths.
170
    struct IfcvtToken {
171
      BBInfo &BBI;
172
      IfcvtKind Kind;
173
      unsigned NumDups;
174
      unsigned NumDups2;
175
      bool NeedSubsumption : 1;
176
      bool TClobbersPred : 1;
177
      bool FClobbersPred : 1;
178
179
      IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
180
                 bool tc = false, bool fc = false)
181
        : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
182
8.82k
          TClobbersPred(tc), FClobbersPred(fc) {}
183
    };
184
185
    /// Results of if-conversion feasibility analysis indexed by basic block
186
    /// number.
187
    std::vector<BBInfo> BBAnalysis;
188
    TargetSchedModel SchedModel;
189
190
    const TargetLoweringBase *TLI;
191
    const TargetInstrInfo *TII;
192
    const TargetRegisterInfo *TRI;
193
    const MachineBranchProbabilityInfo *MBPI;
194
    MachineRegisterInfo *MRI;
195
196
    LivePhysRegs Redefs;
197
198
    bool PreRegAlloc;
199
    bool MadeChange;
200
    int FnNum = -1;
201
    std::function<bool(const MachineFunction &)> PredicateFtor;
202
203
  public:
204
    static char ID;
205
206
    IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
207
8.74k
        : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
208
8.74k
      initializeIfConverterPass(*PassRegistry::getPassRegistry());
209
8.74k
    }
210
211
8.67k
    void getAnalysisUsage(AnalysisUsage &AU) const override {
212
8.67k
      AU.addRequired<MachineBlockFrequencyInfo>();
213
8.67k
      AU.addRequired<MachineBranchProbabilityInfo>();
214
8.67k
      MachineFunctionPass::getAnalysisUsage(AU);
215
8.67k
    }
216
217
    bool runOnMachineFunction(MachineFunction &MF) override;
218
219
8.67k
    MachineFunctionProperties getRequiredProperties() const override {
220
8.67k
      return MachineFunctionProperties().set(
221
8.67k
          MachineFunctionProperties::Property::NoVRegs);
222
8.67k
    }
223
224
  private:
225
    bool reverseBranchCondition(BBInfo &BBI) const;
226
    bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
227
                     BranchProbability Prediction) const;
228
    bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
229
                       bool FalseBranch, unsigned &Dups,
230
                       BranchProbability Prediction) const;
231
    bool CountDuplicatedInstructions(
232
        MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
233
        MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
234
        unsigned &Dups1, unsigned &Dups2,
235
        MachineBasicBlock &TBB, MachineBasicBlock &FBB,
236
        bool SkipUnconditionalBranches) const;
237
    bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
238
                      unsigned &Dups1, unsigned &Dups2,
239
                      BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
240
    bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
241
                            unsigned &Dups1, unsigned &Dups2,
242
                            BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
243
    void AnalyzeBranches(BBInfo &BBI);
244
    void ScanInstructions(BBInfo &BBI,
245
                          MachineBasicBlock::iterator &Begin,
246
                          MachineBasicBlock::iterator &End,
247
                          bool BranchUnpredicable = false) const;
248
    bool RescanInstructions(
249
        MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
250
        MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
251
        BBInfo &TrueBBI, BBInfo &FalseBBI) const;
252
    void AnalyzeBlock(MachineBasicBlock &MBB,
253
                      std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
254
    bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
255
                             bool isTriangle = false, bool RevBranch = false,
256
                             bool hasCommonTail = false);
257
    void AnalyzeBlocks(MachineFunction &MF,
258
                       std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
259
    void InvalidatePreds(MachineBasicBlock &MBB);
260
    bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
261
    bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
262
    bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
263
                                unsigned NumDups1, unsigned NumDups2,
264
                                bool TClobbersPred, bool FClobbersPred,
265
                                bool RemoveBranch, bool MergeAddEdges);
266
    bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
267
                          unsigned NumDups1, unsigned NumDups2,
268
                          bool TClobbers, bool FClobbers);
269
    bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
270
                              unsigned NumDups1, unsigned NumDups2,
271
                              bool TClobbers, bool FClobbers);
272
    void PredicateBlock(BBInfo &BBI,
273
                        MachineBasicBlock::iterator E,
274
                        SmallVectorImpl<MachineOperand> &Cond,
275
                        SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
276
    void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
277
                               SmallVectorImpl<MachineOperand> &Cond,
278
                               bool IgnoreBr = false);
279
    void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
280
281
    bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
282
                            unsigned Cycle, unsigned Extra,
283
34.2k
                            BranchProbability Prediction) const {
284
34.2k
      return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
285
33.9k
                                                   Prediction);
286
34.2k
    }
287
288
    bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
289
                            unsigned TCycle, unsigned TExtra,
290
                            MachineBasicBlock &FBB,
291
                            unsigned FCycle, unsigned FExtra,
292
930
                            BranchProbability Prediction) const {
293
930
      return TCycle > 0 && 
FCycle > 0917
&&
294
930
        TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
295
916
                                 Prediction);
296
930
    }
297
298
    /// Returns true if Block ends without a terminator.
299
119k
    bool blockAlwaysFallThrough(BBInfo &BBI) const {
300
119k
      return BBI.IsBrAnalyzable && 
BBI.TrueBB == nullptr83.9k
;
301
119k
    }
302
303
    /// Used to sort if-conversion candidates.
304
    static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
305
6.64k
                              const std::unique_ptr<IfcvtToken> &C2) {
306
6.64k
      int Incr1 = (C1->Kind == ICDiamond)
307
6.64k
        ? 
-(int)(C1->NumDups + C1->NumDups2)37
:
(int)C1->NumDups6.60k
;
308
6.64k
      int Incr2 = (C2->Kind == ICDiamond)
309
6.64k
        ? 
-(int)(C2->NumDups + C2->NumDups2)279
:
(int)C2->NumDups6.36k
;
310
6.64k
      if (Incr1 > Incr2)
311
281
        return true;
312
6.36k
      else if (Incr1 == Incr2) {
313
6.12k
        // Favors subsumption.
314
6.12k
        if (!C1->NeedSubsumption && 
C2->NeedSubsumption6.07k
)
315
6
          return true;
316
6.11k
        else if (C1->NeedSubsumption == C2->NeedSubsumption) {
317
6.10k
          // Favors diamond over triangle, etc.
318
6.10k
          if ((unsigned)C1->Kind < (unsigned)C2->Kind)
319
2.78k
            return true;
320
3.32k
          else if (C1->Kind == C2->Kind)
321
2.44k
            return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
322
1.13k
        }
323
6.12k
      }
324
1.13k
      return false;
325
1.13k
    }
326
  };
327
328
} // end anonymous namespace
329
330
char IfConverter::ID = 0;
331
332
char &llvm::IfConverterID = IfConverter::ID;
333
334
42.3k
INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
335
42.3k
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
336
42.3k
INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
337
338
49.4k
bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
339
49.4k
  if (skipFunction(MF.getFunction()) || 
(49.4k
PredicateFtor49.4k
&&
!PredicateFtor(MF)25.2k
))
340
1.55k
    return false;
341
47.9k
342
47.9k
  const TargetSubtargetInfo &ST = MF.getSubtarget();
343
47.9k
  TLI = ST.getTargetLowering();
344
47.9k
  TII = ST.getInstrInfo();
345
47.9k
  TRI = ST.getRegisterInfo();
346
47.9k
  BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
347
47.9k
  MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
348
47.9k
  MRI = &MF.getRegInfo();
349
47.9k
  SchedModel.init(&ST);
350
47.9k
351
47.9k
  if (!TII) 
return false0
;
352
47.9k
353
47.9k
  PreRegAlloc = MRI->isSSA();
354
47.9k
355
47.9k
  bool BFChange = false;
356
47.9k
  if (!PreRegAlloc) {
357
47.9k
    // Tail merge tend to expose more if-conversion opportunities.
358
47.9k
    BranchFolder BF(true, false, MBFI, *MBPI);
359
47.9k
    BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
360
47.9k
                                   getAnalysisIfAvailable<MachineModuleInfo>());
361
47.9k
  }
362
47.9k
363
47.9k
  LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
364
47.9k
                    << MF.getName() << "\'");
365
47.9k
366
47.9k
  if (FnNum < IfCvtFnStart || 
(47.8k
IfCvtFnStop != -147.8k
&&
FnNum > IfCvtFnStop0
)) {
367
52
    LLVM_DEBUG(dbgs() << " skipped\n");
368
52
    return false;
369
52
  }
370
47.8k
  LLVM_DEBUG(dbgs() << "\n");
371
47.8k
372
47.8k
  MF.RenumberBlocks();
373
47.8k
  BBAnalysis.resize(MF.getNumBlockIDs());
374
47.8k
375
47.8k
  std::vector<std::unique_ptr<IfcvtToken>> Tokens;
376
47.8k
  MadeChange = false;
377
47.8k
  unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
378
47.8k
    NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
379
52.6k
  while (IfCvtLimit == -1 || 
(int)NumIfCvts < IfCvtLimit6
) {
380
52.6k
    // Do an initial analysis for each basic block and find all the potential
381
52.6k
    // candidates to perform if-conversion.
382
52.6k
    bool Change = false;
383
52.6k
    AnalyzeBlocks(MF, Tokens);
384
61.4k
    while (!Tokens.empty()) {
385
8.82k
      std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
386
8.82k
      Tokens.pop_back();
387
8.82k
      BBInfo &BBI = Token->BBI;
388
8.82k
      IfcvtKind Kind = Token->Kind;
389
8.82k
      unsigned NumDups = Token->NumDups;
390
8.82k
      unsigned NumDups2 = Token->NumDups2;
391
8.82k
392
8.82k
      // If the block has been evicted out of the queue or it has already been
393
8.82k
      // marked dead (due to it being predicated), then skip it.
394
8.82k
      if (BBI.IsDone)
395
366
        BBI.IsEnqueued = false;
396
8.82k
      if (!BBI.IsEnqueued)
397
2.73k
        continue;
398
6.09k
399
6.09k
      BBI.IsEnqueued = false;
400
6.09k
401
6.09k
      bool RetVal = false;
402
6.09k
      switch (Kind) {
403
6.09k
      
default: 0
llvm_unreachable0
("Unexpected!");
404
6.09k
      case ICSimple:
405
2.86k
      case ICSimpleFalse: {
406
2.86k
        bool isFalse = Kind == ICSimpleFalse;
407
2.86k
        if ((isFalse && 
DisableSimpleF711
) || (!isFalse &&
DisableSimple2.15k
))
break0
;
408
2.86k
        LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
409
2.86k
                          << (Kind == ICSimpleFalse ? " false" : "")
410
2.86k
                          << "): " << printMBBReference(*BBI.BB) << " ("
411
2.86k
                          << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
412
2.86k
                                                      : BBI.TrueBB->getNumber())
413
2.86k
                          << ") ");
414
2.86k
        RetVal = IfConvertSimple(BBI, Kind);
415
2.86k
        LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
416
2.86k
        if (RetVal) {
417
2.69k
          if (isFalse) 
++NumSimpleFalse659
;
418
2.03k
          else         ++NumSimple;
419
2.69k
        }
420
2.86k
       break;
421
2.86k
      }
422
2.99k
      case ICTriangle:
423
2.99k
      case ICTriangleRev:
424
2.99k
      case ICTriangleFalse:
425
2.99k
      case ICTriangleFRev: {
426
2.99k
        bool isFalse = Kind == ICTriangleFalse;
427
2.99k
        bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
428
2.99k
        if (DisableTriangle && 
!isFalse0
&&
!isRev0
)
break0
;
429
2.99k
        if (DisableTriangleR && 
!isFalse0
&&
isRev0
)
break0
;
430
2.99k
        if (DisableTriangleF && 
isFalse0
&&
!isRev0
)
break0
;
431
2.99k
        if (DisableTriangleFR && 
isFalse0
&&
isRev0
)
break0
;
432
2.99k
        LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
433
2.99k
        if (isFalse)
434
2.99k
          LLVM_DEBUG(dbgs() << " false");
435
2.99k
        if (isRev)
436
2.99k
          LLVM_DEBUG(dbgs() << " rev");
437
2.99k
        LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
438
2.99k
                          << " (T:" << BBI.TrueBB->getNumber()
439
2.99k
                          << ",F:" << BBI.FalseBB->getNumber() << ") ");
440
2.99k
        RetVal = IfConvertTriangle(BBI, Kind);
441
2.99k
        LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
442
2.99k
        if (RetVal) {
443
2.99k
          if (isFalse) {
444
2.67k
            if (isRev) 
++NumTriangleFRev0
;
445
2.67k
            else       ++NumTriangleFalse;
446
2.67k
          } else {
447
323
            if (isRev) 
++NumTriangleRev261
;
448
62
            else       ++NumTriangle;
449
323
          }
450
2.99k
        }
451
2.99k
        break;
452
2.99k
      }
453
2.99k
      case ICDiamond:
454
236
        if (DisableDiamond) 
break0
;
455
236
        LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
456
236
                          << " (T:" << BBI.TrueBB->getNumber()
457
236
                          << ",F:" << BBI.FalseBB->getNumber() << ") ");
458
236
        RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
459
236
                                  Token->TClobbersPred,
460
236
                                  Token->FClobbersPred);
461
236
        LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
462
236
        if (RetVal) 
++NumDiamonds235
;
463
236
        break;
464
236
      case ICForkedDiamond:
465
2
        if (DisableForkedDiamond) 
break0
;
466
2
        LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
467
2
                          << printMBBReference(*BBI.BB)
468
2
                          << " (T:" << BBI.TrueBB->getNumber()
469
2
                          << ",F:" << BBI.FalseBB->getNumber() << ") ");
470
2
        RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
471
2
                                      Token->TClobbersPred,
472
2
                                      Token->FClobbersPred);
473
2
        LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
474
2
        if (RetVal) ++NumForkedDiamonds;
475
2
        break;
476
6.09k
      }
477
6.09k
478
6.09k
      if (RetVal && 
MRI->tracksLiveness()5.92k
)
479
5.89k
        recomputeLivenessFlags(*BBI.BB);
480
6.09k
481
6.09k
      Change |= RetVal;
482
6.09k
483
6.09k
      NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
484
6.09k
        NumTriangleFalse + NumTriangleFRev + NumDiamonds;
485
6.09k
      if (IfCvtLimit != -1 && 
(int)NumIfCvts >= IfCvtLimit0
)
486
0
        break;
487
6.09k
    }
488
52.6k
489
52.6k
    if (!Change)
490
47.8k
      break;
491
4.75k
    MadeChange |= Change;
492
4.75k
  }
493
47.8k
494
47.8k
  Tokens.clear();
495
47.8k
  BBAnalysis.clear();
496
47.8k
497
47.8k
  if (MadeChange && 
IfCvtBranchFold4.45k
) {
498
4.45k
    BranchFolder BF(false, false, MBFI, *MBPI);
499
4.45k
    BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
500
4.45k
                        getAnalysisIfAvailable<MachineModuleInfo>());
501
4.45k
  }
502
47.8k
503
47.8k
  MadeChange |= BFChange;
504
47.8k
  return MadeChange;
505
47.8k
}
506
507
/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
508
static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
509
55.6k
                                         MachineBasicBlock *TrueBB) {
510
85.7k
  for (MachineBasicBlock *SuccBB : BB->successors()) {
511
85.7k
    if (SuccBB != TrueBB)
512
55.6k
      return SuccBB;
513
85.7k
  }
514
55.6k
  
return nullptr3
;
515
55.6k
}
516
517
/// Reverse the condition of the end of the block branch. Swap block's 'true'
518
/// and 'false' successors.
519
331
bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
520
331
  DebugLoc dl;  // FIXME: this is nowhere
521
331
  if (!TII->reverseBranchCondition(BBI.BrCond)) {
522
331
    TII->removeBranch(*BBI.BB);
523
331
    TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
524
331
    std::swap(BBI.TrueBB, BBI.FalseBB);
525
331
    return true;
526
331
  }
527
0
  return false;
528
0
}
529
530
/// Returns the next block in the function blocks ordering. If it is the end,
531
/// returns NULL.
532
34.9k
static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
533
34.9k
  MachineFunction::iterator I = MBB.getIterator();
534
34.9k
  MachineFunction::iterator E = MBB.getParent()->end();
535
34.9k
  if (++I == E)
536
4.14k
    return nullptr;
537
30.8k
  return &*I;
538
30.8k
}
539
540
/// Returns true if the 'true' block (along with its predecessor) forms a valid
541
/// simple shape for ifcvt. It also returns the number of instructions that the
542
/// ifcvt would need to duplicate if performed in Dups.
543
bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
544
105k
                              BranchProbability Prediction) const {
545
105k
  Dups = 0;
546
105k
  if (TrueBBI.IsBeingAnalyzed || 
TrueBBI.IsDone103k
)
547
3.66k
    return false;
548
101k
549
101k
  if (TrueBBI.IsBrAnalyzable)
550
83.1k
    return false;
551
18.3k
552
18.3k
  if (TrueBBI.BB->pred_size() > 1) {
553
12.5k
    if (TrueBBI.CannotBeCopied ||
554
12.5k
        !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
555
12.5k
                                        Prediction))
556
8.93k
      return false;
557
3.59k
    Dups = TrueBBI.NonPredSize;
558
3.59k
  }
559
18.3k
560
18.3k
  
return true9.45k
;
561
18.3k
}
562
563
/// Returns true if the 'true' and 'false' blocks (along with their common
564
/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
565
/// true, it checks if 'true' block's false branch branches to the 'false' block
566
/// rather than the other way around. It also returns the number of instructions
567
/// that the ifcvt would need to duplicate if performed in 'Dups'.
568
bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
569
                                bool FalseBranch, unsigned &Dups,
570
210k
                                BranchProbability Prediction) const {
571
210k
  Dups = 0;
572
210k
  if (TrueBBI.IsBeingAnalyzed || 
TrueBBI.IsDone206k
)
573
7.33k
    return false;
574
203k
575
203k
  if (TrueBBI.BB->pred_size() > 1) {
576
79.2k
    if (TrueBBI.CannotBeCopied)
577
140
      return false;
578
79.0k
579
79.0k
    unsigned Size = TrueBBI.NonPredSize;
580
79.0k
    if (TrueBBI.IsBrAnalyzable) {
581
54.0k
      if (TrueBBI.TrueBB && 
TrueBBI.BrCond.empty()36.3k
)
582
4.49k
        // Ends with an unconditional branch. It will be removed.
583
4.49k
        --Size;
584
49.5k
      else {
585
49.5k
        MachineBasicBlock *FExit = FalseBranch
586
49.5k
          ? 
TrueBBI.TrueBB24.7k
:
TrueBBI.FalseBB24.7k
;
587
49.5k
        if (FExit)
588
31.8k
          // Require a conditional branch
589
31.8k
          ++Size;
590
49.5k
      }
591
54.0k
    }
592
79.0k
    if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
593
61.8k
      return false;
594
17.2k
    Dups = Size;
595
17.2k
  }
596
203k
597
203k
  
MachineBasicBlock *TExit = FalseBranch 141k
?
TrueBBI.FalseBB70.5k
:
TrueBBI.TrueBB70.5k
;
598
141k
  if (!TExit && 
blockAlwaysFallThrough(TrueBBI)74.9k
) {
599
46.6k
    MachineFunction::iterator I = TrueBBI.BB->getIterator();
600
46.6k
    if (++I == TrueBBI.BB->getParent()->end())
601
4.54k
      return false;
602
42.1k
    TExit = &*I;
603
42.1k
  }
604
141k
  
return 136k
TExit136k
&&
TExit == FalseBBI.BB108k
;
605
141k
}
606
607
/// Count duplicated instructions and move the iterators to show where they
608
/// are.
609
/// @param TIB True Iterator Begin
610
/// @param FIB False Iterator Begin
611
/// These two iterators initially point to the first instruction of the two
612
/// blocks, and finally point to the first non-shared instruction.
613
/// @param TIE True Iterator End
614
/// @param FIE False Iterator End
615
/// These two iterators initially point to End() for the two blocks() and
616
/// finally point to the first shared instruction in the tail.
617
/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
618
/// two blocks.
619
/// @param Dups1 count of duplicated instructions at the beginning of the 2
620
/// blocks.
621
/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
622
/// @param SkipUnconditionalBranches if true, Don't make sure that
623
/// unconditional branches at the end of the blocks are the same. True is
624
/// passed when the blocks are analyzable to allow for fallthrough to be
625
/// handled.
626
/// @return false if the shared portion prevents if conversion.
627
bool IfConverter::CountDuplicatedInstructions(
628
    MachineBasicBlock::iterator &TIB,
629
    MachineBasicBlock::iterator &FIB,
630
    MachineBasicBlock::iterator &TIE,
631
    MachineBasicBlock::iterator &FIE,
632
    unsigned &Dups1, unsigned &Dups2,
633
    MachineBasicBlock &TBB, MachineBasicBlock &FBB,
634
2.63k
    bool SkipUnconditionalBranches) const {
635
2.77k
  while (TIB != TIE && 
FIB != FIE2.77k
) {
636
2.77k
    // Skip dbg_value instructions. These do not count.
637
2.77k
    TIB = skipDebugInstructionsForward(TIB, TIE);
638
2.77k
    FIB = skipDebugInstructionsForward(FIB, FIE);
639
2.77k
    if (TIB == TIE || FIB == FIE)
640
0
      break;
641
2.77k
    if (!TIB->isIdenticalTo(*FIB))
642
2.63k
      break;
643
140
    // A pred-clobbering instruction in the shared portion prevents
644
140
    // if-conversion.
645
140
    std::vector<MachineOperand> PredDefs;
646
140
    if (TII->DefinesPredicate(*TIB, PredDefs))
647
3
      return false;
648
137
    // If we get all the way to the branch instructions, don't count them.
649
137
    if (!TIB->isBranch())
650
136
      ++Dups1;
651
137
    ++TIB;
652
137
    ++FIB;
653
137
  }
654
2.63k
655
2.63k
  // Check for already containing all of the block.
656
2.63k
  
if (2.63k
TIB == TIE2.63k
||
FIB == FIE2.63k
)
657
3
    return true;
658
2.63k
  // Now, in preparation for counting duplicate instructions at the ends of the
659
2.63k
  // blocks, switch to reverse_iterators. Note that getReverse() returns an
660
2.63k
  // iterator that points to the same instruction, unlike std::reverse_iterator.
661
2.63k
  // We have to do our own shifting so that we get the same range.
662
2.63k
  MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
663
2.63k
  MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
664
2.63k
  const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
665
2.63k
  const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
666
2.63k
667
2.63k
  if (!TBB.succ_empty() || 
!FBB.succ_empty()1.04k
) {
668
1.60k
    if (SkipUnconditionalBranches) {
669
1.69k
      while (RTIE != RTIB && RTIE->isUnconditionalBranch())
670
119
        ++RTIE;
671
3.12k
      while (RFIE != RFIB && 
RFIE->isUnconditionalBranch()3.11k
)
672
1.54k
        ++RFIE;
673
1.57k
    }
674
1.60k
  }
675
2.63k
676
2.63k
  // Count duplicate instructions at the ends of the blocks.
677
3.37k
  while (RTIE != RTIB && 
RFIE != RFIB3.36k
) {
678
3.35k
    // Skip dbg_value instructions. These do not count.
679
3.35k
    // Note that these are reverse iterators going forward.
680
3.35k
    RTIE = skipDebugInstructionsForward(RTIE, RTIB);
681
3.35k
    RFIE = skipDebugInstructionsForward(RFIE, RFIB);
682
3.35k
    if (RTIE == RTIB || RFIE == RFIB)
683
0
      break;
684
3.35k
    if (!RTIE->isIdenticalTo(*RFIE))
685
2.61k
      break;
686
739
    // We have to verify that any branch instructions are the same, and then we
687
739
    // don't count them toward the # of duplicate instructions.
688
739
    if (!RTIE->isBranch())
689
685
      ++Dups2;
690
739
    ++RTIE;
691
739
    ++RFIE;
692
739
  }
693
2.63k
  TIE = std::next(RTIE.getReverse());
694
2.63k
  FIE = std::next(RFIE.getReverse());
695
2.63k
  return true;
696
2.63k
}
697
698
/// RescanInstructions - Run ScanInstructions on a pair of blocks.
699
/// @param TIB - True Iterator Begin, points to first non-shared instruction
700
/// @param FIB - False Iterator Begin, points to first non-shared instruction
701
/// @param TIE - True Iterator End, points past last non-shared instruction
702
/// @param FIE - False Iterator End, points past last non-shared instruction
703
/// @param TrueBBI  - BBInfo to update for the true block.
704
/// @param FalseBBI - BBInfo to update for the false block.
705
/// @returns - false if either block cannot be predicated or if both blocks end
706
///   with a predicate-clobbering instruction.
707
bool IfConverter::RescanInstructions(
708
    MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
709
    MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
710
2.63k
    BBInfo &TrueBBI, BBInfo &FalseBBI) const {
711
2.63k
  bool BranchUnpredicable = true;
712
2.63k
  TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
713
2.63k
  ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
714
2.63k
  if (TrueBBI.IsUnpredicable)
715
1.28k
    return false;
716
1.34k
  ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
717
1.34k
  if (FalseBBI.IsUnpredicable)
718
325
    return false;
719
1.02k
  if (TrueBBI.ClobbersPred && 
FalseBBI.ClobbersPred112
)
720
94
    return false;
721
930
  return true;
722
930
}
723
724
#ifndef NDEBUG
725
static void verifySameBranchInstructions(
726
    MachineBasicBlock *MBB1,
727
    MachineBasicBlock *MBB2) {
728
  const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
729
  const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
730
  MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
731
  MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
732
  while (E1 != B1 && E2 != B2) {
733
    skipDebugInstructionsForward(E1, B1);
734
    skipDebugInstructionsForward(E2, B2);
735
    if (E1 == B1 && E2 == B2)
736
      break;
737
738
    if (E1 == B1) {
739
      assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
740
      break;
741
    }
742
    if (E2 == B2) {
743
      assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
744
      break;
745
    }
746
747
    if (E1->isBranch() || E2->isBranch())
748
      assert(E1->isIdenticalTo(*E2) &&
749
             "Branch mis-match, branch instructions don't match.");
750
    else
751
      break;
752
    ++E1;
753
    ++E2;
754
  }
755
}
756
#endif
757
758
/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
759
/// with their common predecessor) form a diamond if a common tail block is
760
/// extracted.
761
/// While not strictly a diamond, this pattern would form a diamond if
762
/// tail-merging had merged the shared tails.
763
///           EBB
764
///         _/   \_
765
///         |     |
766
///        TBB   FBB
767
///        /  \ /   \
768
///  FalseBB TrueBB FalseBB
769
/// Currently only handles analyzable branches.
770
/// Specifically excludes actual diamonds to avoid overlap.
771
bool IfConverter::ValidForkedDiamond(
772
    BBInfo &TrueBBI, BBInfo &FalseBBI,
773
    unsigned &Dups1, unsigned &Dups2,
774
51.6k
    BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
775
51.6k
  Dups1 = Dups2 = 0;
776
51.6k
  if (TrueBBI.IsBeingAnalyzed || 
TrueBBI.IsDone49.7k
||
777
51.6k
      
FalseBBI.IsBeingAnalyzed48.9k
||
FalseBBI.IsDone48.8k
)
778
3.65k
    return false;
779
48.0k
780
48.0k
  if (!TrueBBI.IsBrAnalyzable || 
!FalseBBI.IsBrAnalyzable34.2k
)
781
15.4k
    return false;
782
32.6k
  // Don't IfConvert blocks that can't be folded into their predecessor.
783
32.6k
  if  (TrueBBI.BB->pred_size() > 1 || 
FalseBBI.BB->pred_size() > 113.1k
)
784
20.6k
    return false;
785
12.0k
786
12.0k
  // This function is specifically looking for conditional tails, as
787
12.0k
  // unconditional tails are already handled by the standard diamond case.
788
12.0k
  if (TrueBBI.BrCond.size() == 0 ||
789
12.0k
      
FalseBBI.BrCond.size() == 05.92k
)
790
10.4k
    return false;
791
1.55k
792
1.55k
  MachineBasicBlock *TT = TrueBBI.TrueBB;
793
1.55k
  MachineBasicBlock *TF = TrueBBI.FalseBB;
794
1.55k
  MachineBasicBlock *FT = FalseBBI.TrueBB;
795
1.55k
  MachineBasicBlock *FF = FalseBBI.FalseBB;
796
1.55k
797
1.55k
  if (!TT)
798
0
    TT = getNextBlock(*TrueBBI.BB);
799
1.55k
  if (!TF)
800
0
    TF = getNextBlock(*TrueBBI.BB);
801
1.55k
  if (!FT)
802
0
    FT = getNextBlock(*FalseBBI.BB);
803
1.55k
  if (!FF)
804
0
    FF = getNextBlock(*FalseBBI.BB);
805
1.55k
806
1.55k
  if (!TT || !TF)
807
0
    return false;
808
1.55k
809
1.55k
  // Check successors. If they don't match, bail.
810
1.55k
  if (!((TT == FT && 
TF == FF177
) ||
(1.55k
TF == FT1.55k
&&
TT == FF126
)))
811
1.51k
    return false;
812
39
813
39
  bool FalseReversed = false;
814
39
  if (TF == FT && 
TT == FF35
) {
815
35
    // If the branches are opposing, but we can't reverse, don't do it.
816
35
    if (!FalseBBI.IsBrReversible)
817
0
      return false;
818
35
    FalseReversed = true;
819
35
    reverseBranchCondition(FalseBBI);
820
35
  }
821
39
  auto UnReverseOnExit = make_scope_exit([&]() {
822
39
    if (FalseReversed)
823
35
      reverseBranchCondition(FalseBBI);
824
39
  });
825
39
826
39
  // Count duplicate instructions at the beginning of the true and false blocks.
827
39
  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
828
39
  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
829
39
  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
830
39
  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
831
39
  if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
832
39
                                  *TrueBBI.BB, *FalseBBI.BB,
833
39
                                  /* SkipUnconditionalBranches */ true))
834
0
    return false;
835
39
836
39
  TrueBBICalc.BB = TrueBBI.BB;
837
39
  FalseBBICalc.BB = FalseBBI.BB;
838
39
  if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
839
37
    return false;
840
2
841
2
  // The size is used to decide whether to if-convert, and the shared portions
842
2
  // are subtracted off. Because of the subtraction, we just use the size that
843
2
  // was calculated by the original ScanInstructions, as it is correct.
844
2
  TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
845
2
  FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
846
2
  return true;
847
2
}
848
849
/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
850
/// with their common predecessor) forms a valid diamond shape for ifcvt.
851
bool IfConverter::ValidDiamond(
852
    BBInfo &TrueBBI, BBInfo &FalseBBI,
853
    unsigned &Dups1, unsigned &Dups2,
854
52.6k
    BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
855
52.6k
  Dups1 = Dups2 = 0;
856
52.6k
  if (TrueBBI.IsBeingAnalyzed || 
TrueBBI.IsDone50.7k
||
857
52.6k
      
FalseBBI.IsBeingAnalyzed49.8k
||
FalseBBI.IsDone49.7k
)
858
3.65k
    return false;
859
48.9k
860
48.9k
  MachineBasicBlock *TT = TrueBBI.TrueBB;
861
48.9k
  MachineBasicBlock *FT = FalseBBI.TrueBB;
862
48.9k
863
48.9k
  if (!TT && 
blockAlwaysFallThrough(TrueBBI)27.5k
)
864
13.5k
    TT = getNextBlock(*TrueBBI.BB);
865
48.9k
  if (!FT && 
blockAlwaysFallThrough(FalseBBI)17.2k
)
866
14.1k
    FT = getNextBlock(*FalseBBI.BB);
867
48.9k
  if (TT != FT)
868
41.9k
    return false;
869
6.98k
  if (!TT && 
(2.39k
TrueBBI.IsBrAnalyzable2.39k
||
FalseBBI.IsBrAnalyzable1.43k
))
870
963
    return false;
871
6.02k
  if  (TrueBBI.BB->pred_size() > 1 || 
FalseBBI.BB->pred_size() > 14.48k
)
872
1.75k
    return false;
873
4.26k
874
4.26k
  // FIXME: Allow true block to have an early exit?
875
4.26k
  if (TrueBBI.FalseBB || 
FalseBBI.FalseBB3.66k
)
876
1.66k
    return false;
877
2.59k
878
2.59k
  // Count duplicate instructions at the beginning and end of the true and
879
2.59k
  // false blocks.
880
2.59k
  // Skip unconditional branches only if we are considering an analyzable
881
2.59k
  // diamond. Otherwise the branches must be the same.
882
2.59k
  bool SkipUnconditionalBranches =
883
2.59k
      TrueBBI.IsBrAnalyzable && 
FalseBBI.IsBrAnalyzable1.53k
;
884
2.59k
  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
885
2.59k
  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
886
2.59k
  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
887
2.59k
  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
888
2.59k
  if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
889
2.59k
                                  *TrueBBI.BB, *FalseBBI.BB,
890
2.59k
                                  SkipUnconditionalBranches))
891
3
    return false;
892
2.59k
893
2.59k
  TrueBBICalc.BB = TrueBBI.BB;
894
2.59k
  FalseBBICalc.BB = FalseBBI.BB;
895
2.59k
  if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
896
1.66k
    return false;
897
928
  // The size is used to decide whether to if-convert, and the shared portions
898
928
  // are subtracted off. Because of the subtraction, we just use the size that
899
928
  // was calculated by the original ScanInstructions, as it is correct.
900
928
  TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
901
928
  FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
902
928
  return true;
903
928
}
904
905
/// AnalyzeBranches - Look at the branches at the end of a block to determine if
906
/// the block is predicable.
907
157k
void IfConverter::AnalyzeBranches(BBInfo &BBI) {
908
157k
  if (BBI.IsDone)
909
6.49k
    return;
910
150k
911
150k
  BBI.TrueBB = BBI.FalseBB = nullptr;
912
150k
  BBI.BrCond.clear();
913
150k
  BBI.IsBrAnalyzable =
914
150k
      !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
915
150k
  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
916
150k
  BBI.IsBrReversible = (RevCond.size() == 0) ||
917
150k
      
!TII->reverseBranchCondition(RevCond)56.7k
;
918
150k
  BBI.HasFallThrough = BBI.IsBrAnalyzable && 
BBI.FalseBB == nullptr100k
;
919
150k
920
150k
  if (BBI.BrCond.size()) {
921
56.7k
    // No false branch. This BB must end with a conditional branch and a
922
56.7k
    // fallthrough.
923
56.7k
    if (!BBI.FalseBB)
924
55.6k
      BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
925
56.7k
    if (!BBI.FalseBB) {
926
3
      // Malformed bcc? True and false blocks are the same?
927
3
      BBI.IsUnpredicable = true;
928
3
    }
929
56.7k
  }
930
150k
}
931
932
/// ScanInstructions - Scan all the instructions in the block to determine if
933
/// the block is predicable. In most cases, that means all the instructions
934
/// in the block are isPredicable(). Also checks if the block contains any
935
/// instruction which can clobber a predicate (e.g. condition code register).
936
/// If so, the block is not predicable unless it's the last instruction.
937
void IfConverter::ScanInstructions(BBInfo &BBI,
938
                                   MachineBasicBlock::iterator &Begin,
939
                                   MachineBasicBlock::iterator &End,
940
160k
                                   bool BranchUnpredicable) const {
941
160k
  if (BBI.IsDone || 
BBI.IsUnpredicable154k
)
942
11.1k
    return;
943
149k
944
149k
  bool AlreadyPredicated = !BBI.Predicate.empty();
945
149k
946
149k
  BBI.NonPredSize = 0;
947
149k
  BBI.ExtraCost = 0;
948
149k
  BBI.ExtraCost2 = 0;
949
149k
  BBI.ClobbersPred = false;
950
378k
  for (MachineInstr &MI : make_range(Begin, End)) {
951
378k
    if (MI.isDebugInstr())
952
117
      continue;
953
378k
954
378k
    // It's unsafe to duplicate convergent instructions in this context, so set
955
378k
    // BBI.CannotBeCopied to true if MI is convergent.  To see why, consider the
956
378k
    // following CFG, which is subject to our "simple" transformation.
957
378k
    //
958
378k
    //    BB0     // if (c1) goto BB1; else goto BB2;
959
378k
    //   /   \
960
378k
    //  BB1   |
961
378k
    //   |   BB2  // if (c2) goto TBB; else goto FBB;
962
378k
    //   |   / |
963
378k
    //   |  /  |
964
378k
    //   TBB   |
965
378k
    //    |    |
966
378k
    //    |   FBB
967
378k
    //    |
968
378k
    //    exit
969
378k
    //
970
378k
    // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
971
378k
    // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
972
378k
    // TBB contains a convergent instruction.  This is safe iff doing so does
973
378k
    // not add a control-flow dependency to the convergent instruction -- i.e.,
974
378k
    // it's safe iff the set of control flows that leads us to the convergent
975
378k
    // instruction does not get smaller after the transformation.
976
378k
    //
977
378k
    // Originally we executed TBB if c1 || c2.  After the transformation, there
978
378k
    // are two copies of TBB's instructions.  We get to the first if c1, and we
979
378k
    // get to the second if !c1 && c2.
980
378k
    //
981
378k
    // There are clearly fewer ways to satisfy the condition "c1" than
982
378k
    // "c1 || c2".  Since we've shrunk the set of control flows which lead to
983
378k
    // our convergent instruction, the transformation is unsafe.
984
378k
    if (MI.isNotDuplicable() || 
MI.isConvergent()366k
)
985
11.4k
      BBI.CannotBeCopied = true;
986
378k
987
378k
    bool isPredicated = TII->isPredicated(MI);
988
378k
    bool isCondBr = BBI.IsBrAnalyzable && 
MI.isConditionalBranch()268k
;
989
378k
990
378k
    if (BranchUnpredicable && 
MI.isBranch()9.76k
) {
991
14
      BBI.IsUnpredicable = true;
992
14
      return;
993
14
    }
994
378k
995
378k
    // A conditional branch is not predicable, but it may be eliminated.
996
378k
    if (isCondBr)
997
27.4k
      continue;
998
350k
999
350k
    if (!isPredicated) {
1000
344k
      BBI.NonPredSize++;
1001
344k
      unsigned ExtraPredCost = TII->getPredicationCost(MI);
1002
344k
      unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1003
344k
      if (NumCycles > 1)
1004
56.2k
        BBI.ExtraCost += NumCycles-1;
1005
344k
      BBI.ExtraCost2 += ExtraPredCost;
1006
344k
    } else 
if (6.25k
!AlreadyPredicated6.25k
) {
1007
2.57k
      // FIXME: This instruction is already predicated before the
1008
2.57k
      // if-conversion pass. It's probably something like a conditional move.
1009
2.57k
      // Mark this block unpredicable for now.
1010
2.57k
      BBI.IsUnpredicable = true;
1011
2.57k
      return;
1012
2.57k
    }
1013
348k
1014
348k
    if (BBI.ClobbersPred && 
!isPredicated21.9k
) {
1015
18.4k
      // Predicate modification instruction should end the block (except for
1016
18.4k
      // already predicated instructions and end of block branches).
1017
18.4k
      // Predicate may have been modified, the subsequent (currently)
1018
18.4k
      // unpredicated instructions cannot be correctly predicated.
1019
18.4k
      BBI.IsUnpredicable = true;
1020
18.4k
      return;
1021
18.4k
    }
1022
329k
1023
329k
    // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1024
329k
    // still potentially predicable.
1025
329k
    std::vector<MachineOperand> PredDefs;
1026
329k
    if (TII->DefinesPredicate(MI, PredDefs))
1027
54.6k
      BBI.ClobbersPred = true;
1028
329k
1029
329k
    if (!TII->isPredicable(MI)) {
1030
63.8k
      BBI.IsUnpredicable = true;
1031
63.8k
      return;
1032
63.8k
    }
1033
329k
  }
1034
149k
}
1035
1036
/// Determine if the block is a suitable candidate to be predicated by the
1037
/// specified predicate.
1038
/// @param BBI BBInfo for the block to check
1039
/// @param Pred Predicate array for the branch that leads to BBI
1040
/// @param isTriangle true if the Analysis is for a triangle
1041
/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1042
///        case
1043
/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1044
///        contains any instruction that would make the block unpredicable.
1045
bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
1046
                                      SmallVectorImpl<MachineOperand> &Pred,
1047
                                      bool isTriangle, bool RevBranch,
1048
25.5k
                                      bool hasCommonTail) {
1049
25.5k
  // If the block is dead or unpredicable, then it cannot be predicated.
1050
25.5k
  // Two blocks may share a common unpredicable tail, but this doesn't prevent
1051
25.5k
  // them from being if-converted. The non-shared portion is assumed to have
1052
25.5k
  // been checked
1053
25.5k
  if (BBI.IsDone || (BBI.IsUnpredicable && 
!hasCommonTail12.5k
))
1054
12.4k
    return false;
1055
13.0k
1056
13.0k
  // If it is already predicated but we couldn't analyze its terminator, the
1057
13.0k
  // latter might fallthrough, but we can't determine where to.
1058
13.0k
  // Conservatively avoid if-converting again.
1059
13.0k
  if (BBI.Predicate.size() && 
!BBI.IsBrAnalyzable155
)
1060
0
    return false;
1061
13.0k
1062
13.0k
  // If it is already predicated, check if the new predicate subsumes
1063
13.0k
  // its predicate.
1064
13.0k
  if (BBI.Predicate.size() && 
!TII->SubsumesPredicate(Pred, BBI.Predicate)155
)
1065
86
    return false;
1066
12.9k
1067
12.9k
  if (!hasCommonTail && 
BBI.BrCond.size()11.0k
) {
1068
3.91k
    if (!isTriangle)
1069
0
      return false;
1070
3.91k
1071
3.91k
    // Test predicate subsumption.
1072
3.91k
    SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1073
3.91k
    SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1074
3.91k
    if (RevBranch) {
1075
1.60k
      if (TII->reverseBranchCondition(Cond))
1076
5
        return false;
1077
3.90k
    }
1078
3.90k
    if (TII->reverseBranchCondition(RevPred) ||
1079
3.90k
        !TII->SubsumesPredicate(Cond, RevPred))
1080
2.50k
      return false;
1081
10.4k
  }
1082
10.4k
1083
10.4k
  return true;
1084
10.4k
}
1085
1086
/// Analyze the structure of the sub-CFG starting from the specified block.
1087
/// Record its successors and whether it looks like an if-conversion candidate.
1088
void IfConverter::AnalyzeBlock(
1089
198k
    MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1090
198k
  struct BBState {
1091
303k
    BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
1092
198k
    MachineBasicBlock *MBB;
1093
198k
1094
198k
    /// This flag is true if MBB's successors have been analyzed.
1095
198k
    bool SuccsAnalyzed;
1096
198k
  };
1097
198k
1098
198k
  // Push MBB to the stack.
1099
198k
  SmallVector<BBState, 16> BBStack(1, MBB);
1100
198k
1101
555k
  while (!BBStack.empty()) {
1102
356k
    BBState &State = BBStack.back();
1103
356k
    MachineBasicBlock *BB = State.MBB;
1104
356k
    BBInfo &BBI = BBAnalysis[BB->getNumber()];
1105
356k
1106
356k
    if (!State.SuccsAnalyzed) {
1107
303k
      if (BBI.IsAnalyzed || 
BBI.IsBeingAnalyzed158k
) {
1108
146k
        BBStack.pop_back();
1109
146k
        continue;
1110
146k
      }
1111
157k
1112
157k
      BBI.BB = BB;
1113
157k
      BBI.IsBeingAnalyzed = true;
1114
157k
1115
157k
      AnalyzeBranches(BBI);
1116
157k
      MachineBasicBlock::iterator Begin = BBI.BB->begin();
1117
157k
      MachineBasicBlock::iterator End = BBI.BB->end();
1118
157k
      ScanInstructions(BBI, Begin, End);
1119
157k
1120
157k
      // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1121
157k
      // not considered for ifcvt anymore.
1122
157k
      if (!BBI.IsBrAnalyzable || 
BBI.BrCond.empty()105k
||
BBI.IsDone59.5k
) {
1123
100k
        BBI.IsBeingAnalyzed = false;
1124
100k
        BBI.IsAnalyzed = true;
1125
100k
        BBStack.pop_back();
1126
100k
        continue;
1127
100k
      }
1128
56.6k
1129
56.6k
      // Do not ifcvt if either path is a back edge to the entry block.
1130
56.6k
      if (BBI.TrueBB == BB || 
BBI.FalseBB == BB52.7k
) {
1131
3.91k
        BBI.IsBeingAnalyzed = false;
1132
3.91k
        BBI.IsAnalyzed = true;
1133
3.91k
        BBStack.pop_back();
1134
3.91k
        continue;
1135
3.91k
      }
1136
52.7k
1137
52.7k
      // Do not ifcvt if true and false fallthrough blocks are the same.
1138
52.7k
      if (!BBI.FalseBB) {
1139
3
        BBI.IsBeingAnalyzed = false;
1140
3
        BBI.IsAnalyzed = true;
1141
3
        BBStack.pop_back();
1142
3
        continue;
1143
3
      }
1144
52.7k
1145
52.7k
      // Push the False and True blocks to the stack.
1146
52.7k
      State.SuccsAnalyzed = true;
1147
52.7k
      BBStack.push_back(*BBI.FalseBB);
1148
52.7k
      BBStack.push_back(*BBI.TrueBB);
1149
52.7k
      continue;
1150
52.7k
    }
1151
52.7k
1152
52.7k
    BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1153
52.7k
    BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1154
52.7k
1155
52.7k
    if (TrueBBI.IsDone && 
FalseBBI.IsDone958
) {
1156
90
      BBI.IsBeingAnalyzed = false;
1157
90
      BBI.IsAnalyzed = true;
1158
90
      BBStack.pop_back();
1159
90
      continue;
1160
90
    }
1161
52.6k
1162
52.6k
    SmallVector<MachineOperand, 4>
1163
52.6k
        RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1164
52.6k
    bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1165
52.6k
1166
52.6k
    unsigned Dups = 0;
1167
52.6k
    unsigned Dups2 = 0;
1168
52.6k
    bool TNeedSub = !TrueBBI.Predicate.empty();
1169
52.6k
    bool FNeedSub = !FalseBBI.Predicate.empty();
1170
52.6k
    bool Enqueued = false;
1171
52.6k
1172
52.6k
    BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1173
52.6k
1174
52.6k
    if (CanRevCond) {
1175
52.6k
      BBInfo TrueBBICalc, FalseBBICalc;
1176
52.6k
      auto feasibleDiamond = [&]() {
1177
930
        bool MeetsSize = MeetIfcvtSizeLimit(
1178
930
            *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1179
930
                          TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1180
930
            *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1181
930
                           FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1182
930
            Prediction);
1183
930
        bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1184
930
                                                /* IsTriangle */ false, /* RevCond */ false,
1185
930
                                                /* hasCommonTail */ true);
1186
930
        bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1187
930
                                                 /* IsTriangle */ false, /* RevCond */ false,
1188
930
                                                 /* hasCommonTail */ true);
1189
930
        return MeetsSize && 
TrueFeasible238
&&
FalseFeasible238
;
1190
930
      };
1191
52.6k
1192
52.6k
      if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1193
52.6k
                       TrueBBICalc, FalseBBICalc)) {
1194
928
        if (feasibleDiamond()) {
1195
236
          // Diamond:
1196
236
          //   EBB
1197
236
          //   / \_
1198
236
          //  |   |
1199
236
          // TBB FBB
1200
236
          //   \ /
1201
236
          //  TailBB
1202
236
          // Note TailBB can be empty.
1203
236
          Tokens.push_back(llvm::make_unique<IfcvtToken>(
1204
236
              BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1205
236
              (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1206
236
          Enqueued = true;
1207
236
        }
1208
51.6k
      } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1209
51.6k
                                    TrueBBICalc, FalseBBICalc)) {
1210
2
        if (feasibleDiamond()) {
1211
2
          // ForkedDiamond:
1212
2
          // if TBB and FBB have a common tail that includes their conditional
1213
2
          // branch instructions, then we can If Convert this pattern.
1214
2
          //          EBB
1215
2
          //         _/ \_
1216
2
          //         |   |
1217
2
          //        TBB  FBB
1218
2
          //        / \ /   \
1219
2
          //  FalseBB TrueBB FalseBB
1220
2
          //
1221
2
          Tokens.push_back(llvm::make_unique<IfcvtToken>(
1222
2
              BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1223
2
              (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1224
2
          Enqueued = true;
1225
2
        }
1226
2
      }
1227
52.6k
    }
1228
52.6k
1229
52.6k
    if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1230
52.6k
        MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1231
303
                           TrueBBI.ExtraCost2, Prediction) &&
1232
52.6k
        
FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)229
) {
1233
62
      // Triangle:
1234
62
      //   EBB
1235
62
      //   | \_
1236
62
      //   |  |
1237
62
      //   | TBB
1238
62
      //   |  /
1239
62
      //   FBB
1240
62
      Tokens.push_back(
1241
62
          llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1242
62
      Enqueued = true;
1243
62
    }
1244
52.6k
1245
52.6k
    if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1246
52.6k
        MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1247
30
                           TrueBBI.ExtraCost2, Prediction) &&
1248
52.6k
        
FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)19
) {
1249
1
      Tokens.push_back(
1250
1
          llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1251
1
      Enqueued = true;
1252
1
    }
1253
52.6k
1254
52.6k
    if (ValidSimple(TrueBBI, Dups, Prediction) &&
1255
52.6k
        MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1256
6.22k
                           TrueBBI.ExtraCost2, Prediction) &&
1257
52.6k
        
FeasibilityAnalysis(TrueBBI, BBI.BrCond)4.20k
) {
1258
2.52k
      // Simple (split, no rejoin):
1259
2.52k
      //   EBB
1260
2.52k
      //   | \_
1261
2.52k
      //   |  |
1262
2.52k
      //   | TBB---> exit
1263
2.52k
      //   |
1264
2.52k
      //   FBB
1265
2.52k
      Tokens.push_back(
1266
2.52k
          llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1267
2.52k
      Enqueued = true;
1268
2.52k
    }
1269
52.6k
1270
52.6k
    if (CanRevCond) {
1271
52.6k
      // Try the other path...
1272
52.6k
      if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1273
52.6k
                        Prediction.getCompl()) &&
1274
52.6k
          MeetIfcvtSizeLimit(*FalseBBI.BB,
1275
13.9k
                             FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1276
13.9k
                             FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1277
52.6k
          
FeasibilityAnalysis(FalseBBI, RevCond, true)9.29k
) {
1278
2.99k
        Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1279
2.99k
                                                       FNeedSub, Dups));
1280
2.99k
        Enqueued = true;
1281
2.99k
      }
1282
52.6k
1283
52.6k
      if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1284
52.6k
                        Prediction.getCompl()) &&
1285
52.6k
          MeetIfcvtSizeLimit(*FalseBBI.BB,
1286
10.4k
                             FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1287
10.4k
                           FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1288
52.6k
        
FeasibilityAnalysis(FalseBBI, RevCond, true, true)7.34k
) {
1289
2.05k
        Tokens.push_back(
1290
2.05k
            llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1291
2.05k
        Enqueued = true;
1292
2.05k
      }
1293
52.6k
1294
52.6k
      if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1295
52.6k
          MeetIfcvtSizeLimit(*FalseBBI.BB,
1296
3.23k
                             FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1297
3.23k
                             FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1298
52.6k
          
FeasibilityAnalysis(FalseBBI, RevCond)2.57k
) {
1299
950
        Tokens.push_back(
1300
950
            llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1301
950
        Enqueued = true;
1302
950
      }
1303
52.6k
    }
1304
52.6k
1305
52.6k
    BBI.IsEnqueued = Enqueued;
1306
52.6k
    BBI.IsBeingAnalyzed = false;
1307
52.6k
    BBI.IsAnalyzed = true;
1308
52.6k
    BBStack.pop_back();
1309
52.6k
  }
1310
198k
}
1311
1312
/// Analyze all blocks and find entries for all if-conversion candidates.
1313
void IfConverter::AnalyzeBlocks(
1314
52.6k
    MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1315
52.6k
  for (MachineBasicBlock &MBB : MF)
1316
198k
    AnalyzeBlock(MBB, Tokens);
1317
52.6k
1318
52.6k
  // Sort to favor more complex ifcvt scheme.
1319
52.6k
  llvm::stable_sort(Tokens, IfcvtTokenCmp);
1320
52.6k
}
1321
1322
/// Returns true either if ToMBB is the next block after MBB or that all the
1323
/// intervening blocks are empty (given MBB can fall through to its next block).
1324
5.68k
static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1325
5.68k
  MachineFunction::iterator PI = MBB.getIterator();
1326
5.68k
  MachineFunction::iterator I = std::next(PI);
1327
5.68k
  MachineFunction::iterator TI = ToMBB.getIterator();
1328
5.68k
  MachineFunction::iterator E = MBB.getParent()->end();
1329
5.68k
  while (I != TI) {
1330
1.41k
    // Check isSuccessor to avoid case where the next block is empty, but
1331
1.41k
    // it's not a successor.
1332
1.41k
    if (I == E || 
!I->empty()1.41k
||
!PI->isSuccessor(&*I)48
)
1333
1.41k
      return false;
1334
1
    PI = I++;
1335
1
  }
1336
5.68k
  // Finally see if the last I is indeed a successor to PI.
1337
5.68k
  
return PI->isSuccessor(&*I)4.27k
;
1338
5.68k
}
1339
1340
/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1341
/// can be if-converted. If predecessor is already enqueued, dequeue it!
1342
5.92k
void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1343
5.92k
  for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1344
5.18k
    BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1345
5.18k
    if (PBBI.IsDone || 
PBBI.BB == &MBB5.02k
)
1346
175
      continue;
1347
5.01k
    PBBI.IsAnalyzed = false;
1348
5.01k
    PBBI.IsEnqueued = false;
1349
5.01k
  }
1350
5.92k
}
1351
1352
/// Inserts an unconditional branch from \p MBB to \p ToMBB.
1353
static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
1354
1.53k
                               const TargetInstrInfo *TII) {
1355
1.53k
  DebugLoc dl;  // FIXME: this is nowhere
1356
1.53k
  SmallVector<MachineOperand, 0> NoCond;
1357
1.53k
  TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1358
1.53k
}
1359
1360
/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1361
/// values defined in MI which are also live/used by MI.
1362
10.6k
static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
1363
10.6k
  const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
1364
10.6k
1365
10.6k
  // Before stepping forward past MI, remember which regs were live
1366
10.6k
  // before MI. This is needed to set the Undef flag only when reg is
1367
10.6k
  // dead.
1368
10.6k
  SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
1369
10.6k
  LiveBeforeMI.setUniverse(TRI->getNumRegs());
1370
10.6k
  for (unsigned Reg : Redefs)
1371
351k
    LiveBeforeMI.insert(Reg);
1372
10.6k
1373
10.6k
  SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
1374
10.6k
  Redefs.stepForward(MI, Clobbers);
1375
10.6k
1376
10.6k
  // Now add the implicit uses for each of the clobbered values.
1377
12.3k
  for (auto Clobber : Clobbers) {
1378
12.3k
    // FIXME: Const cast here is nasty, but better than making StepForward
1379
12.3k
    // take a mutable instruction instead of const.
1380
12.3k
    unsigned Reg = Clobber.first;
1381
12.3k
    MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1382
12.3k
    MachineInstr *OpMI = Op.getParent();
1383
12.3k
    MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
1384
12.3k
    if (Op.isRegMask()) {
1385
747
      // First handle regmasks.  They clobber any entries in the mask which
1386
747
      // means that we need a def for those registers.
1387
747
      if (LiveBeforeMI.count(Reg))
1388
747
        MIB.addReg(Reg, RegState::Implicit);
1389
747
1390
747
      // We also need to add an implicit def of this register for the later
1391
747
      // use to read from.
1392
747
      // For the register allocator to have allocated a register clobbered
1393
747
      // by the call which is used later, it must be the case that
1394
747
      // the call doesn't return.
1395
747
      MIB.addReg(Reg, RegState::Implicit | RegState::Define);
1396
747
      continue;
1397
747
    }
1398
11.5k
    if (LiveBeforeMI.count(Reg))
1399
2.75k
      MIB.addReg(Reg, RegState::Implicit);
1400
8.81k
    else {
1401
8.81k
      bool HasLiveSubReg = false;
1402
8.90k
      for (MCSubRegIterator S(Reg, TRI); S.isValid(); 
++S82
) {
1403
100
        if (!LiveBeforeMI.count(*S))
1404
82
          continue;
1405
18
        HasLiveSubReg = true;
1406
18
        break;
1407
18
      }
1408
8.81k
      if (HasLiveSubReg)
1409
18
        MIB.addReg(Reg, RegState::Implicit);
1410
8.81k
    }
1411
11.5k
  }
1412
10.6k
}
1413
1414
/// If convert a simple (split, no rejoin) sub-CFG.
1415
2.86k
bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1416
2.86k
  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1417
2.86k
  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1418
2.86k
  BBInfo *CvtBBI = &TrueBBI;
1419
2.86k
  BBInfo *NextBBI = &FalseBBI;
1420
2.86k
1421
2.86k
  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1422
2.86k
  if (Kind == ICSimpleFalse)
1423
711
    std::swap(CvtBBI, NextBBI);
1424
2.86k
1425
2.86k
  MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1426
2.86k
  MachineBasicBlock &NextMBB = *NextBBI->BB;
1427
2.86k
  if (CvtBBI->IsDone ||
1428
2.86k
      
(2.69k
CvtBBI->CannotBeCopied2.69k
&&
CvtMBB.pred_size() > 10
)) {
1429
168
    // Something has changed. It's no longer safe to predicate this block.
1430
168
    BBI.IsAnalyzed = false;
1431
168
    CvtBBI->IsAnalyzed = false;
1432
168
    return false;
1433
168
  }
1434
2.69k
1435
2.69k
  if (CvtMBB.hasAddressTaken())
1436
0
    // Conservatively abort if-conversion if BB's address is taken.
1437
0
    return false;
1438
2.69k
1439
2.69k
  if (Kind == ICSimpleFalse)
1440
659
    if (TII->reverseBranchCondition(Cond))
1441
659
      
llvm_unreachable0
("Unable to reverse branch condition!");
1442
2.69k
1443
2.69k
  Redefs.init(*TRI);
1444
2.69k
1445
2.69k
  if (MRI->tracksLiveness()) {
1446
2.68k
    // Initialize liveins to the first BB. These are potentially redefined by
1447
2.68k
    // predicated instructions.
1448
2.68k
    Redefs.addLiveIns(CvtMBB);
1449
2.68k
    Redefs.addLiveIns(NextMBB);
1450
2.68k
  }
1451
2.69k
1452
2.69k
  // Remove the branches from the entry so we can add the contents of the true
1453
2.69k
  // block to it.
1454
2.69k
  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1455
2.69k
1456
2.69k
  if (CvtMBB.pred_size() > 1) {
1457
1.32k
    // Copy instructions in the true block, predicate them, and add them to
1458
1.32k
    // the entry block.
1459
1.32k
    CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1460
1.32k
1461
1.32k
    // Keep the CFG updated.
1462
1.32k
    BBI.BB->removeSuccessor(&CvtMBB, true);
1463
1.37k
  } else {
1464
1.37k
    // Predicate the instructions in the true block.
1465
1.37k
    PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1466
1.37k
1467
1.37k
    // Merge converted block into entry block. The BB to Cvt edge is removed
1468
1.37k
    // by MergeBlocks.
1469
1.37k
    MergeBlocks(BBI, *CvtBBI);
1470
1.37k
  }
1471
2.69k
1472
2.69k
  bool IterIfcvt = true;
1473
2.69k
  if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1474
262
    InsertUncondBranch(*BBI.BB, NextMBB, TII);
1475
262
    BBI.HasFallThrough = false;
1476
262
    // Now ifcvt'd block will look like this:
1477
262
    // BB:
1478
262
    // ...
1479
262
    // t, f = cmp
1480
262
    // if t op
1481
262
    // b BBf
1482
262
    //
1483
262
    // We cannot further ifcvt this block because the unconditional branch
1484
262
    // will have to be predicated on the new condition, that will not be
1485
262
    // available if cmp executes.
1486
262
    IterIfcvt = false;
1487
262
  }
1488
2.69k
1489
2.69k
  // Update block info. BB can be iteratively if-converted.
1490
2.69k
  if (!IterIfcvt)
1491
262
    BBI.IsDone = true;
1492
2.69k
  InvalidatePreds(*BBI.BB);
1493
2.69k
  CvtBBI->IsDone = true;
1494
2.69k
1495
2.69k
  // FIXME: Must maintain LiveIns.
1496
2.69k
  return true;
1497
2.69k
}
1498
1499
/// If convert a triangle sub-CFG.
1500
2.99k
bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1501
2.99k
  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1502
2.99k
  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1503
2.99k
  BBInfo *CvtBBI = &TrueBBI;
1504
2.99k
  BBInfo *NextBBI = &FalseBBI;
1505
2.99k
  DebugLoc dl;  // FIXME: this is nowhere
1506
2.99k
1507
2.99k
  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1508
2.99k
  if (Kind == ICTriangleFalse || 
Kind == ICTriangleFRev323
)
1509
2.93k
    std::swap(CvtBBI, NextBBI);
1510
2.99k
1511
2.99k
  MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1512
2.99k
  MachineBasicBlock &NextMBB = *NextBBI->BB;
1513
2.99k
  if (CvtBBI->IsDone ||
1514
2.99k
      (CvtBBI->CannotBeCopied && 
CvtMBB.pred_size() > 10
)) {
1515
0
    // Something has changed. It's no longer safe to predicate this block.
1516
0
    BBI.IsAnalyzed = false;
1517
0
    CvtBBI->IsAnalyzed = false;
1518
0
    return false;
1519
0
  }
1520
2.99k
1521
2.99k
  if (CvtMBB.hasAddressTaken())
1522
3
    // Conservatively abort if-conversion if BB's address is taken.
1523
3
    return false;
1524
2.99k
1525
2.99k
  if (Kind == ICTriangleFalse || 
Kind == ICTriangleFRev323
)
1526
2.93k
    if (TII->reverseBranchCondition(Cond))
1527
2.93k
      
llvm_unreachable0
("Unable to reverse branch condition!");
1528
2.99k
1529
2.99k
  if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1530
261
    if (reverseBranchCondition(*CvtBBI)) {
1531
261
      // BB has been changed, modify its predecessors (except for this
1532
261
      // one) so they don't get ifcvt'ed based on bad intel.
1533
261
      for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1534
261
        if (PBB == BBI.BB)
1535
261
          continue;
1536
0
        BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1537
0
        if (PBBI.IsEnqueued) {
1538
0
          PBBI.IsAnalyzed = false;
1539
0
          PBBI.IsEnqueued = false;
1540
0
        }
1541
0
      }
1542
261
    }
1543
261
  }
1544
2.99k
1545
2.99k
  // Initialize liveins to the first BB. These are potentially redefined by
1546
2.99k
  // predicated instructions.
1547
2.99k
  Redefs.init(*TRI);
1548
2.99k
  if (MRI->tracksLiveness()) {
1549
2.96k
    Redefs.addLiveIns(CvtMBB);
1550
2.96k
    Redefs.addLiveIns(NextMBB);
1551
2.96k
  }
1552
2.99k
1553
2.99k
  bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1554
2.99k
  BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1555
2.99k
1556
2.99k
  if (HasEarlyExit) {
1557
1.22k
    // Get probabilities before modifying CvtMBB and BBI.BB.
1558
1.22k
    CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1559
1.22k
    CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1560
1.22k
    BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1561
1.22k
    BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1562
1.22k
  }
1563
2.99k
1564
2.99k
  // Remove the branches from the entry so we can add the contents of the true
1565
2.99k
  // block to it.
1566
2.99k
  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1567
2.99k
1568
2.99k
  if (CvtMBB.pred_size() > 1) {
1569
106
    // Copy instructions in the true block, predicate them, and add them to
1570
106
    // the entry block.
1571
106
    CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1572
2.88k
  } else {
1573
2.88k
    // Predicate the 'true' block after removing its branch.
1574
2.88k
    CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1575
2.88k
    PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1576
2.88k
1577
2.88k
    // Now merge the entry of the triangle with the true block.
1578
2.88k
    MergeBlocks(BBI, *CvtBBI, false);
1579
2.88k
  }
1580
2.99k
1581
2.99k
  // Keep the CFG updated.
1582
2.99k
  BBI.BB->removeSuccessor(&CvtMBB, true);
1583
2.99k
1584
2.99k
  // If 'true' block has a 'false' successor, add an exit branch to it.
1585
2.99k
  if (HasEarlyExit) {
1586
1.22k
    SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1587
1.22k
                                           CvtBBI->BrCond.end());
1588
1.22k
    if (TII->reverseBranchCondition(RevCond))
1589
1.22k
      
llvm_unreachable0
("Unable to reverse branch condition!");
1590
1.22k
1591
1.22k
    // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1592
1.22k
    // NewNext = New_Prob(BBI.BB, NextMBB) =
1593
1.22k
    //   Prob(BBI.BB, NextMBB) +
1594
1.22k
    //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1595
1.22k
    // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1596
1.22k
    //   Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1597
1.22k
    auto NewTrueBB = getNextBlock(*BBI.BB);
1598
1.22k
    auto NewNext = BBNext + BBCvt * CvtNext;
1599
1.22k
    auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1600
1.22k
    if (NewTrueBBIter != BBI.BB->succ_end())
1601
289
      BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1602
1.22k
1603
1.22k
    auto NewFalse = BBCvt * CvtFalse;
1604
1.22k
    TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1605
1.22k
    BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1606
1.22k
  }
1607
2.99k
1608
2.99k
  // Merge in the 'false' block if the 'false' block has no other
1609
2.99k
  // predecessors. Otherwise, add an unconditional branch to 'false'.
1610
2.99k
  bool FalseBBDead = false;
1611
2.99k
  bool IterIfcvt = true;
1612
2.99k
  bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1613
2.99k
  if (!isFallThrough) {
1614
1.15k
    // Only merge them if the true block does not fallthrough to the false
1615
1.15k
    // block. By not merging them, we make it possible to iteratively
1616
1.15k
    // ifcvt the blocks.
1617
1.15k
    if (!HasEarlyExit &&
1618
1.15k
        
NextMBB.pred_size() == 1215
&&
!NextBBI->HasFallThrough5
&&
1619
1.15k
        
!NextMBB.hasAddressTaken()2
) {
1620
2
      MergeBlocks(BBI, *NextBBI);
1621
2
      FalseBBDead = true;
1622
1.14k
    } else {
1623
1.14k
      InsertUncondBranch(*BBI.BB, NextMBB, TII);
1624
1.14k
      BBI.HasFallThrough = false;
1625
1.14k
    }
1626
1.15k
    // Mixed predicated and unpredicated code. This cannot be iteratively
1627
1.15k
    // predicated.
1628
1.15k
    IterIfcvt = false;
1629
1.15k
  }
1630
2.99k
1631
2.99k
  // Update block info. BB can be iteratively if-converted.
1632
2.99k
  if (!IterIfcvt)
1633
1.15k
    BBI.IsDone = true;
1634
2.99k
  InvalidatePreds(*BBI.BB);
1635
2.99k
  CvtBBI->IsDone = true;
1636
2.99k
  if (FalseBBDead)
1637
2
    NextBBI->IsDone = true;
1638
2.99k
1639
2.99k
  // FIXME: Must maintain LiveIns.
1640
2.99k
  return true;
1641
2.99k
}
1642
1643
/// Common code shared between diamond conversions.
1644
/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1645
/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1646
///               and FalseBBI
1647
/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1648
///               and \p FalseBBI
1649
/// \p RemoveBranch - Remove the common branch of the two blocks before
1650
///                   predicating. Only false for unanalyzable fallthrough
1651
///                   cases. The caller will replace the branch if necessary.
1652
/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1653
///                    unanalyzable fallthrough
1654
bool IfConverter::IfConvertDiamondCommon(
1655
    BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1656
    unsigned NumDups1, unsigned NumDups2,
1657
    bool TClobbersPred, bool FClobbersPred,
1658
238
    bool RemoveBranch, bool MergeAddEdges) {
1659
238
1660
238
  if (TrueBBI.IsDone || FalseBBI.IsDone ||
1661
238
      TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1662
0
    // Something has changed. It's no longer safe to predicate these blocks.
1663
0
    BBI.IsAnalyzed = false;
1664
0
    TrueBBI.IsAnalyzed = false;
1665
0
    FalseBBI.IsAnalyzed = false;
1666
0
    return false;
1667
0
  }
1668
238
1669
238
  if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1670
1
    // Conservatively abort if-conversion if either BB has its address taken.
1671
1
    return false;
1672
237
1673
237
  // Put the predicated instructions from the 'true' block before the
1674
237
  // instructions from the 'false' block, unless the true block would clobber
1675
237
  // the predicate, in which case, do the opposite.
1676
237
  BBInfo *BBI1 = &TrueBBI;
1677
237
  BBInfo *BBI2 = &FalseBBI;
1678
237
  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1679
237
  if (TII->reverseBranchCondition(RevCond))
1680
237
    
llvm_unreachable0
("Unable to reverse branch condition!");
1681
237
  SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1682
237
  SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1683
237
1684
237
  // Figure out the more profitable ordering.
1685
237
  bool DoSwap = false;
1686
237
  if (TClobbersPred && 
!FClobbersPred0
)
1687
0
    DoSwap = true;
1688
237
  else if (!TClobbersPred && !FClobbersPred) {
1689
236
    if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1690
39
      DoSwap = true;
1691
236
  } else 
if (1
TClobbersPred1
&&
FClobbersPred0
)
1692
1
    
llvm_unreachable0
("Predicate info cannot be clobbered by both sides.");
1693
237
  if (DoSwap) {
1694
39
    std::swap(BBI1, BBI2);
1695
39
    std::swap(Cond1, Cond2);
1696
39
  }
1697
237
1698
237
  // Remove the conditional branch from entry to the blocks.
1699
237
  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1700
237
1701
237
  MachineBasicBlock &MBB1 = *BBI1->BB;
1702
237
  MachineBasicBlock &MBB2 = *BBI2->BB;
1703
237
1704
237
  // Initialize the Redefs:
1705
237
  // - BB2 live-in regs need implicit uses before being redefined by BB1
1706
237
  //   instructions.
1707
237
  // - BB1 live-out regs need implicit uses before being redefined by BB2
1708
237
  //   instructions. We start with BB1 live-ins so we have the live-out regs
1709
237
  //   after tracking the BB1 instructions.
1710
237
  Redefs.init(*TRI);
1711
237
  if (MRI->tracksLiveness()) {
1712
232
    Redefs.addLiveIns(MBB1);
1713
232
    Redefs.addLiveIns(MBB2);
1714
232
  }
1715
237
1716
237
  // Remove the duplicated instructions at the beginnings of both paths.
1717
237
  // Skip dbg_value instructions.
1718
237
  MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1719
237
  MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
1720
237
  BBI1->NonPredSize -= NumDups1;
1721
237
  BBI2->NonPredSize -= NumDups1;
1722
237
1723
237
  // Skip past the dups on each side separately since there may be
1724
237
  // differing dbg_value entries. NumDups1 can include a "return"
1725
237
  // instruction, if it's not marked as "branch".
1726
249
  for (unsigned i = 0; i < NumDups1; 
++DI112
) {
1727
12
    if (DI1 == MBB1.end())
1728
0
      break;
1729
12
    if (!DI1->isDebugInstr())
1730
12
      ++i;
1731
12
  }
1732
248
  while (NumDups1 != 0) {
1733
12
    ++DI2;
1734
12
    if (DI2 == MBB2.end())
1735
1
      break;
1736
11
    if (!DI2->isDebugInstr())
1737
11
      --NumDups1;
1738
11
  }
1739
237
1740
237
  if (MRI->tracksLiveness()) {
1741
232
    for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1742
9
      SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
1743
9
      Redefs.stepForward(MI, Dummy);
1744
9
    }
1745
232
  }
1746
237
1747
237
  BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1748
237
  MBB2.erase(MBB2.begin(), DI2);
1749
237
1750
237
  // The branches have been checked to match, so it is safe to remove the
1751
237
  // branch in BB1 and rely on the copy in BB2. The complication is that
1752
237
  // the blocks may end with a return instruction, which may or may not
1753
237
  // be marked as "branch". If it's not, then it could be included in
1754
237
  // "dups1", leaving the blocks potentially empty after moving the common
1755
237
  // duplicates.
1756
#ifndef NDEBUG
1757
  // Unanalyzable branches must match exactly. Check that now.
1758
  if (!BBI1->IsBrAnalyzable)
1759
    verifySameBranchInstructions(&MBB1, &MBB2);
1760
#endif
1761
  BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
1762
237
  // Remove duplicated instructions.
1763
237
  DI1 = MBB1.end();
1764
349
  for (unsigned i = 0; i != NumDups2; ) {
1765
112
    // NumDups2 only counted non-dbg_value instructions, so this won't
1766
112
    // run off the head of the list.
1767
112
    assert(DI1 != MBB1.begin());
1768
112
    --DI1;
1769
112
    // skip dbg_value instructions
1770
112
    if (!DI1->isDebugInstr())
1771
112
      ++i;
1772
112
  }
1773
237
  MBB1.erase(DI1, MBB1.end());
1774
237
1775
237
  DI2 = BBI2->BB->end();
1776
237
  // The branches have been checked to match. Skip over the branch in the false
1777
237
  // block so that we don't try to predicate it.
1778
237
  if (RemoveBranch)
1779
132
    BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1780
105
  else {
1781
105
    // Make DI2 point to the end of the range where the common "tail"
1782
105
    // instructions could be found.
1783
111
    while (DI2 != MBB2.begin()) {
1784
109
      MachineBasicBlock::iterator Prev = std::prev(DI2);
1785
109
      if (!Prev->isBranch() && 
!Prev->isDebugInstr()103
)
1786
103
        break;
1787
6
      DI2 = Prev;
1788
6
    }
1789
105
  }
1790
349
  while (NumDups2 != 0) {
1791
112
    // NumDups2 only counted non-dbg_value instructions, so this won't
1792
112
    // run off the head of the list.
1793
112
    assert(DI2 != MBB2.begin());
1794
112
    --DI2;
1795
112
    // skip dbg_value instructions
1796
112
    if (!DI2->isDebugInstr())
1797
112
      --NumDups2;
1798
112
  }
1799
237
1800
237
  // Remember which registers would later be defined by the false block.
1801
237
  // This allows us not to predicate instructions in the true block that would
1802
237
  // later be re-defined. That is, rather than
1803
237
  //   subeq  r0, r1, #1
1804
237
  //   addne  r0, r1, #1
1805
237
  // generate:
1806
237
  //   sub    r0, r1, #1
1807
237
  //   addne  r0, r1, #1
1808
237
  SmallSet<MCPhysReg, 4> RedefsByFalse;
1809
237
  SmallSet<MCPhysReg, 4> ExtUses;
1810
237
  if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1811
27
    for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1812
27
      if (FI.isDebugInstr())
1813
0
        continue;
1814
27
      SmallVector<MCPhysReg, 4> Defs;
1815
137
      for (const MachineOperand &MO : FI.operands()) {
1816
137
        if (!MO.isReg())
1817
47
          continue;
1818
90
        unsigned Reg = MO.getReg();
1819
90
        if (!Reg)
1820
48
          continue;
1821
42
        if (MO.isDef()) {
1822
25
          Defs.push_back(Reg);
1823
25
        } else 
if (17
!RedefsByFalse.count(Reg)17
) {
1824
14
          // These are defined before ctrl flow reach the 'false' instructions.
1825
14
          // They cannot be modified by the 'true' instructions.
1826
14
          for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1827
28
               SubRegs.isValid(); 
++SubRegs14
)
1828
14
            ExtUses.insert(*SubRegs);
1829
14
        }
1830
42
      }
1831
27
1832
27
      for (MCPhysReg Reg : Defs) {
1833
25
        if (!ExtUses.count(Reg)) {
1834
20
          for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1835
40
               SubRegs.isValid(); 
++SubRegs20
)
1836
20
            RedefsByFalse.insert(*SubRegs);
1837
20
        }
1838
25
      }
1839
27
    }
1840
19
  }
1841
237
1842
237
  // Predicate the 'true' block.
1843
237
  PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1844
237
1845
237
  // After predicating BBI1, if there is a predicated terminator in BBI1 and
1846
237
  // a non-predicated in BBI2, then we don't want to predicate the one from
1847
237
  // BBI2. The reason is that if we merged these blocks, we would end up with
1848
237
  // two predicated terminators in the same block.
1849
237
  // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1850
237
  // predicate them either. They were checked to be identical, and so the
1851
237
  // same branch would happen regardless of which path was taken.
1852
237
  if (!MBB2.empty() && 
(DI2 == MBB2.end())236
) {
1853
129
    MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1854
129
    MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1855
129
    bool BB1Predicated = BBI1T != MBB1.end() && 
TII->isPredicated(*BBI1T)1
;
1856
129
    bool BB2NonPredicated = BBI2T != MBB2.end() && 
!TII->isPredicated(*BBI2T)1
;
1857
129
    if (BB2NonPredicated && 
(1
BB1Predicated1
||
!BBI2->IsBrAnalyzable0
))
1858
1
      --DI2;
1859
129
  }
1860
237
1861
237
  // Predicate the 'false' block.
1862
237
  PredicateBlock(*BBI2, DI2, *Cond2);
1863
237
1864
237
  // Merge the true block into the entry of the diamond.
1865
237
  MergeBlocks(BBI, *BBI1, MergeAddEdges);
1866
237
  MergeBlocks(BBI, *BBI2, MergeAddEdges);
1867
237
  return true;
1868
237
}
1869
1870
/// If convert an almost-diamond sub-CFG where the true
1871
/// and false blocks share a common tail.
1872
bool IfConverter::IfConvertForkedDiamond(
1873
    BBInfo &BBI, IfcvtKind Kind,
1874
    unsigned NumDups1, unsigned NumDups2,
1875
2
    bool TClobbersPred, bool FClobbersPred) {
1876
2
  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1877
2
  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1878
2
1879
2
  // Save the debug location for later.
1880
2
  DebugLoc dl;
1881
2
  MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1882
2
  if (TIE != TrueBBI.BB->end())
1883
2
    dl = TIE->getDebugLoc();
1884
2
  // Removing branches from both blocks is safe, because we have already
1885
2
  // determined that both blocks have the same branch instructions. The branch
1886
2
  // will be added back at the end, unpredicated.
1887
2
  if (!IfConvertDiamondCommon(
1888
2
      BBI, TrueBBI, FalseBBI,
1889
2
      NumDups1, NumDups2,
1890
2
      TClobbersPred, FClobbersPred,
1891
2
      /* RemoveBranch */ true, /* MergeAddEdges */ true))
1892
0
    return false;
1893
2
1894
2
  // Add back the branch.
1895
2
  // Debug location saved above when removing the branch from BBI2
1896
2
  TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1897
2
                    TrueBBI.BrCond, dl);
1898
2
1899
2
  // Update block info.
1900
2
  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1901
2
  InvalidatePreds(*BBI.BB);
1902
2
1903
2
  // FIXME: Must maintain LiveIns.
1904
2
  return true;
1905
2
}
1906
1907
/// If convert a diamond sub-CFG.
1908
bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1909
                                   unsigned NumDups1, unsigned NumDups2,
1910
236
                                   bool TClobbersPred, bool FClobbersPred) {
1911
236
  BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1912
236
  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1913
236
  MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1914
236
1915
236
  // True block must fall through or end with an unanalyzable terminator.
1916
236
  if (!TailBB) {
1917
223
    if (blockAlwaysFallThrough(TrueBBI))
1918
117
      TailBB = FalseBBI.TrueBB;
1919
223
    assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1920
223
  }
1921
236
1922
236
  if (!IfConvertDiamondCommon(
1923
236
      BBI, TrueBBI, FalseBBI,
1924
236
      NumDups1, NumDups2,
1925
236
      TClobbersPred, FClobbersPred,
1926
236
      /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
1927
236
      /* MergeAddEdges */ TailBB == nullptr))
1928
1
    return false;
1929
235
1930
235
  // If the if-converted block falls through or unconditionally branches into
1931
235
  // the tail block, and the tail block does not have other predecessors, then
1932
235
  // fold the tail block in as well. Otherwise, unless it falls through to the
1933
235
  // tail, add a unconditional branch to it.
1934
235
  if (TailBB) {
1935
130
    // We need to remove the edges to the true and false blocks manually since
1936
130
    // we didn't let IfConvertDiamondCommon update the CFG.
1937
130
    BBI.BB->removeSuccessor(TrueBBI.BB);
1938
130
    BBI.BB->removeSuccessor(FalseBBI.BB, true);
1939
130
1940
130
    BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1941
130
    bool CanMergeTail = !TailBBI.HasFallThrough &&
1942
130
      
!TailBBI.BB->hasAddressTaken()36
;
1943
130
    // The if-converted block can still have a predicated terminator
1944
130
    // (e.g. a predicated return). If that is the case, we cannot merge
1945
130
    // it with the tail block.
1946
130
    MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1947
130
    if (TI != BBI.BB->end() && 
TII->isPredicated(*TI)0
)
1948
0
      CanMergeTail = false;
1949
130
    // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1950
130
    // check if there are any other predecessors besides those.
1951
130
    unsigned NumPreds = TailBB->pred_size();
1952
130
    if (NumPreds > 1)
1953
110
      CanMergeTail = false;
1954
20
    else if (NumPreds == 1 && CanMergeTail) {
1955
3
      MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1956
3
      if (*PI != TrueBBI.BB && 
*PI != FalseBBI.BB2
)
1957
0
        CanMergeTail = false;
1958
3
    }
1959
130
    if (CanMergeTail) {
1960
3
      MergeBlocks(BBI, TailBBI);
1961
3
      TailBBI.IsDone = true;
1962
127
    } else {
1963
127
      BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1964
127
      InsertUncondBranch(*BBI.BB, *TailBB, TII);
1965
127
      BBI.HasFallThrough = false;
1966
127
    }
1967
130
  }
1968
235
1969
235
  // Update block info.
1970
235
  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1971
235
  InvalidatePreds(*BBI.BB);
1972
235
1973
235
  // FIXME: Must maintain LiveIns.
1974
235
  return true;
1975
235
}
1976
1977
static bool MaySpeculate(const MachineInstr &MI,
1978
236
                         SmallSet<MCPhysReg, 4> &LaterRedefs) {
1979
236
  bool SawStore = true;
1980
236
  if (!MI.isSafeToMove(nullptr, SawStore))
1981
49
    return false;
1982
187
1983
226
  
for (const MachineOperand &MO : MI.operands())187
{
1984
226
    if (!MO.isReg())
1985
18
      continue;
1986
208
    unsigned Reg = MO.getReg();
1987
208
    if (!Reg)
1988
18
      continue;
1989
190
    if (MO.isDef() && 
!LaterRedefs.count(Reg)187
)
1990
177
      return false;
1991
190
  }
1992
187
1993
187
  
return true10
;
1994
187
}
1995
1996
/// Predicate instructions from the start of the block to the specified end with
1997
/// the specified condition.
1998
void IfConverter::PredicateBlock(BBInfo &BBI,
1999
                                 MachineBasicBlock::iterator E,
2000
                                 SmallVectorImpl<MachineOperand> &Cond,
2001
4.73k
                                 SmallSet<MCPhysReg, 4> *LaterRedefs) {
2002
4.73k
  bool AnyUnpred = false;
2003
4.73k
  bool MaySpec = LaterRedefs != nullptr;
2004
9.27k
  for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2005
9.27k
    if (I.isDebugInstr() || TII->isPredicated(I))
2006
53
      continue;
2007
9.22k
    // It may be possible not to predicate an instruction if it's the 'true'
2008
9.22k
    // side of a diamond and the 'false' side may re-define the instruction's
2009
9.22k
    // defs.
2010
9.22k
    if (MaySpec && 
MaySpeculate(I, *LaterRedefs)236
) {
2011
10
      AnyUnpred = true;
2012
10
      continue;
2013
10
    }
2014
9.21k
    // If any instruction is predicated, then every instruction after it must
2015
9.21k
    // be predicated.
2016
9.21k
    MaySpec = false;
2017
9.21k
    if (!TII->PredicateInstruction(I, Cond)) {
2018
#ifndef NDEBUG
2019
      dbgs() << "Unable to predicate " << I << "!\n";
2020
#endif
2021
0
      llvm_unreachable(nullptr);
2022
0
    }
2023
9.21k
2024
9.21k
    // If the predicated instruction now redefines a register as the result of
2025
9.21k
    // if-conversion, add an implicit kill.
2026
9.21k
    UpdatePredRedefs(I, Redefs);
2027
9.21k
  }
2028
4.73k
2029
4.73k
  BBI.Predicate.append(Cond.begin(), Cond.end());
2030
4.73k
2031
4.73k
  BBI.IsAnalyzed = false;
2032
4.73k
  BBI.NonPredSize = 0;
2033
4.73k
2034
4.73k
  ++NumIfConvBBs;
2035
4.73k
  if (AnyUnpred)
2036
10
    ++NumUnpred;
2037
4.73k
}
2038
2039
/// Copy and predicate instructions from source BB to the destination block.
2040
/// Skip end of block branches if IgnoreBr is true.
2041
void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2042
                                        SmallVectorImpl<MachineOperand> &Cond,
2043
1.42k
                                        bool IgnoreBr) {
2044
1.42k
  MachineFunction &MF = *ToBBI.BB->getParent();
2045
1.42k
2046
1.42k
  MachineBasicBlock &FromMBB = *FromBBI.BB;
2047
1.47k
  for (MachineInstr &I : FromMBB) {
2048
1.47k
    // Do not copy the end of the block branches.
2049
1.47k
    if (IgnoreBr && 
I.isBranch()122
)
2050
16
      break;
2051
1.46k
2052
1.46k
    MachineInstr *MI = MF.CloneMachineInstr(&I);
2053
1.46k
    ToBBI.BB->insert(ToBBI.BB->end(), MI);
2054
1.46k
    ToBBI.NonPredSize++;
2055
1.46k
    unsigned ExtraPredCost = TII->getPredicationCost(I);
2056
1.46k
    unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2057
1.46k
    if (NumCycles > 1)
2058
137
      ToBBI.ExtraCost += NumCycles-1;
2059
1.46k
    ToBBI.ExtraCost2 += ExtraPredCost;
2060
1.46k
2061
1.46k
    if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
2062
1.46k
      if (!TII->PredicateInstruction(*MI, Cond)) {
2063
#ifndef NDEBUG
2064
        dbgs() << "Unable to predicate " << I << "!\n";
2065
#endif
2066
0
        llvm_unreachable(nullptr);
2067
0
      }
2068
1.46k
    }
2069
1.46k
2070
1.46k
    // If the predicated instruction now redefines a register as the result of
2071
1.46k
    // if-conversion, add an implicit kill.
2072
1.46k
    UpdatePredRedefs(*MI, Redefs);
2073
1.46k
  }
2074
1.42k
2075
1.42k
  if (!IgnoreBr) {
2076
1.32k
    std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2077
1.32k
                                           FromMBB.succ_end());
2078
1.32k
    MachineBasicBlock *NBB = getNextBlock(FromMBB);
2079
1.32k
    MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? 
NBB0
: nullptr;
2080
1.32k
2081
1.32k
    for (MachineBasicBlock *Succ : Succs) {
2082
0
      // Fallthrough edge can't be transferred.
2083
0
      if (Succ == FallThrough)
2084
0
        continue;
2085
0
      ToBBI.BB->addSuccessor(Succ);
2086
0
    }
2087
1.32k
  }
2088
1.42k
2089
1.42k
  ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2090
1.42k
  ToBBI.Predicate.append(Cond.begin(), Cond.end());
2091
1.42k
2092
1.42k
  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2093
1.42k
  ToBBI.IsAnalyzed = false;
2094
1.42k
2095
1.42k
  ++NumDupBBs;
2096
1.42k
}
2097
2098
/// Move all instructions from FromBB to the end of ToBB.  This will leave
2099
/// FromBB as an empty block, so remove all of its successor edges except for
2100
/// the fall-through edge.  If AddEdges is true, i.e., when FromBBI's branch is
2101
/// being moved, add those successor edges to ToBBI and remove the old edge
2102
/// from ToBBI to FromBBI.
2103
4.73k
void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2104
4.73k
  MachineBasicBlock &FromMBB = *FromBBI.BB;
2105
4.73k
  assert(!FromMBB.hasAddressTaken() &&
2106
4.73k
         "Removing a BB whose address is taken!");
2107
4.73k
2108
4.73k
  // In case FromMBB contains terminators (e.g. return instruction),
2109
4.73k
  // first move the non-terminator instructions, then the terminators.
2110
4.73k
  MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
2111
4.73k
  MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2112
4.73k
  ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2113
4.73k
2114
4.73k
  // If FromBB has non-predicated terminator we should copy it at the end.
2115
4.73k
  if (FromTI != FromMBB.end() && 
!TII->isPredicated(*FromTI)1.48k
)
2116
311
    ToTI = ToBBI.BB->end();
2117
4.73k
  ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2118
4.73k
2119
4.73k
  // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2120
4.73k
  // unknown probabilities into known ones.
2121
4.73k
  // FIXME: This usage is too tricky and in the future we would like to
2122
4.73k
  // eliminate all unknown probabilities in MBB.
2123
4.73k
  if (ToBBI.IsBrAnalyzable)
2124
4.73k
    ToBBI.BB->normalizeSuccProbs();
2125
4.73k
2126
4.73k
  SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2127
4.73k
                                                FromMBB.succ_end());
2128
4.73k
  MachineBasicBlock *NBB = getNextBlock(FromMBB);
2129
4.73k
  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? 
NBB3.14k
:
nullptr1.59k
;
2130
4.73k
  // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2131
4.73k
  // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2132
4.73k
  auto To2FromProb = BranchProbability::getZero();
2133
4.73k
  if (AddEdges && 
ToBBI.BB->isSuccessor(&FromMBB)1.59k
) {
2134
1.58k
    // Remove the old edge but remember the edge probability so we can calculate
2135
1.58k
    // the correct weights on the new edges being added further down.
2136
1.58k
    To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2137
1.58k
    ToBBI.BB->removeSuccessor(&FromMBB);
2138
1.58k
  }
2139
4.73k
2140
4.73k
  for (MachineBasicBlock *Succ : FromSuccs) {
2141
4.34k
    // Fallthrough edge can't be transferred.
2142
4.34k
    if (Succ == FallThrough)
2143
2.92k
      continue;
2144
1.42k
2145
1.42k
    auto NewProb = BranchProbability::getZero();
2146
1.42k
    if (AddEdges) {
2147
18
      // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2148
18
      // which is a portion of the edge probability from FromMBB to Succ. The
2149
18
      // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2150
18
      // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2151
18
      NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2152
18
2153
18
      // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2154
18
      // only happens when if-converting a diamond CFG and FromMBB is the
2155
18
      // tail BB.  In this case FromMBB post-dominates ToBBI.BB and hence we
2156
18
      // could just use the probabilities on FromMBB's out-edges when adding
2157
18
      // new successors.
2158
18
      if (!To2FromProb.isZero())
2159
17
        NewProb *= To2FromProb;
2160
18
    }
2161
1.42k
2162
1.42k
    FromMBB.removeSuccessor(Succ);
2163
1.42k
2164
1.42k
    if (AddEdges) {
2165
18
      // If the edge from ToBBI.BB to Succ already exists, update the
2166
18
      // probability of this edge by adding NewProb to it. An example is shown
2167
18
      // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2168
18
      // don't have to set C as A's successor as it already is. We only need to
2169
18
      // update the edge probability on A->C. Note that B will not be
2170
18
      // immediately removed from A's successors. It is possible that B->D is
2171
18
      // not removed either if D is a fallthrough of B. Later the edge A->D
2172
18
      // (generated here) and B->D will be combined into one edge. To maintain
2173
18
      // correct edge probability of this combined edge, we need to set the edge
2174
18
      // probability of A->B to zero, which is already done above. The edge
2175
18
      // probability on A->D is calculated by scaling the original probability
2176
18
      // on A->B by the probability of B->D.
2177
18
      //
2178
18
      // Before ifcvt:      After ifcvt (assume B->D is kept):
2179
18
      //
2180
18
      //       A                A
2181
18
      //      /|               /|\
2182
18
      //     / B              / B|
2183
18
      //    | /|             |  ||
2184
18
      //    |/ |             |  |/
2185
18
      //    C  D             C  D
2186
18
      //
2187
18
      if (ToBBI.BB->isSuccessor(Succ))
2188
4
        ToBBI.BB->setSuccProbability(
2189
4
            find(ToBBI.BB->successors(), Succ),
2190
4
            MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2191
14
      else
2192
14
        ToBBI.BB->addSuccessor(Succ, NewProb);
2193
18
    }
2194
1.42k
  }
2195
4.73k
2196
4.73k
  // Move the now empty FromMBB out of the way to the end of the function so
2197
4.73k
  // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2198
4.73k
  MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2199
4.73k
  if (Last != &FromMBB)
2200
4.09k
    FromMBB.moveAfter(Last);
2201
4.73k
2202
4.73k
  // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2203
4.73k
  // we've done above.
2204
4.73k
  if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2205
3.15k
    ToBBI.BB->normalizeSuccProbs();
2206
4.73k
2207
4.73k
  ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2208
4.73k
  FromBBI.Predicate.clear();
2209
4.73k
2210
4.73k
  ToBBI.NonPredSize += FromBBI.NonPredSize;
2211
4.73k
  ToBBI.ExtraCost += FromBBI.ExtraCost;
2212
4.73k
  ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2213
4.73k
  FromBBI.NonPredSize = 0;
2214
4.73k
  FromBBI.ExtraCost = 0;
2215
4.73k
  FromBBI.ExtraCost2 = 0;
2216
4.73k
2217
4.73k
  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2218
4.73k
  ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2219
4.73k
  ToBBI.IsAnalyzed = false;
2220
4.73k
  FromBBI.IsAnalyzed = false;
2221
4.73k
}
2222
2223
FunctionPass *
2224
4.91k
llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
2225
4.91k
  return new IfConverter(std::move(Ftor));
2226
4.91k
}