LLVM  9.0.0svn
IfConversion.cpp
Go to the documentation of this file.
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"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Pass.h"
43 #include "llvm/Support/Debug.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;
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  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  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;
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  : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
209  }
210 
211  void getAnalysisUsage(AnalysisUsage &AU) const override {
215  }
216 
217  bool runOnMachineFunction(MachineFunction &MF) override;
218 
219  MachineFunctionProperties getRequiredProperties() const override {
222  }
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(
234  unsigned &Dups1, unsigned &Dups2,
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,
247  bool BranchUnpredicable = false) const;
248  bool RescanInstructions(
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,
275  SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
276  void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
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  BranchProbability Prediction) const {
284  return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
285  Prediction);
286  }
287 
288  bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
289  unsigned TCycle, unsigned TExtra,
290  MachineBasicBlock &FBB,
291  unsigned FCycle, unsigned FExtra,
292  BranchProbability Prediction) const {
293  return TCycle > 0 && FCycle > 0 &&
294  TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
295  Prediction);
296  }
297 
298  /// Returns true if Block ends without a terminator.
299  bool blockAlwaysFallThrough(BBInfo &BBI) const {
300  return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
301  }
302 
303  /// Used to sort if-conversion candidates.
304  static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
305  const std::unique_ptr<IfcvtToken> &C2) {
306  int Incr1 = (C1->Kind == ICDiamond)
307  ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
308  int Incr2 = (C2->Kind == ICDiamond)
309  ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
310  if (Incr1 > Incr2)
311  return true;
312  else if (Incr1 == Incr2) {
313  // Favors subsumption.
314  if (!C1->NeedSubsumption && C2->NeedSubsumption)
315  return true;
316  else if (C1->NeedSubsumption == C2->NeedSubsumption) {
317  // Favors diamond over triangle, etc.
318  if ((unsigned)C1->Kind < (unsigned)C2->Kind)
319  return true;
320  else if (C1->Kind == C2->Kind)
321  return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
322  }
323  }
324  return false;
325  }
326  };
327 
328 } // end anonymous namespace
329 
330 char IfConverter::ID = 0;
331 
333 
334 INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
336 INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
337 
338 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
339  if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
340  return false;
341 
342  const TargetSubtargetInfo &ST = MF.getSubtarget();
343  TLI = ST.getTargetLowering();
344  TII = ST.getInstrInfo();
345  TRI = ST.getRegisterInfo();
346  BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
347  MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
348  MRI = &MF.getRegInfo();
349  SchedModel.init(&ST);
350 
351  if (!TII) return false;
352 
353  PreRegAlloc = MRI->isSSA();
354 
355  bool BFChange = false;
356  if (!PreRegAlloc) {
357  // Tail merge tend to expose more if-conversion opportunities.
358  BranchFolder BF(true, false, MBFI, *MBPI);
359  BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
360  getAnalysisIfAvailable<MachineModuleInfo>());
361  }
362 
363  LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
364  << MF.getName() << "\'");
365 
366  if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
367  LLVM_DEBUG(dbgs() << " skipped\n");
368  return false;
369  }
370  LLVM_DEBUG(dbgs() << "\n");
371 
372  MF.RenumberBlocks();
373  BBAnalysis.resize(MF.getNumBlockIDs());
374 
375  std::vector<std::unique_ptr<IfcvtToken>> Tokens;
376  MadeChange = false;
377  unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
378  NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
379  while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
380  // Do an initial analysis for each basic block and find all the potential
381  // candidates to perform if-conversion.
382  bool Change = false;
383  AnalyzeBlocks(MF, Tokens);
384  while (!Tokens.empty()) {
385  std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
386  Tokens.pop_back();
387  BBInfo &BBI = Token->BBI;
388  IfcvtKind Kind = Token->Kind;
389  unsigned NumDups = Token->NumDups;
390  unsigned NumDups2 = Token->NumDups2;
391 
392  // If the block has been evicted out of the queue or it has already been
393  // marked dead (due to it being predicated), then skip it.
394  if (BBI.IsDone)
395  BBI.IsEnqueued = false;
396  if (!BBI.IsEnqueued)
397  continue;
398 
399  BBI.IsEnqueued = false;
400 
401  bool RetVal = false;
402  switch (Kind) {
403  default: llvm_unreachable("Unexpected!");
404  case ICSimple:
405  case ICSimpleFalse: {
406  bool isFalse = Kind == ICSimpleFalse;
407  if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
408  LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
409  << (Kind == ICSimpleFalse ? " false" : "")
410  << "): " << printMBBReference(*BBI.BB) << " ("
411  << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
412  : BBI.TrueBB->getNumber())
413  << ") ");
414  RetVal = IfConvertSimple(BBI, Kind);
415  LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
416  if (RetVal) {
417  if (isFalse) ++NumSimpleFalse;
418  else ++NumSimple;
419  }
420  break;
421  }
422  case ICTriangle:
423  case ICTriangleRev:
424  case ICTriangleFalse:
425  case ICTriangleFRev: {
426  bool isFalse = Kind == ICTriangleFalse;
427  bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
428  if (DisableTriangle && !isFalse && !isRev) break;
429  if (DisableTriangleR && !isFalse && isRev) break;
430  if (DisableTriangleF && isFalse && !isRev) break;
431  if (DisableTriangleFR && isFalse && isRev) break;
432  LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
433  if (isFalse)
434  LLVM_DEBUG(dbgs() << " false");
435  if (isRev)
436  LLVM_DEBUG(dbgs() << " rev");
437  LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
438  << " (T:" << BBI.TrueBB->getNumber()
439  << ",F:" << BBI.FalseBB->getNumber() << ") ");
440  RetVal = IfConvertTriangle(BBI, Kind);
441  LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
442  if (RetVal) {
443  if (isFalse) {
444  if (isRev) ++NumTriangleFRev;
445  else ++NumTriangleFalse;
446  } else {
447  if (isRev) ++NumTriangleRev;
448  else ++NumTriangle;
449  }
450  }
451  break;
452  }
453  case ICDiamond:
454  if (DisableDiamond) break;
455  LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
456  << " (T:" << BBI.TrueBB->getNumber()
457  << ",F:" << BBI.FalseBB->getNumber() << ") ");
458  RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
459  Token->TClobbersPred,
460  Token->FClobbersPred);
461  LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
462  if (RetVal) ++NumDiamonds;
463  break;
464  case ICForkedDiamond:
465  if (DisableForkedDiamond) break;
466  LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
467  << printMBBReference(*BBI.BB)
468  << " (T:" << BBI.TrueBB->getNumber()
469  << ",F:" << BBI.FalseBB->getNumber() << ") ");
470  RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
471  Token->TClobbersPred,
472  Token->FClobbersPred);
473  LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
474  if (RetVal) ++NumForkedDiamonds;
475  break;
476  }
477 
478  if (RetVal && MRI->tracksLiveness())
479  recomputeLivenessFlags(*BBI.BB);
480 
481  Change |= RetVal;
482 
483  NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
484  NumTriangleFalse + NumTriangleFRev + NumDiamonds;
485  if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
486  break;
487  }
488 
489  if (!Change)
490  break;
491  MadeChange |= Change;
492  }
493 
494  Tokens.clear();
495  BBAnalysis.clear();
496 
497  if (MadeChange && IfCvtBranchFold) {
498  BranchFolder BF(false, false, MBFI, *MBPI);
499  BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
500  getAnalysisIfAvailable<MachineModuleInfo>());
501  }
502 
503  MadeChange |= BFChange;
504  return MadeChange;
505 }
506 
507 /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
509  MachineBasicBlock *TrueBB) {
510  for (MachineBasicBlock *SuccBB : BB->successors()) {
511  if (SuccBB != TrueBB)
512  return SuccBB;
513  }
514  return nullptr;
515 }
516 
517 /// Reverse the condition of the end of the block branch. Swap block's 'true'
518 /// and 'false' successors.
519 bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
520  DebugLoc dl; // FIXME: this is nowhere
521  if (!TII->reverseBranchCondition(BBI.BrCond)) {
522  TII->removeBranch(*BBI.BB);
523  TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
524  std::swap(BBI.TrueBB, BBI.FalseBB);
525  return true;
526  }
527  return false;
528 }
529 
530 /// Returns the next block in the function blocks ordering. If it is the end,
531 /// returns NULL.
535  if (++I == E)
536  return nullptr;
537  return &*I;
538 }
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  BranchProbability Prediction) const {
545  Dups = 0;
546  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
547  return false;
548 
549  if (TrueBBI.IsBrAnalyzable)
550  return false;
551 
552  if (TrueBBI.BB->pred_size() > 1) {
553  if (TrueBBI.CannotBeCopied ||
554  !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
555  Prediction))
556  return false;
557  Dups = TrueBBI.NonPredSize;
558  }
559 
560  return true;
561 }
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  BranchProbability Prediction) const {
571  Dups = 0;
572  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
573  return false;
574 
575  if (TrueBBI.BB->pred_size() > 1) {
576  if (TrueBBI.CannotBeCopied)
577  return false;
578 
579  unsigned Size = TrueBBI.NonPredSize;
580  if (TrueBBI.IsBrAnalyzable) {
581  if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
582  // Ends with an unconditional branch. It will be removed.
583  --Size;
584  else {
585  MachineBasicBlock *FExit = FalseBranch
586  ? TrueBBI.TrueBB : TrueBBI.FalseBB;
587  if (FExit)
588  // Require a conditional branch
589  ++Size;
590  }
591  }
592  if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
593  return false;
594  Dups = Size;
595  }
596 
597  MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
598  if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
599  MachineFunction::iterator I = TrueBBI.BB->getIterator();
600  if (++I == TrueBBI.BB->getParent()->end())
601  return false;
602  TExit = &*I;
603  }
604  return TExit && TExit == FalseBBI.BB;
605 }
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(
632  unsigned &Dups1, unsigned &Dups2,
634  bool SkipUnconditionalBranches) const {
635  while (TIB != TIE && FIB != FIE) {
636  // Skip dbg_value instructions. These do not count.
637  TIB = skipDebugInstructionsForward(TIB, TIE);
638  FIB = skipDebugInstructionsForward(FIB, FIE);
639  if (TIB == TIE || FIB == FIE)
640  break;
641  if (!TIB->isIdenticalTo(*FIB))
642  break;
643  // A pred-clobbering instruction in the shared portion prevents
644  // if-conversion.
645  std::vector<MachineOperand> PredDefs;
646  if (TII->DefinesPredicate(*TIB, PredDefs))
647  return false;
648  // If we get all the way to the branch instructions, don't count them.
649  if (!TIB->isBranch())
650  ++Dups1;
651  ++TIB;
652  ++FIB;
653  }
654 
655  // Check for already containing all of the block.
656  if (TIB == TIE || FIB == FIE)
657  return true;
658  // Now, in preparation for counting duplicate instructions at the ends of the
659  // blocks, switch to reverse_iterators. Note that getReverse() returns an
660  // iterator that points to the same instruction, unlike std::reverse_iterator.
661  // We have to do our own shifting so that we get the same range.
662  MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
663  MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
664  const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
665  const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
666 
667  if (!TBB.succ_empty() || !FBB.succ_empty()) {
668  if (SkipUnconditionalBranches) {
669  while (RTIE != RTIB && RTIE->isUnconditionalBranch())
670  ++RTIE;
671  while (RFIE != RFIB && RFIE->isUnconditionalBranch())
672  ++RFIE;
673  }
674  }
675 
676  // Count duplicate instructions at the ends of the blocks.
677  while (RTIE != RTIB && RFIE != RFIB) {
678  // Skip dbg_value instructions. These do not count.
679  // Note that these are reverse iterators going forward.
680  RTIE = skipDebugInstructionsForward(RTIE, RTIB);
681  RFIE = skipDebugInstructionsForward(RFIE, RFIB);
682  if (RTIE == RTIB || RFIE == RFIB)
683  break;
684  if (!RTIE->isIdenticalTo(*RFIE))
685  break;
686  // We have to verify that any branch instructions are the same, and then we
687  // don't count them toward the # of duplicate instructions.
688  if (!RTIE->isBranch())
689  ++Dups2;
690  ++RTIE;
691  ++RFIE;
692  }
693  TIE = std::next(RTIE.getReverse());
694  FIE = std::next(RFIE.getReverse());
695  return true;
696 }
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(
710  BBInfo &TrueBBI, BBInfo &FalseBBI) const {
711  bool BranchUnpredicable = true;
712  TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
713  ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
714  if (TrueBBI.IsUnpredicable)
715  return false;
716  ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
717  if (FalseBBI.IsUnpredicable)
718  return false;
719  if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
720  return false;
721  return true;
722 }
723 
724 #ifndef NDEBUG
726  MachineBasicBlock *MBB1,
727  MachineBasicBlock *MBB2) {
729  const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
732  while (E1 != B1 && 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  BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
775  Dups1 = Dups2 = 0;
776  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
777  FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
778  return false;
779 
780  if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
781  return false;
782  // Don't IfConvert blocks that can't be folded into their predecessor.
783  if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
784  return false;
785 
786  // This function is specifically looking for conditional tails, as
787  // unconditional tails are already handled by the standard diamond case.
788  if (TrueBBI.BrCond.size() == 0 ||
789  FalseBBI.BrCond.size() == 0)
790  return false;
791 
792  MachineBasicBlock *TT = TrueBBI.TrueBB;
793  MachineBasicBlock *TF = TrueBBI.FalseBB;
794  MachineBasicBlock *FT = FalseBBI.TrueBB;
795  MachineBasicBlock *FF = FalseBBI.FalseBB;
796 
797  if (!TT)
798  TT = getNextBlock(*TrueBBI.BB);
799  if (!TF)
800  TF = getNextBlock(*TrueBBI.BB);
801  if (!FT)
802  FT = getNextBlock(*FalseBBI.BB);
803  if (!FF)
804  FF = getNextBlock(*FalseBBI.BB);
805 
806  if (!TT || !TF)
807  return false;
808 
809  // Check successors. If they don't match, bail.
810  if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
811  return false;
812 
813  bool FalseReversed = false;
814  if (TF == FT && TT == FF) {
815  // If the branches are opposing, but we can't reverse, don't do it.
816  if (!FalseBBI.IsBrReversible)
817  return false;
818  FalseReversed = true;
819  reverseBranchCondition(FalseBBI);
820  }
821  auto UnReverseOnExit = make_scope_exit([&]() {
822  if (FalseReversed)
823  reverseBranchCondition(FalseBBI);
824  });
825 
826  // Count duplicate instructions at the beginning of the true and false blocks.
827  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
828  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
829  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
830  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
831  if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
832  *TrueBBI.BB, *FalseBBI.BB,
833  /* SkipUnconditionalBranches */ true))
834  return false;
835 
836  TrueBBICalc.BB = TrueBBI.BB;
837  FalseBBICalc.BB = FalseBBI.BB;
838  if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
839  return false;
840 
841  // The size is used to decide whether to if-convert, and the shared portions
842  // are subtracted off. Because of the subtraction, we just use the size that
843  // was calculated by the original ScanInstructions, as it is correct.
844  TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
845  FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
846  return true;
847 }
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  BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
855  Dups1 = Dups2 = 0;
856  if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
857  FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
858  return false;
859 
860  MachineBasicBlock *TT = TrueBBI.TrueBB;
861  MachineBasicBlock *FT = FalseBBI.TrueBB;
862 
863  if (!TT && blockAlwaysFallThrough(TrueBBI))
864  TT = getNextBlock(*TrueBBI.BB);
865  if (!FT && blockAlwaysFallThrough(FalseBBI))
866  FT = getNextBlock(*FalseBBI.BB);
867  if (TT != FT)
868  return false;
869  if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
870  return false;
871  if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
872  return false;
873 
874  // FIXME: Allow true block to have an early exit?
875  if (TrueBBI.FalseBB || FalseBBI.FalseBB)
876  return false;
877 
878  // Count duplicate instructions at the beginning and end of the true and
879  // false blocks.
880  // Skip unconditional branches only if we are considering an analyzable
881  // diamond. Otherwise the branches must be the same.
882  bool SkipUnconditionalBranches =
883  TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
884  MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
885  MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
886  MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
887  MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
888  if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
889  *TrueBBI.BB, *FalseBBI.BB,
890  SkipUnconditionalBranches))
891  return false;
892 
893  TrueBBICalc.BB = TrueBBI.BB;
894  FalseBBICalc.BB = FalseBBI.BB;
895  if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
896  return false;
897  // The size is used to decide whether to if-convert, and the shared portions
898  // are subtracted off. Because of the subtraction, we just use the size that
899  // was calculated by the original ScanInstructions, as it is correct.
900  TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
901  FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
902  return true;
903 }
904 
905 /// AnalyzeBranches - Look at the branches at the end of a block to determine if
906 /// the block is predicable.
907 void IfConverter::AnalyzeBranches(BBInfo &BBI) {
908  if (BBI.IsDone)
909  return;
910 
911  BBI.TrueBB = BBI.FalseBB = nullptr;
912  BBI.BrCond.clear();
913  BBI.IsBrAnalyzable =
914  !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
915  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
916  BBI.IsBrReversible = (RevCond.size() == 0) ||
917  !TII->reverseBranchCondition(RevCond);
918  BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
919 
920  if (BBI.BrCond.size()) {
921  // No false branch. This BB must end with a conditional branch and a
922  // fallthrough.
923  if (!BBI.FalseBB)
924  BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
925  if (!BBI.FalseBB) {
926  // Malformed bcc? True and false blocks are the same?
927  BBI.IsUnpredicable = true;
928  }
929  }
930 }
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,
940  bool BranchUnpredicable) const {
941  if (BBI.IsDone || BBI.IsUnpredicable)
942  return;
943 
944  bool AlreadyPredicated = !BBI.Predicate.empty();
945 
946  BBI.NonPredSize = 0;
947  BBI.ExtraCost = 0;
948  BBI.ExtraCost2 = 0;
949  BBI.ClobbersPred = false;
950  for (MachineInstr &MI : make_range(Begin, End)) {
951  if (MI.isDebugInstr())
952  continue;
953 
954  // It's unsafe to duplicate convergent instructions in this context, so set
955  // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
956  // following CFG, which is subject to our "simple" transformation.
957  //
958  // BB0 // if (c1) goto BB1; else goto BB2;
959  // / \
960  // BB1 |
961  // | BB2 // if (c2) goto TBB; else goto FBB;
962  // | / |
963  // | / |
964  // TBB |
965  // | |
966  // | FBB
967  // |
968  // exit
969  //
970  // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
971  // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
972  // TBB contains a convergent instruction. This is safe iff doing so does
973  // not add a control-flow dependency to the convergent instruction -- i.e.,
974  // it's safe iff the set of control flows that leads us to the convergent
975  // instruction does not get smaller after the transformation.
976  //
977  // Originally we executed TBB if c1 || c2. After the transformation, there
978  // are two copies of TBB's instructions. We get to the first if c1, and we
979  // get to the second if !c1 && c2.
980  //
981  // There are clearly fewer ways to satisfy the condition "c1" than
982  // "c1 || c2". Since we've shrunk the set of control flows which lead to
983  // our convergent instruction, the transformation is unsafe.
984  if (MI.isNotDuplicable() || MI.isConvergent())
985  BBI.CannotBeCopied = true;
986 
987  bool isPredicated = TII->isPredicated(MI);
988  bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
989 
990  if (BranchUnpredicable && MI.isBranch()) {
991  BBI.IsUnpredicable = true;
992  return;
993  }
994 
995  // A conditional branch is not predicable, but it may be eliminated.
996  if (isCondBr)
997  continue;
998 
999  if (!isPredicated) {
1000  BBI.NonPredSize++;
1001  unsigned ExtraPredCost = TII->getPredicationCost(MI);
1002  unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
1003  if (NumCycles > 1)
1004  BBI.ExtraCost += NumCycles-1;
1005  BBI.ExtraCost2 += ExtraPredCost;
1006  } else if (!AlreadyPredicated) {
1007  // FIXME: This instruction is already predicated before the
1008  // if-conversion pass. It's probably something like a conditional move.
1009  // Mark this block unpredicable for now.
1010  BBI.IsUnpredicable = true;
1011  return;
1012  }
1013 
1014  if (BBI.ClobbersPred && !isPredicated) {
1015  // Predicate modification instruction should end the block (except for
1016  // already predicated instructions and end of block branches).
1017  // Predicate may have been modified, the subsequent (currently)
1018  // unpredicated instructions cannot be correctly predicated.
1019  BBI.IsUnpredicable = true;
1020  return;
1021  }
1022 
1023  // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1024  // still potentially predicable.
1025  std::vector<MachineOperand> PredDefs;
1026  if (TII->DefinesPredicate(MI, PredDefs))
1027  BBI.ClobbersPred = true;
1028 
1029  if (!TII->isPredicable(MI)) {
1030  BBI.IsUnpredicable = true;
1031  return;
1032  }
1033  }
1034 }
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,
1047  bool isTriangle, bool RevBranch,
1048  bool hasCommonTail) {
1049  // If the block is dead or unpredicable, then it cannot be predicated.
1050  // Two blocks may share a common unpredicable tail, but this doesn't prevent
1051  // them from being if-converted. The non-shared portion is assumed to have
1052  // been checked
1053  if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1054  return false;
1055 
1056  // If it is already predicated but we couldn't analyze its terminator, the
1057  // latter might fallthrough, but we can't determine where to.
1058  // Conservatively avoid if-converting again.
1059  if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1060  return false;
1061 
1062  // If it is already predicated, check if the new predicate subsumes
1063  // its predicate.
1064  if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
1065  return false;
1066 
1067  if (!hasCommonTail && BBI.BrCond.size()) {
1068  if (!isTriangle)
1069  return false;
1070 
1071  // Test predicate subsumption.
1072  SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1073  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1074  if (RevBranch) {
1075  if (TII->reverseBranchCondition(Cond))
1076  return false;
1077  }
1078  if (TII->reverseBranchCondition(RevPred) ||
1079  !TII->SubsumesPredicate(Cond, RevPred))
1080  return false;
1081  }
1082 
1083  return true;
1084 }
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  MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1090  struct BBState {
1091  BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
1092  MachineBasicBlock *MBB;
1093 
1094  /// This flag is true if MBB's successors have been analyzed.
1095  bool SuccsAnalyzed;
1096  };
1097 
1098  // Push MBB to the stack.
1099  SmallVector<BBState, 16> BBStack(1, MBB);
1100 
1101  while (!BBStack.empty()) {
1102  BBState &State = BBStack.back();
1103  MachineBasicBlock *BB = State.MBB;
1104  BBInfo &BBI = BBAnalysis[BB->getNumber()];
1105 
1106  if (!State.SuccsAnalyzed) {
1107  if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1108  BBStack.pop_back();
1109  continue;
1110  }
1111 
1112  BBI.BB = BB;
1113  BBI.IsBeingAnalyzed = true;
1114 
1115  AnalyzeBranches(BBI);
1116  MachineBasicBlock::iterator Begin = BBI.BB->begin();
1117  MachineBasicBlock::iterator End = BBI.BB->end();
1118  ScanInstructions(BBI, Begin, End);
1119 
1120  // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1121  // not considered for ifcvt anymore.
1122  if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1123  BBI.IsBeingAnalyzed = false;
1124  BBI.IsAnalyzed = true;
1125  BBStack.pop_back();
1126  continue;
1127  }
1128 
1129  // Do not ifcvt if either path is a back edge to the entry block.
1130  if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1131  BBI.IsBeingAnalyzed = false;
1132  BBI.IsAnalyzed = true;
1133  BBStack.pop_back();
1134  continue;
1135  }
1136 
1137  // Do not ifcvt if true and false fallthrough blocks are the same.
1138  if (!BBI.FalseBB) {
1139  BBI.IsBeingAnalyzed = false;
1140  BBI.IsAnalyzed = true;
1141  BBStack.pop_back();
1142  continue;
1143  }
1144 
1145  // Push the False and True blocks to the stack.
1146  State.SuccsAnalyzed = true;
1147  BBStack.push_back(*BBI.FalseBB);
1148  BBStack.push_back(*BBI.TrueBB);
1149  continue;
1150  }
1151 
1152  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1153  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1154 
1155  if (TrueBBI.IsDone && FalseBBI.IsDone) {
1156  BBI.IsBeingAnalyzed = false;
1157  BBI.IsAnalyzed = true;
1158  BBStack.pop_back();
1159  continue;
1160  }
1161 
1163  RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1164  bool CanRevCond = !TII->reverseBranchCondition(RevCond);
1165 
1166  unsigned Dups = 0;
1167  unsigned Dups2 = 0;
1168  bool TNeedSub = !TrueBBI.Predicate.empty();
1169  bool FNeedSub = !FalseBBI.Predicate.empty();
1170  bool Enqueued = false;
1171 
1172  BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1173 
1174  if (CanRevCond) {
1175  BBInfo TrueBBICalc, FalseBBICalc;
1176  auto feasibleDiamond = [&]() {
1177  bool MeetsSize = MeetIfcvtSizeLimit(
1178  *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1179  TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1180  *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1181  FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1182  Prediction);
1183  bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1184  /* IsTriangle */ false, /* RevCond */ false,
1185  /* hasCommonTail */ true);
1186  bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1187  /* IsTriangle */ false, /* RevCond */ false,
1188  /* hasCommonTail */ true);
1189  return MeetsSize && TrueFeasible && FalseFeasible;
1190  };
1191 
1192  if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1193  TrueBBICalc, FalseBBICalc)) {
1194  if (feasibleDiamond()) {
1195  // Diamond:
1196  // EBB
1197  // / \_
1198  // | |
1199  // TBB FBB
1200  // \ /
1201  // TailBB
1202  // Note TailBB can be empty.
1203  Tokens.push_back(llvm::make_unique<IfcvtToken>(
1204  BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1205  (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1206  Enqueued = true;
1207  }
1208  } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1209  TrueBBICalc, FalseBBICalc)) {
1210  if (feasibleDiamond()) {
1211  // ForkedDiamond:
1212  // if TBB and FBB have a common tail that includes their conditional
1213  // branch instructions, then we can If Convert this pattern.
1214  // EBB
1215  // _/ \_
1216  // | |
1217  // TBB FBB
1218  // / \ / \
1219  // FalseBB TrueBB FalseBB
1220  //
1221  Tokens.push_back(llvm::make_unique<IfcvtToken>(
1222  BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1223  (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1224  Enqueued = true;
1225  }
1226  }
1227  }
1228 
1229  if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1230  MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1231  TrueBBI.ExtraCost2, Prediction) &&
1232  FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1233  // Triangle:
1234  // EBB
1235  // | \_
1236  // | |
1237  // | TBB
1238  // | /
1239  // FBB
1240  Tokens.push_back(
1241  llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1242  Enqueued = true;
1243  }
1244 
1245  if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1246  MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1247  TrueBBI.ExtraCost2, Prediction) &&
1248  FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
1249  Tokens.push_back(
1250  llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1251  Enqueued = true;
1252  }
1253 
1254  if (ValidSimple(TrueBBI, Dups, Prediction) &&
1255  MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1256  TrueBBI.ExtraCost2, Prediction) &&
1257  FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1258  // Simple (split, no rejoin):
1259  // EBB
1260  // | \_
1261  // | |
1262  // | TBB---> exit
1263  // |
1264  // FBB
1265  Tokens.push_back(
1266  llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1267  Enqueued = true;
1268  }
1269 
1270  if (CanRevCond) {
1271  // Try the other path...
1272  if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1273  Prediction.getCompl()) &&
1274  MeetIfcvtSizeLimit(*FalseBBI.BB,
1275  FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1276  FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1277  FeasibilityAnalysis(FalseBBI, RevCond, true)) {
1278  Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1279  FNeedSub, Dups));
1280  Enqueued = true;
1281  }
1282 
1283  if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1284  Prediction.getCompl()) &&
1285  MeetIfcvtSizeLimit(*FalseBBI.BB,
1286  FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1287  FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1288  FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
1289  Tokens.push_back(
1290  llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1291  Enqueued = true;
1292  }
1293 
1294  if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1295  MeetIfcvtSizeLimit(*FalseBBI.BB,
1296  FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1297  FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1298  FeasibilityAnalysis(FalseBBI, RevCond)) {
1299  Tokens.push_back(
1300  llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1301  Enqueued = true;
1302  }
1303  }
1304 
1305  BBI.IsEnqueued = Enqueued;
1306  BBI.IsBeingAnalyzed = false;
1307  BBI.IsAnalyzed = true;
1308  BBStack.pop_back();
1309  }
1310 }
1311 
1312 /// Analyze all blocks and find entries for all if-conversion candidates.
1313 void IfConverter::AnalyzeBlocks(
1314  MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1315  for (MachineBasicBlock &MBB : MF)
1316  AnalyzeBlock(MBB, Tokens);
1317 
1318  // Sort to favor more complex ifcvt scheme.
1319  std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
1320 }
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).
1326  MachineFunction::iterator I = std::next(PI);
1329  while (I != TI) {
1330  // Check isSuccessor to avoid case where the next block is empty, but
1331  // it's not a successor.
1332  if (I == E || !I->empty() || !PI->isSuccessor(&*I))
1333  return false;
1334  PI = I++;
1335  }
1336  // Finally see if the last I is indeed a successor to PI.
1337  return PI->isSuccessor(&*I);
1338 }
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 void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1343  for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
1344  BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1345  if (PBBI.IsDone || PBBI.BB == &MBB)
1346  continue;
1347  PBBI.IsAnalyzed = false;
1348  PBBI.IsEnqueued = false;
1349  }
1350 }
1351 
1352 /// Inserts an unconditional branch from \p MBB to \p ToMBB.
1354  const TargetInstrInfo *TII) {
1355  DebugLoc dl; // FIXME: this is nowhere
1357  TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
1358 }
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.
1363  const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
1364 
1365  // Before stepping forward past MI, remember which regs were live
1366  // before MI. This is needed to set the Undef flag only when reg is
1367  // dead.
1369  LiveBeforeMI.setUniverse(TRI->getNumRegs());
1370  for (unsigned Reg : Redefs)
1371  LiveBeforeMI.insert(Reg);
1372 
1374  Redefs.stepForward(MI, Clobbers);
1375 
1376  // Now add the implicit uses for each of the clobbered values.
1377  for (auto Clobber : Clobbers) {
1378  // FIXME: Const cast here is nasty, but better than making StepForward
1379  // take a mutable instruction instead of const.
1380  unsigned Reg = Clobber.first;
1381  MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
1382  MachineInstr *OpMI = Op.getParent();
1383  MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
1384  if (Op.isRegMask()) {
1385  // First handle regmasks. They clobber any entries in the mask which
1386  // means that we need a def for those registers.
1387  if (LiveBeforeMI.count(Reg))
1388  MIB.addReg(Reg, RegState::Implicit);
1389 
1390  // We also need to add an implicit def of this register for the later
1391  // use to read from.
1392  // For the register allocator to have allocated a register clobbered
1393  // by the call which is used later, it must be the case that
1394  // the call doesn't return.
1396  continue;
1397  }
1398  if (LiveBeforeMI.count(Reg))
1399  MIB.addReg(Reg, RegState::Implicit);
1400  else {
1401  bool HasLiveSubReg = false;
1402  for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1403  if (!LiveBeforeMI.count(*S))
1404  continue;
1405  HasLiveSubReg = true;
1406  break;
1407  }
1408  if (HasLiveSubReg)
1409  MIB.addReg(Reg, RegState::Implicit);
1410  }
1411  }
1412 }
1413 
1414 /// If convert a simple (split, no rejoin) sub-CFG.
1415 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1416  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1417  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1418  BBInfo *CvtBBI = &TrueBBI;
1419  BBInfo *NextBBI = &FalseBBI;
1420 
1421  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1422  if (Kind == ICSimpleFalse)
1423  std::swap(CvtBBI, NextBBI);
1424 
1425  MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1426  MachineBasicBlock &NextMBB = *NextBBI->BB;
1427  if (CvtBBI->IsDone ||
1428  (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1429  // Something has changed. It's no longer safe to predicate this block.
1430  BBI.IsAnalyzed = false;
1431  CvtBBI->IsAnalyzed = false;
1432  return false;
1433  }
1434 
1435  if (CvtMBB.hasAddressTaken())
1436  // Conservatively abort if-conversion if BB's address is taken.
1437  return false;
1438 
1439  if (Kind == ICSimpleFalse)
1440  if (TII->reverseBranchCondition(Cond))
1441  llvm_unreachable("Unable to reverse branch condition!");
1442 
1443  Redefs.init(*TRI);
1444 
1445  if (MRI->tracksLiveness()) {
1446  // Initialize liveins to the first BB. These are potentially redefined by
1447  // predicated instructions.
1448  Redefs.addLiveIns(CvtMBB);
1449  Redefs.addLiveIns(NextMBB);
1450  }
1451 
1452  // Remove the branches from the entry so we can add the contents of the true
1453  // block to it.
1454  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1455 
1456  if (CvtMBB.pred_size() > 1) {
1457  // Copy instructions in the true block, predicate them, and add them to
1458  // the entry block.
1459  CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1460 
1461  // Keep the CFG updated.
1462  BBI.BB->removeSuccessor(&CvtMBB, true);
1463  } else {
1464  // Predicate the instructions in the true block.
1465  PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1466 
1467  // Merge converted block into entry block. The BB to Cvt edge is removed
1468  // by MergeBlocks.
1469  MergeBlocks(BBI, *CvtBBI);
1470  }
1471 
1472  bool IterIfcvt = true;
1473  if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1474  InsertUncondBranch(*BBI.BB, NextMBB, TII);
1475  BBI.HasFallThrough = false;
1476  // Now ifcvt'd block will look like this:
1477  // BB:
1478  // ...
1479  // t, f = cmp
1480  // if t op
1481  // b BBf
1482  //
1483  // We cannot further ifcvt this block because the unconditional branch
1484  // will have to be predicated on the new condition, that will not be
1485  // available if cmp executes.
1486  IterIfcvt = false;
1487  }
1488 
1489  // Update block info. BB can be iteratively if-converted.
1490  if (!IterIfcvt)
1491  BBI.IsDone = true;
1492  InvalidatePreds(*BBI.BB);
1493  CvtBBI->IsDone = true;
1494 
1495  // FIXME: Must maintain LiveIns.
1496  return true;
1497 }
1498 
1499 /// If convert a triangle sub-CFG.
1500 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1501  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1502  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1503  BBInfo *CvtBBI = &TrueBBI;
1504  BBInfo *NextBBI = &FalseBBI;
1505  DebugLoc dl; // FIXME: this is nowhere
1506 
1507  SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1508  if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1509  std::swap(CvtBBI, NextBBI);
1510 
1511  MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1512  MachineBasicBlock &NextMBB = *NextBBI->BB;
1513  if (CvtBBI->IsDone ||
1514  (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
1515  // Something has changed. It's no longer safe to predicate this block.
1516  BBI.IsAnalyzed = false;
1517  CvtBBI->IsAnalyzed = false;
1518  return false;
1519  }
1520 
1521  if (CvtMBB.hasAddressTaken())
1522  // Conservatively abort if-conversion if BB's address is taken.
1523  return false;
1524 
1525  if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1526  if (TII->reverseBranchCondition(Cond))
1527  llvm_unreachable("Unable to reverse branch condition!");
1528 
1529  if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1530  if (reverseBranchCondition(*CvtBBI)) {
1531  // BB has been changed, modify its predecessors (except for this
1532  // one) so they don't get ifcvt'ed based on bad intel.
1533  for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
1534  if (PBB == BBI.BB)
1535  continue;
1536  BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1537  if (PBBI.IsEnqueued) {
1538  PBBI.IsAnalyzed = false;
1539  PBBI.IsEnqueued = false;
1540  }
1541  }
1542  }
1543  }
1544 
1545  // Initialize liveins to the first BB. These are potentially redefined by
1546  // predicated instructions.
1547  Redefs.init(*TRI);
1548  if (MRI->tracksLiveness()) {
1549  Redefs.addLiveIns(CvtMBB);
1550  Redefs.addLiveIns(NextMBB);
1551  }
1552 
1553  bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1554  BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1555 
1556  if (HasEarlyExit) {
1557  // Get probabilities before modifying CvtMBB and BBI.BB.
1558  CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1559  CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1560  BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1561  BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
1562  }
1563 
1564  // Remove the branches from the entry so we can add the contents of the true
1565  // block to it.
1566  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1567 
1568  if (CvtMBB.pred_size() > 1) {
1569  // Copy instructions in the true block, predicate them, and add them to
1570  // the entry block.
1571  CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1572  } else {
1573  // Predicate the 'true' block after removing its branch.
1574  CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
1575  PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
1576 
1577  // Now merge the entry of the triangle with the true block.
1578  MergeBlocks(BBI, *CvtBBI, false);
1579  }
1580 
1581  // Keep the CFG updated.
1582  BBI.BB->removeSuccessor(&CvtMBB, true);
1583 
1584  // If 'true' block has a 'false' successor, add an exit branch to it.
1585  if (HasEarlyExit) {
1586  SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1587  CvtBBI->BrCond.end());
1588  if (TII->reverseBranchCondition(RevCond))
1589  llvm_unreachable("Unable to reverse branch condition!");
1590 
1591  // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1592  // NewNext = New_Prob(BBI.BB, NextMBB) =
1593  // Prob(BBI.BB, NextMBB) +
1594  // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
1595  // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1596  // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1597  auto NewTrueBB = getNextBlock(*BBI.BB);
1598  auto NewNext = BBNext + BBCvt * CvtNext;
1599  auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
1600  if (NewTrueBBIter != BBI.BB->succ_end())
1601  BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1602 
1603  auto NewFalse = BBCvt * CvtFalse;
1604  TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1605  BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1606  }
1607 
1608  // Merge in the 'false' block if the 'false' block has no other
1609  // predecessors. Otherwise, add an unconditional branch to 'false'.
1610  bool FalseBBDead = false;
1611  bool IterIfcvt = true;
1612  bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
1613  if (!isFallThrough) {
1614  // Only merge them if the true block does not fallthrough to the false
1615  // block. By not merging them, we make it possible to iteratively
1616  // ifcvt the blocks.
1617  if (!HasEarlyExit &&
1618  NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1619  !NextMBB.hasAddressTaken()) {
1620  MergeBlocks(BBI, *NextBBI);
1621  FalseBBDead = true;
1622  } else {
1623  InsertUncondBranch(*BBI.BB, NextMBB, TII);
1624  BBI.HasFallThrough = false;
1625  }
1626  // Mixed predicated and unpredicated code. This cannot be iteratively
1627  // predicated.
1628  IterIfcvt = false;
1629  }
1630 
1631  // Update block info. BB can be iteratively if-converted.
1632  if (!IterIfcvt)
1633  BBI.IsDone = true;
1634  InvalidatePreds(*BBI.BB);
1635  CvtBBI->IsDone = true;
1636  if (FalseBBDead)
1637  NextBBI->IsDone = true;
1638 
1639  // FIXME: Must maintain LiveIns.
1640  return true;
1641 }
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  bool RemoveBranch, bool MergeAddEdges) {
1659 
1660  if (TrueBBI.IsDone || FalseBBI.IsDone ||
1661  TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1662  // Something has changed. It's no longer safe to predicate these blocks.
1663  BBI.IsAnalyzed = false;
1664  TrueBBI.IsAnalyzed = false;
1665  FalseBBI.IsAnalyzed = false;
1666  return false;
1667  }
1668 
1669  if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1670  // Conservatively abort if-conversion if either BB has its address taken.
1671  return false;
1672 
1673  // Put the predicated instructions from the 'true' block before the
1674  // instructions from the 'false' block, unless the true block would clobber
1675  // the predicate, in which case, do the opposite.
1676  BBInfo *BBI1 = &TrueBBI;
1677  BBInfo *BBI2 = &FalseBBI;
1678  SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1679  if (TII->reverseBranchCondition(RevCond))
1680  llvm_unreachable("Unable to reverse branch condition!");
1681  SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1682  SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1683 
1684  // Figure out the more profitable ordering.
1685  bool DoSwap = false;
1686  if (TClobbersPred && !FClobbersPred)
1687  DoSwap = true;
1688  else if (!TClobbersPred && !FClobbersPred) {
1689  if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1690  DoSwap = true;
1691  } else if (TClobbersPred && FClobbersPred)
1692  llvm_unreachable("Predicate info cannot be clobbered by both sides.");
1693  if (DoSwap) {
1694  std::swap(BBI1, BBI2);
1695  std::swap(Cond1, Cond2);
1696  }
1697 
1698  // Remove the conditional branch from entry to the blocks.
1699  BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1700 
1701  MachineBasicBlock &MBB1 = *BBI1->BB;
1702  MachineBasicBlock &MBB2 = *BBI2->BB;
1703 
1704  // Initialize the Redefs:
1705  // - BB2 live-in regs need implicit uses before being redefined by BB1
1706  // instructions.
1707  // - BB1 live-out regs need implicit uses before being redefined by BB2
1708  // instructions. We start with BB1 live-ins so we have the live-out regs
1709  // after tracking the BB1 instructions.
1710  Redefs.init(*TRI);
1711  if (MRI->tracksLiveness()) {
1712  Redefs.addLiveIns(MBB1);
1713  Redefs.addLiveIns(MBB2);
1714  }
1715 
1716  // Remove the duplicated instructions at the beginnings of both paths.
1717  // Skip dbg_value instructions.
1720  BBI1->NonPredSize -= NumDups1;
1721  BBI2->NonPredSize -= NumDups1;
1722 
1723  // Skip past the dups on each side separately since there may be
1724  // differing dbg_value entries. NumDups1 can include a "return"
1725  // instruction, if it's not marked as "branch".
1726  for (unsigned i = 0; i < NumDups1; ++DI1) {
1727  if (DI1 == MBB1.end())
1728  break;
1729  if (!DI1->isDebugInstr())
1730  ++i;
1731  }
1732  while (NumDups1 != 0) {
1733  ++DI2;
1734  if (DI2 == MBB2.end())
1735  break;
1736  if (!DI2->isDebugInstr())
1737  --NumDups1;
1738  }
1739 
1740  if (MRI->tracksLiveness()) {
1741  for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1743  Redefs.stepForward(MI, Dummy);
1744  }
1745  }
1746 
1747  BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1748  MBB2.erase(MBB2.begin(), DI2);
1749 
1750  // The branches have been checked to match, so it is safe to remove the
1751  // branch in BB1 and rely on the copy in BB2. The complication is that
1752  // the blocks may end with a return instruction, which may or may not
1753  // be marked as "branch". If it's not, then it could be included in
1754  // "dups1", leaving the blocks potentially empty after moving the common
1755  // 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  // Remove duplicated instructions.
1763  DI1 = MBB1.end();
1764  for (unsigned i = 0; i != NumDups2; ) {
1765  // NumDups2 only counted non-dbg_value instructions, so this won't
1766  // run off the head of the list.
1767  assert(DI1 != MBB1.begin());
1768  --DI1;
1769  // skip dbg_value instructions
1770  if (!DI1->isDebugInstr())
1771  ++i;
1772  }
1773  MBB1.erase(DI1, MBB1.end());
1774 
1775  DI2 = BBI2->BB->end();
1776  // The branches have been checked to match. Skip over the branch in the false
1777  // block so that we don't try to predicate it.
1778  if (RemoveBranch)
1779  BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
1780  else {
1781  // Make DI2 point to the end of the range where the common "tail"
1782  // instructions could be found.
1783  while (DI2 != MBB2.begin()) {
1784  MachineBasicBlock::iterator Prev = std::prev(DI2);
1785  if (!Prev->isBranch() && !Prev->isDebugInstr())
1786  break;
1787  DI2 = Prev;
1788  }
1789  }
1790  while (NumDups2 != 0) {
1791  // NumDups2 only counted non-dbg_value instructions, so this won't
1792  // run off the head of the list.
1793  assert(DI2 != MBB2.begin());
1794  --DI2;
1795  // skip dbg_value instructions
1796  if (!DI2->isDebugInstr())
1797  --NumDups2;
1798  }
1799 
1800  // Remember which registers would later be defined by the false block.
1801  // This allows us not to predicate instructions in the true block that would
1802  // later be re-defined. That is, rather than
1803  // subeq r0, r1, #1
1804  // addne r0, r1, #1
1805  // generate:
1806  // sub r0, r1, #1
1807  // addne r0, r1, #1
1808  SmallSet<MCPhysReg, 4> RedefsByFalse;
1809  SmallSet<MCPhysReg, 4> ExtUses;
1810  if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1811  for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
1812  if (FI.isDebugInstr())
1813  continue;
1815  for (const MachineOperand &MO : FI.operands()) {
1816  if (!MO.isReg())
1817  continue;
1818  unsigned Reg = MO.getReg();
1819  if (!Reg)
1820  continue;
1821  if (MO.isDef()) {
1822  Defs.push_back(Reg);
1823  } else if (!RedefsByFalse.count(Reg)) {
1824  // These are defined before ctrl flow reach the 'false' instructions.
1825  // They cannot be modified by the 'true' instructions.
1826  for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1827  SubRegs.isValid(); ++SubRegs)
1828  ExtUses.insert(*SubRegs);
1829  }
1830  }
1831 
1832  for (MCPhysReg Reg : Defs) {
1833  if (!ExtUses.count(Reg)) {
1834  for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1835  SubRegs.isValid(); ++SubRegs)
1836  RedefsByFalse.insert(*SubRegs);
1837  }
1838  }
1839  }
1840  }
1841 
1842  // Predicate the 'true' block.
1843  PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
1844 
1845  // After predicating BBI1, if there is a predicated terminator in BBI1 and
1846  // a non-predicated in BBI2, then we don't want to predicate the one from
1847  // BBI2. The reason is that if we merged these blocks, we would end up with
1848  // two predicated terminators in the same block.
1849  // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
1850  // predicate them either. They were checked to be identical, and so the
1851  // same branch would happen regardless of which path was taken.
1852  if (!MBB2.empty() && (DI2 == MBB2.end())) {
1855  bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
1856  bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
1857  if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
1858  --DI2;
1859  }
1860 
1861  // Predicate the 'false' block.
1862  PredicateBlock(*BBI2, DI2, *Cond2);
1863 
1864  // Merge the true block into the entry of the diamond.
1865  MergeBlocks(BBI, *BBI1, MergeAddEdges);
1866  MergeBlocks(BBI, *BBI2, MergeAddEdges);
1867  return true;
1868 }
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  bool TClobbersPred, bool FClobbersPred) {
1876  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1877  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1878 
1879  // Save the debug location for later.
1880  DebugLoc dl;
1881  MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1882  if (TIE != TrueBBI.BB->end())
1883  dl = TIE->getDebugLoc();
1884  // Removing branches from both blocks is safe, because we have already
1885  // determined that both blocks have the same branch instructions. The branch
1886  // will be added back at the end, unpredicated.
1887  if (!IfConvertDiamondCommon(
1888  BBI, TrueBBI, FalseBBI,
1889  NumDups1, NumDups2,
1890  TClobbersPred, FClobbersPred,
1891  /* RemoveBranch */ true, /* MergeAddEdges */ true))
1892  return false;
1893 
1894  // Add back the branch.
1895  // Debug location saved above when removing the branch from BBI2
1896  TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
1897  TrueBBI.BrCond, dl);
1898 
1899  // Update block info.
1900  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1901  InvalidatePreds(*BBI.BB);
1902 
1903  // FIXME: Must maintain LiveIns.
1904  return true;
1905 }
1906 
1907 /// If convert a diamond sub-CFG.
1908 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1909  unsigned NumDups1, unsigned NumDups2,
1910  bool TClobbersPred, bool FClobbersPred) {
1911  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1912  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1913  MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1914 
1915  // True block must fall through or end with an unanalyzable terminator.
1916  if (!TailBB) {
1917  if (blockAlwaysFallThrough(TrueBBI))
1918  TailBB = FalseBBI.TrueBB;
1919  assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1920  }
1921 
1922  if (!IfConvertDiamondCommon(
1923  BBI, TrueBBI, FalseBBI,
1924  NumDups1, NumDups2,
1925  TClobbersPred, FClobbersPred,
1926  /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
1927  /* MergeAddEdges */ TailBB == nullptr))
1928  return false;
1929 
1930  // If the if-converted block falls through or unconditionally branches into
1931  // the tail block, and the tail block does not have other predecessors, then
1932  // fold the tail block in as well. Otherwise, unless it falls through to the
1933  // tail, add a unconditional branch to it.
1934  if (TailBB) {
1935  // We need to remove the edges to the true and false blocks manually since
1936  // we didn't let IfConvertDiamondCommon update the CFG.
1937  BBI.BB->removeSuccessor(TrueBBI.BB);
1938  BBI.BB->removeSuccessor(FalseBBI.BB, true);
1939 
1940  BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1941  bool CanMergeTail = !TailBBI.HasFallThrough &&
1942  !TailBBI.BB->hasAddressTaken();
1943  // The if-converted block can still have a predicated terminator
1944  // (e.g. a predicated return). If that is the case, we cannot merge
1945  // it with the tail block.
1946  MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
1947  if (TI != BBI.BB->end() && TII->isPredicated(*TI))
1948  CanMergeTail = false;
1949  // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1950  // check if there are any other predecessors besides those.
1951  unsigned NumPreds = TailBB->pred_size();
1952  if (NumPreds > 1)
1953  CanMergeTail = false;
1954  else if (NumPreds == 1 && CanMergeTail) {
1956  if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
1957  CanMergeTail = false;
1958  }
1959  if (CanMergeTail) {
1960  MergeBlocks(BBI, TailBBI);
1961  TailBBI.IsDone = true;
1962  } else {
1963  BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
1964  InsertUncondBranch(*BBI.BB, *TailBB, TII);
1965  BBI.HasFallThrough = false;
1966  }
1967  }
1968 
1969  // Update block info.
1970  BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1971  InvalidatePreds(*BBI.BB);
1972 
1973  // FIXME: Must maintain LiveIns.
1974  return true;
1975 }
1976 
1977 static bool MaySpeculate(const MachineInstr &MI,
1978  SmallSet<MCPhysReg, 4> &LaterRedefs) {
1979  bool SawStore = true;
1980  if (!MI.isSafeToMove(nullptr, SawStore))
1981  return false;
1982 
1983  for (const MachineOperand &MO : MI.operands()) {
1984  if (!MO.isReg())
1985  continue;
1986  unsigned Reg = MO.getReg();
1987  if (!Reg)
1988  continue;
1989  if (MO.isDef() && !LaterRedefs.count(Reg))
1990  return false;
1991  }
1992 
1993  return true;
1994 }
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,
2001  SmallSet<MCPhysReg, 4> *LaterRedefs) {
2002  bool AnyUnpred = false;
2003  bool MaySpec = LaterRedefs != nullptr;
2004  for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
2005  if (I.isDebugInstr() || TII->isPredicated(I))
2006  continue;
2007  // It may be possible not to predicate an instruction if it's the 'true'
2008  // side of a diamond and the 'false' side may re-define the instruction's
2009  // defs.
2010  if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
2011  AnyUnpred = true;
2012  continue;
2013  }
2014  // If any instruction is predicated, then every instruction after it must
2015  // be predicated.
2016  MaySpec = false;
2017  if (!TII->PredicateInstruction(I, Cond)) {
2018 #ifndef NDEBUG
2019  dbgs() << "Unable to predicate " << I << "!\n";
2020 #endif
2021  llvm_unreachable(nullptr);
2022  }
2023 
2024  // If the predicated instruction now redefines a register as the result of
2025  // if-conversion, add an implicit kill.
2026  UpdatePredRedefs(I, Redefs);
2027  }
2028 
2029  BBI.Predicate.append(Cond.begin(), Cond.end());
2030 
2031  BBI.IsAnalyzed = false;
2032  BBI.NonPredSize = 0;
2033 
2034  ++NumIfConvBBs;
2035  if (AnyUnpred)
2036  ++NumUnpred;
2037 }
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,
2043  bool IgnoreBr) {
2044  MachineFunction &MF = *ToBBI.BB->getParent();
2045 
2046  MachineBasicBlock &FromMBB = *FromBBI.BB;
2047  for (MachineInstr &I : FromMBB) {
2048  // Do not copy the end of the block branches.
2049  if (IgnoreBr && I.isBranch())
2050  break;
2051 
2053  ToBBI.BB->insert(ToBBI.BB->end(), MI);
2054  ToBBI.NonPredSize++;
2055  unsigned ExtraPredCost = TII->getPredicationCost(I);
2056  unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
2057  if (NumCycles > 1)
2058  ToBBI.ExtraCost += NumCycles-1;
2059  ToBBI.ExtraCost2 += ExtraPredCost;
2060 
2061  if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
2062  if (!TII->PredicateInstruction(*MI, Cond)) {
2063 #ifndef NDEBUG
2064  dbgs() << "Unable to predicate " << I << "!\n";
2065 #endif
2066  llvm_unreachable(nullptr);
2067  }
2068  }
2069 
2070  // If the predicated instruction now redefines a register as the result of
2071  // if-conversion, add an implicit kill.
2072  UpdatePredRedefs(*MI, Redefs);
2073  }
2074 
2075  if (!IgnoreBr) {
2076  std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2077  FromMBB.succ_end());
2078  MachineBasicBlock *NBB = getNextBlock(FromMBB);
2079  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2080 
2081  for (MachineBasicBlock *Succ : Succs) {
2082  // Fallthrough edge can't be transferred.
2083  if (Succ == FallThrough)
2084  continue;
2085  ToBBI.BB->addSuccessor(Succ);
2086  }
2087  }
2088 
2089  ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2090  ToBBI.Predicate.append(Cond.begin(), Cond.end());
2091 
2092  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2093  ToBBI.IsAnalyzed = false;
2094 
2095  ++NumDupBBs;
2096 }
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 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
2104  MachineBasicBlock &FromMBB = *FromBBI.BB;
2105  assert(!FromMBB.hasAddressTaken() &&
2106  "Removing a BB whose address is taken!");
2107 
2108  // In case FromMBB contains terminators (e.g. return instruction),
2109  // first move the non-terminator instructions, then the terminators.
2111  MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
2112  ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2113 
2114  // If FromBB has non-predicated terminator we should copy it at the end.
2115  if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
2116  ToTI = ToBBI.BB->end();
2117  ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2118 
2119  // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2120  // unknown probabilities into known ones.
2121  // FIXME: This usage is too tricky and in the future we would like to
2122  // eliminate all unknown probabilities in MBB.
2123  if (ToBBI.IsBrAnalyzable)
2124  ToBBI.BB->normalizeSuccProbs();
2125 
2126  SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2127  FromMBB.succ_end());
2128  MachineBasicBlock *NBB = getNextBlock(FromMBB);
2129  MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
2130  // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2131  // AddEdges is true and FromMBB is a successor of ToBBI.BB.
2132  auto To2FromProb = BranchProbability::getZero();
2133  if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2134  // Remove the old edge but remember the edge probability so we can calculate
2135  // the correct weights on the new edges being added further down.
2136  To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
2137  ToBBI.BB->removeSuccessor(&FromMBB);
2138  }
2139 
2140  for (MachineBasicBlock *Succ : FromSuccs) {
2141  // Fallthrough edge can't be transferred.
2142  if (Succ == FallThrough)
2143  continue;
2144 
2145  auto NewProb = BranchProbability::getZero();
2146  if (AddEdges) {
2147  // Calculate the edge probability for the edge from ToBBI.BB to Succ,
2148  // which is a portion of the edge probability from FromMBB to Succ. The
2149  // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
2150  // FromBBI is a successor of ToBBI.BB. See comment below for exception).
2151  NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
2152 
2153  // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2154  // only happens when if-converting a diamond CFG and FromMBB is the
2155  // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2156  // could just use the probabilities on FromMBB's out-edges when adding
2157  // new successors.
2158  if (!To2FromProb.isZero())
2159  NewProb *= To2FromProb;
2160  }
2161 
2162  FromMBB.removeSuccessor(Succ);
2163 
2164  if (AddEdges) {
2165  // If the edge from ToBBI.BB to Succ already exists, update the
2166  // probability of this edge by adding NewProb to it. An example is shown
2167  // below, in which A is ToBBI.BB and B is FromMBB. In this case we
2168  // don't have to set C as A's successor as it already is. We only need to
2169  // update the edge probability on A->C. Note that B will not be
2170  // immediately removed from A's successors. It is possible that B->D is
2171  // not removed either if D is a fallthrough of B. Later the edge A->D
2172  // (generated here) and B->D will be combined into one edge. To maintain
2173  // correct edge probability of this combined edge, we need to set the edge
2174  // probability of A->B to zero, which is already done above. The edge
2175  // probability on A->D is calculated by scaling the original probability
2176  // on A->B by the probability of B->D.
2177  //
2178  // Before ifcvt: After ifcvt (assume B->D is kept):
2179  //
2180  // A A
2181  // /| /|\
2182  // / B / B|
2183  // | /| | ||
2184  // |/ | | |/
2185  // C D C D
2186  //
2187  if (ToBBI.BB->isSuccessor(Succ))
2188  ToBBI.BB->setSuccProbability(
2189  find(ToBBI.BB->successors(), Succ),
2190  MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
2191  else
2192  ToBBI.BB->addSuccessor(Succ, NewProb);
2193  }
2194  }
2195 
2196  // Move the now empty FromMBB out of the way to the end of the function so
2197  // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2198  MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2199  if (Last != &FromMBB)
2200  FromMBB.moveAfter(Last);
2201 
2202  // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2203  // we've done above.
2204  if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2205  ToBBI.BB->normalizeSuccProbs();
2206 
2207  ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2208  FromBBI.Predicate.clear();
2209 
2210  ToBBI.NonPredSize += FromBBI.NonPredSize;
2211  ToBBI.ExtraCost += FromBBI.ExtraCost;
2212  ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2213  FromBBI.NonPredSize = 0;
2214  FromBBI.ExtraCost = 0;
2215  FromBBI.ExtraCost2 = 0;
2216 
2217  ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2218  ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2219  ToBBI.IsAnalyzed = false;
2220  FromBBI.IsAnalyzed = false;
2221 }
2222 
2223 FunctionPass *
2225  return new IfConverter(std::move(Ftor));
2226 }
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BranchProbability getCompl() const
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs)
Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all values defined in MI whic...
virtual bool DefinesPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred) const
If the specified instruction defines any predicate or condition code register(s) used for predication...
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Definition: SparseSet.h:249
static cl::opt< bool > DisableDiamond("disable-ifcvt-diamond", cl::init(false), cl::Hidden)
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static bool MaySpeculate(const MachineInstr &MI, SmallSet< MCPhysReg, 4 > &LaterRedefs)
static cl::opt< bool > DisableForkedDiamond("disable-ifcvt-forked-diamond", cl::init(false), cl::Hidden)
static cl::opt< bool > DisableTriangleFR("disable-ifcvt-triangle-false-rev", cl::init(false), cl::Hidden)
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned Reg
virtual const TargetLowering * getTargetLowering() const
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:58
FunctionPass * createIfConverter(std::function< bool(const MachineFunction &)> Ftor)
STATISTIC(NumFunctions, "Total number of functions")
void moveAfter(MachineBasicBlock *NewBefore)
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
static cl::opt< bool > DisableSimple("disable-ifcvt-simple", cl::init(false), cl::Hidden)
static BranchProbability getOne()
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
iterator_range< succ_iterator > successors()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Definition: BitVector.h:937
bool OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineModuleInfo *mmi, MachineLoopInfo *mli=nullptr, bool AfterPlacement=false)
Perhaps branch folding, tail merging and other CFG optimizations on the given function.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise. ...
Definition: SparseSet.h:235
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
void initializeIfConverterPass(PassRegistry &)
#define DEBUG_TYPE
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const
Return true if it&#39;s profitable to predicate instructions with accumulated instruction latency of "Num...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
static MachineBasicBlock * getNextBlock(MachineBasicBlock &MBB)
Returns the next block in the function blocks ordering.
reverse_iterator rend()
reverse_iterator rbegin()
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
TargetInstrInfo - Interface to description of machine instruction set.
static cl::opt< bool > DisableTriangleR("disable-ifcvt-triangle-rev", cl::init(false), cl::Hidden)
Early If Converter
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
BB has a fallthrough. Find its &#39;false&#39; successor given its &#39;true&#39; successor.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
unsigned const MachineRegisterInfo * MRI
virtual unsigned getPredicationCost(const MachineInstr &MI) const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void addLiveIns(const MachineBasicBlock &MBB)
Adds all live-in registers of basic block MBB.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
static cl::opt< bool > DisableTriangleF("disable-ifcvt-triangle-false", cl::init(false), cl::Hidden)
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
Definition: LivePhysRegs.h:66
Represent the analysis usage information of a pass.
static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB)
Returns true either if ToMBB is the next block after MBB or that all the intervening blocks are empty...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
self_iterator getIterator()
Definition: ilist_node.h:81
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
Definition: SparseSet.h:155
iterator_range< pred_iterator > predecessors()
std::vector< MachineBasicBlock * >::iterator pred_iterator
void init(const TargetSubtargetInfo *TSInfo)
Initialize the machine model for instruction scheduling.
virtual bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Pred) const
Convert the instruction into a predicated instruction.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
bool isDebugInstr() const
Definition: MachineInstr.h:998
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
static cl::opt< bool > DisableTriangle("disable-ifcvt-triangle", cl::init(false), cl::Hidden)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:47
virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, BranchProbability Probability) const
Return true if it&#39;s profitable for if-converter to duplicate instructions of specified accumulated in...
static cl::opt< int > IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden)
unsigned pred_size() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
virtual bool isPredicable(const MachineInstr &MI) const
Return true if the specified instruction can be predicated.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
bool isPredicated(MCInstrInfo const &MCII, MCInst const &MCI)
IterT skipDebugInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
TargetSubtargetInfo - Generic base class for all target subtargets.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
virtual bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const
Returns true if the first specified predicate subsumes the second, e.g.
static cl::opt< int > IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden)
SparseSet - Fast set implmentation for objects that can be identified by small unsigned keys...
Definition: SparseSet.h:123
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:48
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static cl::opt< bool > IfCvtBranchFold("ifcvt-branch-fold", cl::init(true), cl::Hidden)
char & IfConverterID
IfConverter - This pass performs machine code if conversion.
#define I(x, y, z)
Definition: MD5.cpp:58
static cl::opt< bool > DisableSimpleF("disable-ifcvt-simple-false", cl::init(false), cl::Hidden)
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
uint32_t Size
Definition: Profile.cpp:46
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
const unsigned Kind
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB, const TargetInstrInfo *TII)
Inserts an unconditional branch from MBB to ToMBB.
This class keeps track of branch frequencies of newly created blocks and tail-merged blocks...
print Print MemDeps of function
IRTranslator LLVM IR MI
static BranchProbability getZero()
void stepForward(const MachineInstr &MI, SmallVectorImpl< std::pair< MCPhysReg, const MachineOperand *>> &Clobbers)
Simulates liveness when stepping forward over an instruction(bundle).
#define LLVM_DEBUG(X)
Definition: Debug.h:122
void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
reverse_iterator rbegin()
virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB, MachineBasicBlock &FMBB) const
Return true if it&#39;s profitable to unpredicate one side of a &#39;diamond&#39;, i.e.
bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const
Return true if it is safe to move this instruction.
Properties which a MachineFunction may have at a given point in time.
This file describes how to lower LLVM code to machine code.
static void verifySameBranchInstructions(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2)
static cl::opt< int > IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164