blob: 9d53d7bda23748fe8f186e653e70adf4cab05c1f [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000020#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000021#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000022#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000027#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000028#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000029#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000036#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000037#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000038
Evan Chengf5e53a52007-05-16 02:00:57 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "ifcvt"
42
Chris Lattner769c86b2008-01-07 05:40:58 +000043// Hidden options for help debugging.
44static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
45static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000047static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000049static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000051static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000053static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000054 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000055static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000056 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000057static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000058 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000059static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000060 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000061static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
62 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000063
Evan Cheng2117d1f2007-06-09 01:03:43 +000064STATISTIC(NumSimple, "Number of simple if-conversions performed");
65STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
66STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000067STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000068STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
69STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
70STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
71STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000072STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000073STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000074
75namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000076 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000077 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000078 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000079 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000080 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
81 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000082 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000083 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000084 ICTriangle, // BB is entry of a triangle sub-CFG.
Diana Picus68be1eb2016-08-14 02:10:18 +000085 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000086 };
87
Matthias Braun2c931792016-08-17 02:51:57 +000088 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +000089 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000090 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000091 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000092 /// diamond shape), its size, whether it's predicable, and whether any
93 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000094 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000095 /// IsDone - True if BB is not to be considered for ifcvt.
96 /// IsBeingAnalyzed - True if BB is currently being analyzed.
97 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
98 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +000099 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000100 /// HasFallThrough - True if BB may fallthrough to the following BB.
101 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000102 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000103 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000104 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000105 /// ExtraCost - Extra cost for multi-cycle instructions.
106 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000107 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000108 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000109 /// BrCond - Conditions for end of block conditional branches.
110 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000111 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000112 bool IsDone : 1;
113 bool IsBeingAnalyzed : 1;
114 bool IsAnalyzed : 1;
115 bool IsEnqueued : 1;
116 bool IsBrAnalyzable : 1;
117 bool HasFallThrough : 1;
118 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000119 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000120 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000121 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000122 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000123 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000124 MachineBasicBlock *BB;
125 MachineBasicBlock *TrueBB;
126 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000127 SmallVector<MachineOperand, 4> BrCond;
128 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000129 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000130 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Diana Picus68be1eb2016-08-14 02:10:18 +0000131 HasFallThrough(false), IsUnpredicable(false),
132 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
133 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000134 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 };
136
Matthias Braun2c931792016-08-17 02:51:57 +0000137 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000138 /// BBI - Corresponding BBInfo.
139 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000140 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000141 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000142 /// NumDups - Number of instructions that would be duplicated due
143 /// to this if-conversion. (For diamonds, the number of
144 /// identical instructions at the beginnings of both
145 /// paths).
146 /// NumDups2 - For diamonds, the number of identical instructions
147 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000148 struct IfcvtToken {
149 BBInfo &BBI;
150 IfcvtKind Kind;
Diana Picus68be1eb2016-08-14 02:10:18 +0000151 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000152 unsigned NumDups;
153 unsigned NumDups2;
Diana Picus68be1eb2016-08-14 02:10:18 +0000154 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
155 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000156 };
157
Matthias Braun2c931792016-08-17 02:51:57 +0000158 /// Results of if-conversion feasibility analysis indexed by basic block
159 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000160 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000161 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000162
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000163 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000164 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000165 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000167 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000168
Juergen Ributzka310034e2013-12-14 06:52:56 +0000169 LivePhysRegs Redefs;
170 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000171
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000174 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000175 std::function<bool(const Function &)> PredicateFtor;
176
Evan Chengf5e53a52007-05-16 02:00:57 +0000177 public:
178 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000179 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000180 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000181 initializeIfConverterPass(*PassRegistry::getPassRegistry());
182 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000183
Craig Topper4584cd52014-03-07 09:26:03 +0000184 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000185 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000186 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000187 MachineFunctionPass::getAnalysisUsage(AU);
188 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
Craig Topper4584cd52014-03-07 09:26:03 +0000190 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000191
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
194 MachineFunctionProperties::Property::AllVRegsAllocated);
195 }
196
Evan Chengf5e53a52007-05-16 02:00:57 +0000197 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000198 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000199 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000200 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000201 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000202 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000203 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Diana Picus68be1eb2016-08-14 02:10:18 +0000205 unsigned &Dups1, unsigned &Dups2) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000206 void AnalyzeBranches(BBInfo &BBI);
207 void ScanInstructions(BBInfo &BBI,
208 MachineBasicBlock::iterator &Begin,
209 MachineBasicBlock::iterator &End) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000210 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000211 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000212 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Diana Picus68be1eb2016-08-14 02:10:18 +0000213 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000214 void AnalyzeBlocks(MachineFunction &MF,
215 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000216 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng288f1542007-06-08 22:01:07 +0000217 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000218 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
219 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000220 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
221 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000222 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000223 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000224 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000225 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000226 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000227 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000228 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000229 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000230
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
232 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000233 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000234 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000235 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000236 }
237
Evan Chengdebf9c52010-11-03 00:45:17 +0000238 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
239 unsigned TCycle, unsigned TExtra,
240 MachineBasicBlock &FBB,
241 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000242 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000243 return TCycle > 0 && FCycle > 0 &&
244 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000245 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000246 }
247
Matthias Braun2c931792016-08-17 02:51:57 +0000248 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000249 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000250 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000251 }
252
Matthias Braun2c931792016-08-17 02:51:57 +0000253 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000254 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
255 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000256 int Incr1 = (C1->Kind == ICDiamond)
257 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
258 int Incr2 = (C2->Kind == ICDiamond)
259 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
260 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000261 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000262 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000263 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000264 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000265 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000266 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000267 // Favors diamond over triangle, etc.
268 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
269 return true;
270 else if (C1->Kind == C2->Kind)
271 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
272 }
273 }
274 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000275 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000276 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000277
Evan Chengf5e53a52007-05-16 02:00:57 +0000278 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000279}
Evan Chengf5e53a52007-05-16 02:00:57 +0000280
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000281char &llvm::IfConverterID = IfConverter::ID;
282
Owen Anderson8ac477f2010-10-12 19:48:12 +0000283INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000284INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000285INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000286
Evan Chengf5e53a52007-05-16 02:00:57 +0000287bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000288 if (skipFunction(*MF.getFunction()) ||
289 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000290 return false;
291
Eric Christopher3d4276f2015-01-27 07:31:29 +0000292 const TargetSubtargetInfo &ST = MF.getSubtarget();
293 TLI = ST.getTargetLowering();
294 TII = ST.getInstrInfo();
295 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000296 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000297 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000298 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000299 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000300
Evan Chengf5e53a52007-05-16 02:00:57 +0000301 if (!TII) return false;
302
Evan Chengc5adcca2012-06-08 21:53:50 +0000303 PreRegAlloc = MRI->isSSA();
304
305 bool BFChange = false;
306 if (!PreRegAlloc) {
307 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000308 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000309 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000310 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000311 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000312
David Greene72e47cd2010-01-04 22:02:01 +0000313 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000314 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000315
316 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000317 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000318 return false;
319 }
David Greene72e47cd2010-01-04 22:02:01 +0000320 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000321
Evan Chengf5e53a52007-05-16 02:00:57 +0000322 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000323 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000324
Justin Lebar3a7bc572016-02-22 17:51:28 +0000325 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000326 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000327 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
328 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
329 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000330 // Do an initial analysis for each basic block and find all the potential
331 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000332 bool Change = false;
333 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000334 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000335 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000336 Tokens.pop_back();
337 BBInfo &BBI = Token->BBI;
338 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000339 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000340 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000341
Evan Cheng4dd31a72007-06-11 22:26:22 +0000342 // If the block has been evicted out of the queue or it has already been
343 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000344 if (BBI.IsDone)
345 BBI.IsEnqueued = false;
346 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000347 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000348
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000349 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000350
Evan Cheng312b7232007-06-04 06:47:22 +0000351 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000352 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000353 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000354 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000355 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000356 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000357 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000358 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
359 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000360 << "): BB#" << BBI.BB->getNumber() << " ("
361 << ((Kind == ICSimpleFalse)
362 ? BBI.FalseBB->getNumber()
363 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000364 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000365 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000366 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000367 if (isFalse) ++NumSimpleFalse;
368 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000369 }
Evan Cheng312b7232007-06-04 06:47:22 +0000370 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000371 }
Evan Chengd0e66912007-05-23 07:23:16 +0000372 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000373 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000374 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000375 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000376 bool isFalse = Kind == ICTriangleFalse;
377 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000378 if (DisableTriangle && !isFalse && !isRev) break;
379 if (DisableTriangleR && !isFalse && isRev) break;
380 if (DisableTriangleF && isFalse && !isRev) break;
381 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000382 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000383 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000384 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000385 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000386 DEBUG(dbgs() << " rev");
387 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000388 << BBI.TrueBB->getNumber() << ",F:"
389 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000390 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000391 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000392 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000393 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000394 if (isRev) ++NumTriangleFRev;
395 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000396 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000397 if (isRev) ++NumTriangleRev;
398 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000399 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000400 }
Evan Chengd0e66912007-05-23 07:23:16 +0000401 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000402 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000403 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000404 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000405 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000406 << BBI.TrueBB->getNumber() << ",F:"
407 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000408 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000409 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000410 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000411 break;
412 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000413 }
414
Evan Cheng312b7232007-06-04 06:47:22 +0000415 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000416
Evan Cheng92fb5452007-06-15 07:36:12 +0000417 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
418 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
419 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000420 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000421 }
Evan Chengd0e66912007-05-23 07:23:16 +0000422
Evan Chengd0e66912007-05-23 07:23:16 +0000423 if (!Change)
424 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000425 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000426 }
Evan Cheng478b8052007-05-18 01:55:58 +0000427
Evan Cheng3a51c852007-06-16 09:34:52 +0000428 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000429 BBAnalysis.clear();
430
Evan Chengcf9e8a92010-06-18 22:17:13 +0000431 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000432 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000433 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000434 getAnalysisIfAvailable<MachineModuleInfo>());
435 }
436
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000437 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000438 return MadeChange;
439}
440
Matthias Braun2c931792016-08-17 02:51:57 +0000441/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000442static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000443 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000444 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000445 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000446 return SuccBB;
447 }
Craig Topperc0196b12014-04-14 00:51:57 +0000448 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000449}
450
Matthias Braun2c931792016-08-17 02:51:57 +0000451/// Reverse the condition of the end of the block branch. Swap block's 'true'
452/// and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000453bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000454 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000455 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
456 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000457 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000458 std::swap(BBI.TrueBB, BBI.FalseBB);
459 return true;
460 }
461 return false;
462}
463
Matthias Braun2c931792016-08-17 02:51:57 +0000464/// Returns the next block in the function blocks ordering. If it is the end,
465/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000466static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
467 MachineFunction::iterator I = MBB.getIterator();
468 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000469 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000470 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000471 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000472}
473
Matthias Braun2c931792016-08-17 02:51:57 +0000474/// Returns true if the 'true' block (along with its predecessor) forms a valid
475/// simple shape for ifcvt. It also returns the number of instructions that the
476/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000477bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000478 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000479 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000480 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000481 return false;
482
Evan Chenga955c022007-06-19 21:45:13 +0000483 if (TrueBBI.IsBrAnalyzable)
484 return false;
485
Evan Cheng23402fc2007-06-15 21:18:05 +0000486 if (TrueBBI.BB->pred_size() > 1) {
487 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000488 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000489 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000490 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000491 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000492 }
493
Evan Chenga955c022007-06-19 21:45:13 +0000494 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000495}
496
Matthias Braun2c931792016-08-17 02:51:57 +0000497/// Returns true if the 'true' and 'false' blocks (along with their common
498/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
499/// true, it checks if 'true' block's false branch branches to the 'false' block
500/// rather than the other way around. It also returns the number of instructions
501/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000502bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000503 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000504 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000505 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000506 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000507 return false;
508
Evan Cheng23402fc2007-06-15 21:18:05 +0000509 if (TrueBBI.BB->pred_size() > 1) {
510 if (TrueBBI.CannotBeCopied)
511 return false;
512
Evan Cheng92fb5452007-06-15 07:36:12 +0000513 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000514 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000515 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000516 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000517 --Size;
518 else {
519 MachineBasicBlock *FExit = FalseBranch
520 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
521 if (FExit)
522 // Require a conditional branch
523 ++Size;
524 }
525 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000526 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000527 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000528 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000529 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000530
Evan Cheng7783f822007-06-08 09:36:04 +0000531 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
532 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000533 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000534 if (++I == TrueBBI.BB->getParent()->end())
535 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000536 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000537 }
Evan Cheng7783f822007-06-08 09:36:04 +0000538 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000539}
540
Matthias Braun2c931792016-08-17 02:51:57 +0000541/// Increment \p It until it points to a non-debug instruction or to \p End.
Kyle Buttfe916822016-08-06 01:52:31 +0000542/// @param It Iterator to increment
543/// @param End Iterator that points to end. Will be compared to It
544/// @returns true if It == End, false otherwise.
545static inline bool skipDebugInstructionsForward(
546 MachineBasicBlock::iterator &It,
547 MachineBasicBlock::iterator &End) {
548 while (It != End && It->isDebugValue())
549 It++;
550 return It == End;
551}
552
Matthias Braun2c931792016-08-17 02:51:57 +0000553/// Decrement \p It until it points to a non-debug instruction or to \p Begin.
Kyle Buttfe916822016-08-06 01:52:31 +0000554/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000555/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttfe916822016-08-06 01:52:31 +0000556/// @returns true if It == Begin, false otherwise.
557static inline bool skipDebugInstructionsBackward(
558 MachineBasicBlock::iterator &It,
559 MachineBasicBlock::iterator &Begin) {
560 while (It != Begin && It->isDebugValue())
561 It--;
562 return It == Begin;
563}
564
Kyle Butt4f0e2872016-08-06 01:52:33 +0000565/// Count duplicated instructions and move the iterators to show where they
566/// are.
567/// @param TIB True Iterator Begin
568/// @param FIB False Iterator Begin
569/// These two iterators initially point to the first instruction of the two
570/// blocks, and finally point to the first non-shared instruction.
571/// @param TIE True Iterator End
572/// @param FIE False Iterator End
573/// These two iterators initially point to End() for the two blocks() and
574/// finally point to the first shared instruction in the tail.
575/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
576/// two blocks.
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000577static void countDuplicatedInstructions(
578 MachineBasicBlock::iterator &TIB,
579 MachineBasicBlock::iterator &FIB,
580 MachineBasicBlock::iterator &TIE,
581 MachineBasicBlock::iterator &FIE,
582 unsigned &Dups1, unsigned &Dups2,
583 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
584 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000585
Bob Wilsone1961fe2010-10-26 00:02:24 +0000586 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000587 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000588 if(skipDebugInstructionsForward(TIB, TIE))
589 break;
590 if(skipDebugInstructionsForward(FIB, FIE))
591 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000592 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000593 break;
594 ++Dups1;
595 ++TIB;
596 ++FIB;
597 }
598
599 // Now, in preparation for counting duplicate instructions at the ends of the
600 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000601 // If both blocks are returning don't skip the branches, since they will
602 // likely be both identical return instructions. In such cases the return
603 // can be left unpredicated.
604 // Check for already containing all of the block.
605 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000606 return;
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000607 --TIE;
608 --FIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000609 if (!TBB.succ_empty() || !FBB.succ_empty()) {
610 if (SkipConditionalBranches) {
611 while (TIE != TIB && TIE->isBranch())
612 --TIE;
613 while (FIE != FIB && FIE->isBranch())
614 --FIE;
615 } else {
616 while (TIE != TIB && TIE->isUnconditionalBranch())
617 --TIE;
618 while (FIE != FIB && FIE->isUnconditionalBranch())
619 --FIE;
620 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000621 }
622
623 // If Dups1 includes all of a block, then don't count duplicate
624 // instructions at the end of the blocks.
Nico Weber99ceee82016-08-07 20:18:04 +0000625 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000626 return;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000627
628 // Count duplicate instructions at the ends of the blocks.
629 while (TIE != TIB && FIE != FIB) {
630 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000631 if (skipDebugInstructionsBackward(TIE, TIB))
632 break;
633 if (skipDebugInstructionsBackward(FIE, FIB))
634 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000635 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000636 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000637 // If we are trying to make sure the conditional branches are the same, we
638 // still don't want to count them.
639 if (SkipConditionalBranches || !TIE->isBranch())
640 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000641 --TIE;
642 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000643 }
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000644}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000645
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000646/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
647/// with their common predecessor) forms a valid diamond shape for ifcvt.
Diana Picus68be1eb2016-08-14 02:10:18 +0000648bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
649 unsigned &Dups1, unsigned &Dups2) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000650 Dups1 = Dups2 = 0;
651 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
652 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
653 return false;
654
655 MachineBasicBlock *TT = TrueBBI.TrueBB;
656 MachineBasicBlock *FT = FalseBBI.TrueBB;
657
658 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000659 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000660 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000661 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000662 if (TT != FT)
663 return false;
664 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
665 return false;
666 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
667 return false;
668
669 // FIXME: Allow true block to have an early exit?
Diana Picus68be1eb2016-08-14 02:10:18 +0000670 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
671 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000672 return false;
673
674 // Count duplicate instructions at the beginning and end of the true and
675 // false blocks.
676 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
677 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
678 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
679 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
680 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
681 *TrueBBI.BB, *FalseBBI.BB,
682 /* SkipConditionalBranches */ true);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000683 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000684}
685
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000686/// AnalyzeBranches - Look at the branches at the end of a block to determine if
687/// the block is predicable.
688void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000689 if (BBI.IsDone)
690 return;
691
Craig Topperc0196b12014-04-14 00:51:57 +0000692 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000693 BBI.BrCond.clear();
694 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000695 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000696 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000697
698 if (BBI.BrCond.size()) {
699 // No false branch. This BB must end with a conditional branch and a
700 // fallthrough.
701 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000702 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000703 if (!BBI.FalseBB) {
704 // Malformed bcc? True and false blocks are the same?
705 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000706 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000707 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000708}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000709
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000710/// ScanInstructions - Scan all the instructions in the block to determine if
711/// the block is predicable. In most cases, that means all the instructions
712/// in the block are isPredicable(). Also checks if the block contains any
713/// instruction which can clobber a predicate (e.g. condition code register).
714/// If so, the block is not predicable unless it's the last instruction.
715void IfConverter::ScanInstructions(BBInfo &BBI,
716 MachineBasicBlock::iterator &Begin,
717 MachineBasicBlock::iterator &End) const {
718 if (BBI.IsDone || BBI.IsUnpredicable)
719 return;
720
721 bool AlreadyPredicated = !BBI.Predicate.empty();
722
Evan Cheng4dd31a72007-06-11 22:26:22 +0000723 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000724 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000725 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000726 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000727 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000728 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000729 continue;
730
Justin Lebar7dba2e02016-04-15 01:38:41 +0000731 // It's unsafe to duplicate convergent instructions in this context, so set
732 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
733 // following CFG, which is subject to our "simple" transformation.
734 //
735 // BB0 // if (c1) goto BB1; else goto BB2;
736 // / \
737 // BB1 |
738 // | BB2 // if (c2) goto TBB; else goto FBB;
739 // | / |
740 // | / |
741 // TBB |
742 // | |
743 // | FBB
744 // |
745 // exit
746 //
747 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
748 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
749 // TBB contains a convergent instruction. This is safe iff doing so does
750 // not add a control-flow dependency to the convergent instruction -- i.e.,
751 // it's safe iff the set of control flows that leads us to the convergent
752 // instruction does not get smaller after the transformation.
753 //
754 // Originally we executed TBB if c1 || c2. After the transformation, there
755 // are two copies of TBB's instructions. We get to the first if c1, and we
756 // get to the second if !c1 && c2.
757 //
758 // There are clearly fewer ways to satisfy the condition "c1" than
759 // "c1 || c2". Since we've shrunk the set of control flows which lead to
760 // our convergent instruction, the transformation is unsafe.
761 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000762 BBI.CannotBeCopied = true;
763
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000764 bool isPredicated = TII->isPredicated(MI);
765 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000766
Joey Goulya5153cb2013-09-09 14:21:49 +0000767 // A conditional branch is not predicable, but it may be eliminated.
768 if (isCondBr)
769 continue;
770
771 if (!isPredicated) {
772 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000773 unsigned ExtraPredCost = TII->getPredicationCost(MI);
774 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000775 if (NumCycles > 1)
776 BBI.ExtraCost += NumCycles-1;
777 BBI.ExtraCost2 += ExtraPredCost;
778 } else if (!AlreadyPredicated) {
779 // FIXME: This instruction is already predicated before the
780 // if-conversion pass. It's probably something like a conditional move.
781 // Mark this block unpredicable for now.
782 BBI.IsUnpredicable = true;
783 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000784 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000785
786 if (BBI.ClobbersPred && !isPredicated) {
787 // Predicate modification instruction should end the block (except for
788 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000789 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000790 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000791 BBI.IsUnpredicable = true;
792 return;
793 }
794
Evan Chengfbc73092007-07-10 17:50:43 +0000795 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
796 // still potentially predicable.
797 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000798 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000799 BBI.ClobbersPred = true;
800
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000801 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000802 BBI.IsUnpredicable = true;
803 return;
804 }
805 }
806}
807
Matthias Braun2c931792016-08-17 02:51:57 +0000808/// Determine if the block is a suitable candidate to be predicated by the
809/// specified predicate.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000810bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000811 SmallVectorImpl<MachineOperand> &Pred,
Diana Picus68be1eb2016-08-14 02:10:18 +0000812 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000813 // If the block is dead or unpredicable, then it cannot be predicated.
Diana Picus68be1eb2016-08-14 02:10:18 +0000814 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000815 return false;
816
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000817 // If it is already predicated but we couldn't analyze its terminator, the
818 // latter might fallthrough, but we can't determine where to.
819 // Conservatively avoid if-converting again.
820 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
821 return false;
822
Quentin Colombetbdab2272013-07-24 20:20:37 +0000823 // If it is already predicated, check if the new predicate subsumes
824 // its predicate.
825 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000826 return false;
827
Diana Picus68be1eb2016-08-14 02:10:18 +0000828 if (BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000829 if (!isTriangle)
830 return false;
831
Bob Wilson2371f4f2009-05-13 23:25:24 +0000832 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000833 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
834 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000835 if (RevBranch) {
836 if (TII->ReverseBranchCondition(Cond))
837 return false;
838 }
839 if (TII->ReverseBranchCondition(RevPred) ||
840 !TII->SubsumesPredicate(Cond, RevPred))
841 return false;
842 }
843
844 return true;
845}
846
Matthias Braun2c931792016-08-17 02:51:57 +0000847/// Analyze the structure of the sub-CFG starting from the specified block.
848/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000849void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +0000850 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000851 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +0000852 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000853 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000854
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000855 /// This flag is true if MBB's successors have been analyzed.
856 bool SuccsAnalyzed;
857 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000858
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000859 // Push MBB to the stack.
860 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000861
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000862 while (!BBStack.empty()) {
863 BBState &State = BBStack.back();
864 MachineBasicBlock *BB = State.MBB;
865 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000866
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000867 if (!State.SuccsAnalyzed) {
868 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
869 BBStack.pop_back();
870 continue;
871 }
Evan Cheng9030b982007-06-06 10:16:17 +0000872
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000873 BBI.BB = BB;
874 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000875
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000876 AnalyzeBranches(BBI);
877 MachineBasicBlock::iterator Begin = BBI.BB->begin();
878 MachineBasicBlock::iterator End = BBI.BB->end();
879 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +0000880
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000881 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
882 // not considered for ifcvt anymore.
883 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
884 BBI.IsBeingAnalyzed = false;
885 BBI.IsAnalyzed = true;
886 BBStack.pop_back();
887 continue;
888 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000889
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000890 // Do not ifcvt if either path is a back edge to the entry block.
891 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
892 BBI.IsBeingAnalyzed = false;
893 BBI.IsAnalyzed = true;
894 BBStack.pop_back();
895 continue;
896 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000897
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000898 // Do not ifcvt if true and false fallthrough blocks are the same.
899 if (!BBI.FalseBB) {
900 BBI.IsBeingAnalyzed = false;
901 BBI.IsAnalyzed = true;
902 BBStack.pop_back();
903 continue;
904 }
Evan Cheng7783f822007-06-08 09:36:04 +0000905
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000906 // Push the False and True blocks to the stack.
907 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +0000908 BBStack.push_back(*BBI.FalseBB);
909 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000910 continue;
911 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000912
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000913 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
914 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000915
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000916 if (TrueBBI.IsDone && FalseBBI.IsDone) {
917 BBI.IsBeingAnalyzed = false;
918 BBI.IsAnalyzed = true;
919 BBStack.pop_back();
920 continue;
921 }
922
923 SmallVector<MachineOperand, 4>
924 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
925 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
926
927 unsigned Dups = 0;
928 unsigned Dups2 = 0;
929 bool TNeedSub = !TrueBBI.Predicate.empty();
930 bool FNeedSub = !FalseBBI.Predicate.empty();
931 bool Enqueued = false;
932
933 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
934
Diana Picus68be1eb2016-08-14 02:10:18 +0000935 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
936 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
937 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
938 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
939 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
940 Prediction) &&
941 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
942 FeasibilityAnalysis(FalseBBI, RevCond)) {
943 // Diamond:
944 // EBB
945 // / \_
946 // | |
947 // TBB FBB
948 // \ /
949 // TailBB
950 // Note TailBB can be empty.
951 Tokens.push_back(llvm::make_unique<IfcvtToken>(
952 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
953 Enqueued = true;
Evan Cheng3a51c852007-06-16 09:34:52 +0000954 }
955
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000956 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
957 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
958 TrueBBI.ExtraCost2, Prediction) &&
959 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
960 // Triangle:
961 // EBB
962 // | \_
963 // | |
964 // | TBB
965 // | /
966 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000967 Tokens.push_back(
968 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000969 Enqueued = true;
970 }
971
972 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
973 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
974 TrueBBI.ExtraCost2, Prediction) &&
975 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000976 Tokens.push_back(
977 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000978 Enqueued = true;
979 }
980
981 if (ValidSimple(TrueBBI, Dups, Prediction) &&
982 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
983 TrueBBI.ExtraCost2, Prediction) &&
984 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
985 // Simple (split, no rejoin):
986 // EBB
987 // | \_
988 // | |
989 // | TBB---> exit
990 // |
991 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000992 Tokens.push_back(
993 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000994 Enqueued = true;
995 }
996
997 if (CanRevCond) {
998 // Try the other path...
999 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1000 Prediction.getCompl()) &&
1001 MeetIfcvtSizeLimit(*FalseBBI.BB,
1002 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1003 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1004 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001005 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1006 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001007 Enqueued = true;
1008 }
1009
1010 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1011 Prediction.getCompl()) &&
1012 MeetIfcvtSizeLimit(*FalseBBI.BB,
1013 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001014 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001015 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001016 Tokens.push_back(
1017 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001018 Enqueued = true;
1019 }
1020
1021 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1022 MeetIfcvtSizeLimit(*FalseBBI.BB,
1023 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1024 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1025 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001026 Tokens.push_back(
1027 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001028 Enqueued = true;
1029 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001030 }
1031
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001032 BBI.IsEnqueued = Enqueued;
1033 BBI.IsBeingAnalyzed = false;
1034 BBI.IsAnalyzed = true;
1035 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001036 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001037}
1038
Matthias Braun2c931792016-08-17 02:51:57 +00001039/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001040void IfConverter::AnalyzeBlocks(
1041 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001042 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001043 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001044
Evan Cheng20e05992007-06-01 00:12:12 +00001045 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001046 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001047}
1048
Matthias Braun2c931792016-08-17 02:51:57 +00001049/// Returns true either if ToMBB is the next block after MBB or that all the
1050/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001051static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1052 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001053 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001054 MachineFunction::iterator TI = ToMBB.getIterator();
1055 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001056 while (I != TI) {
1057 // Check isSuccessor to avoid case where the next block is empty, but
1058 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001059 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001060 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001061 PI = I++;
1062 }
Evan Cheng312b7232007-06-04 06:47:22 +00001063 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001064}
1065
Matthias Braun2c931792016-08-17 02:51:57 +00001066/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1067/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001068void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1069 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001070 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001071 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001072 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001073 PBBI.IsAnalyzed = false;
1074 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001075 }
1076}
1077
Matthias Braun2c931792016-08-17 02:51:57 +00001078/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001079static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001080 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001081 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001082 SmallVector<MachineOperand, 0> NoCond;
Matthias Braun08f47042016-08-17 02:52:01 +00001083 TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001084}
1085
Matthias Braun2c931792016-08-17 02:51:57 +00001086/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001087void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001088 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001089 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001090 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001091 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001092}
1093
Matthias Braund616ccc2013-10-11 19:04:37 +00001094/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001095/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001096static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001097 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1098 ->getSubtarget().getRegisterInfo();
1099
1100 // Before stepping forward past MI, remember which regs were live
1101 // before MI. This is needed to set the Undef flag only when reg is
1102 // dead.
1103 SparseSet<unsigned> LiveBeforeMI;
1104 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001105 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001106 LiveBeforeMI.insert(Reg);
1107
Pete Cooper7605e372015-05-05 20:14:22 +00001108 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001109 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001110
Pete Cooper7605e372015-05-05 20:14:22 +00001111 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001112 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001113 // FIXME: Const cast here is nasty, but better than making StepForward
1114 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001115 unsigned Reg = Clobber.first;
1116 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001117 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001118 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001119 if (Op.isRegMask()) {
1120 // First handle regmasks. They clobber any entries in the mask which
1121 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001122 if (LiveBeforeMI.count(Reg))
1123 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001124
1125 // We also need to add an implicit def of this register for the later
1126 // use to read from.
1127 // For the register allocator to have allocated a register clobbered
1128 // by the call which is used later, it must be the case that
1129 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001130 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001131 continue;
1132 }
1133 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001134 if (Op.isDead()) {
1135 // If we found a dead def, but it needs to be live, then remove the dead
1136 // flag.
1137 if (Redefs.contains(Op.getReg()))
1138 Op.setIsDead(false);
1139 }
Matthias Braun08f47042016-08-17 02:52:01 +00001140 if (LiveBeforeMI.count(Reg))
1141 MIB.addReg(Reg, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001142 }
1143}
1144
Matthias Braun2c931792016-08-17 02:51:57 +00001145/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001146static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001147 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001148 if (!O->isReg() || !O->isKill())
1149 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001150 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001151 O->setIsKill(false);
1152 }
1153}
1154
Matthias Braun2c931792016-08-17 02:51:57 +00001155/// Walks a range of machine instructions and removes kill flags for registers
1156/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001157static void RemoveKills(MachineBasicBlock::iterator I,
1158 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001159 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001160 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001161 for (MachineInstr &MI : make_range(I, E))
1162 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001163}
1164
Matthias Braun2c931792016-08-17 02:51:57 +00001165/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001166bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001167 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1168 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1169 BBInfo *CvtBBI = &TrueBBI;
1170 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001171
Owen Anderson4f6bf042008-08-14 22:49:33 +00001172 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001173 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001174 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001175
Matthias Braun08f47042016-08-17 02:52:01 +00001176 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1177 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001178 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001179 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001180 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001181 BBI.IsAnalyzed = false;
1182 CvtBBI->IsAnalyzed = false;
1183 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001184 }
Evan Chengd0e66912007-05-23 07:23:16 +00001185
Matthias Braun08f47042016-08-17 02:52:01 +00001186 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001187 // Conservatively abort if-conversion if BB's address is taken.
1188 return false;
1189
Evan Cheng3a51c852007-06-16 09:34:52 +00001190 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001191 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001192 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001193
Bob Wilson45814342010-06-19 05:33:57 +00001194 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001195 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001196 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001197 Redefs.addLiveIns(CvtMBB);
1198 Redefs.addLiveIns(NextMBB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001199
1200 // Compute a set of registers which must not be killed by instructions in
1201 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001202 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001203 DontKill.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001204
Matthias Braun08f47042016-08-17 02:52:01 +00001205 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001206 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001207 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001208 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001209 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001210
1211 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1212 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001213 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001214 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001215 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1216 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001217
Evan Cheng92fb5452007-06-15 07:36:12 +00001218 // Merge converted block into entry block.
1219 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1220 MergeBlocks(BBI, *CvtBBI);
1221 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001222
Evan Chenge4ec9182007-06-06 02:08:52 +00001223 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001224 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1225 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001226 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001227 // Now ifcvt'd block will look like this:
1228 // BB:
1229 // ...
1230 // t, f = cmp
1231 // if t op
1232 // b BBf
1233 //
1234 // We cannot further ifcvt this block because the unconditional branch
1235 // will have to be predicated on the new condition, that will not be
1236 // available if cmp executes.
1237 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001238 }
Evan Chenge26c0912007-05-21 22:22:58 +00001239
Evan Cheng288f1542007-06-08 22:01:07 +00001240 RemoveExtraEdges(BBI);
1241
Evan Chengd0e66912007-05-23 07:23:16 +00001242 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001243 if (!IterIfcvt)
1244 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001245 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001246 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001247
1248 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001249 return true;
1250}
1251
Matthias Braun2c931792016-08-17 02:51:57 +00001252/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001253bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001254 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001255 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1256 BBInfo *CvtBBI = &TrueBBI;
1257 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001258 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001259
Owen Anderson4f6bf042008-08-14 22:49:33 +00001260 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001261 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001262 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001263
Matthias Braun08f47042016-08-17 02:52:01 +00001264 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1265 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001266 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001267 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001268 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001269 BBI.IsAnalyzed = false;
1270 CvtBBI->IsAnalyzed = false;
1271 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001272 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001273
Matthias Braun08f47042016-08-17 02:52:01 +00001274 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001275 // Conservatively abort if-conversion if BB's address is taken.
1276 return false;
1277
Evan Cheng3a51c852007-06-16 09:34:52 +00001278 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001279 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001280 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001281
Evan Cheng3a51c852007-06-16 09:34:52 +00001282 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001283 if (ReverseBranchCondition(*CvtBBI)) {
1284 // BB has been changed, modify its predecessors (except for this
1285 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001286 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001287 if (PBB == BBI.BB)
1288 continue;
1289 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1290 if (PBBI.IsEnqueued) {
1291 PBBI.IsAnalyzed = false;
1292 PBBI.IsEnqueued = false;
1293 }
Evan Chengadd97762007-06-14 23:34:09 +00001294 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001295 }
1296 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001297
Bob Wilson45814342010-06-19 05:33:57 +00001298 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001299 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001300 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001301 Redefs.addLiveIns(CvtMBB);
1302 Redefs.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001303
Andrew Trick276dd452013-10-14 20:45:17 +00001304 DontKill.clear();
1305
Craig Topperc0196b12014-04-14 00:51:57 +00001306 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001307 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001308
Manman Renb6819182014-01-29 23:18:47 +00001309 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001310 // Get probabilities before modifying CvtMBB and BBI.BB.
1311 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1312 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1313 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1314 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001315 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001316
Matthias Braun08f47042016-08-17 02:52:01 +00001317 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001318 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001319 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001320 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001321 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001322
1323 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1324 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001325 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001326 } else {
1327 // Predicate the 'true' block after removing its branch.
Matthias Braun08f47042016-08-17 02:52:01 +00001328 CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1329 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001330
Evan Cheng0598b2d2007-06-18 22:44:57 +00001331 // Now merge the entry of the triangle with the true block.
1332 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001333 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001334 }
1335
Evan Cheng312b7232007-06-04 06:47:22 +00001336 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001337 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001338 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1339 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001340 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001341 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001342
Cong Houd97c1002015-12-01 05:29:22 +00001343 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001344 // NewNext = New_Prob(BBI.BB, NextMBB) =
1345 // Prob(BBI.BB, NextMBB) +
1346 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001347 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001348 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1349 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001350 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001351 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001352 if (NewTrueBBIter != BBI.BB->succ_end())
1353 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001354
1355 auto NewFalse = BBCvt * CvtFalse;
1356 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1357 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001358 }
Evan Cheng7783f822007-06-08 09:36:04 +00001359
1360 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001361 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001362 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001363 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001364 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001365 if (!isFallThrough) {
1366 // Only merge them if the true block does not fallthrough to the false
1367 // block. By not merging them, we make it possible to iteratively
1368 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001369 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001370 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1371 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001372 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001373 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001374 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001375 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001376 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001377 }
Evan Cheng7783f822007-06-08 09:36:04 +00001378 // Mixed predicated and unpredicated code. This cannot be iteratively
1379 // predicated.
1380 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001381 }
Evan Chenge26c0912007-05-21 22:22:58 +00001382
Evan Cheng288f1542007-06-08 22:01:07 +00001383 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001384
Evan Chengd0e66912007-05-23 07:23:16 +00001385 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001386 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001387 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001388 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001389 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001390 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001391 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001392
1393 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001394 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001395}
1396
Matthias Braun2c931792016-08-17 02:51:57 +00001397/// If convert a diamond sub-CFG.
Diana Picus68be1eb2016-08-14 02:10:18 +00001398bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1399 unsigned NumDups1, unsigned NumDups2) {
1400 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1401 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1402 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1403 // True block must fall through or end with an unanalyzable terminator.
1404 if (!TailBB) {
1405 if (blockAlwaysFallThrough(TrueBBI))
1406 TailBB = FalseBBI.TrueBB;
1407 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1408 }
Evan Chenge26c0912007-05-21 22:22:58 +00001409
Evan Cheng51eb2c32007-06-18 08:37:25 +00001410 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Diana Picus68be1eb2016-08-14 02:10:18 +00001411 TrueBBI.BB->pred_size() > 1 ||
1412 FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001413 // Something has changed. It's no longer safe to predicate these blocks.
1414 BBI.IsAnalyzed = false;
1415 TrueBBI.IsAnalyzed = false;
1416 FalseBBI.IsAnalyzed = false;
1417 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001418 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001419
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001420 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1421 // Conservatively abort if-conversion if either BB has its address taken.
1422 return false;
1423
Bob Wilson1e5da552010-06-29 00:55:23 +00001424 // Put the predicated instructions from the 'true' block before the
1425 // instructions from the 'false' block, unless the true block would clobber
1426 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001427 BBInfo *BBI1 = &TrueBBI;
1428 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001429 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001430 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001431 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001432 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1433 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001434
Evan Cheng3a51c852007-06-16 09:34:52 +00001435 // Figure out the more profitable ordering.
1436 bool DoSwap = false;
Diana Picus68be1eb2016-08-14 02:10:18 +00001437 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001438 DoSwap = true;
Diana Picus68be1eb2016-08-14 02:10:18 +00001439 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001440 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001441 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001442 }
1443 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001444 std::swap(BBI1, BBI2);
1445 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001446 }
Evan Cheng79484222007-06-05 23:46:14 +00001447
Evan Cheng51eb2c32007-06-18 08:37:25 +00001448 // Remove the conditional branch from entry to the blocks.
1449 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1450
Matthias Braun08f47042016-08-17 02:52:01 +00001451 MachineBasicBlock &MBB1 = *BBI1->BB;
1452 MachineBasicBlock &MBB2 = *BBI2->BB;
1453
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001454 // Initialize the Redefs:
1455 // - BB2 live-in regs need implicit uses before being redefined by BB1
1456 // instructions.
1457 // - BB1 live-out regs need implicit uses before being redefined by BB2
1458 // instructions. We start with BB1 live-ins so we have the live-out regs
1459 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001460 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001461 Redefs.addLiveIns(MBB1);
1462 Redefs.addLiveIns(MBB2);
Evan Chengf128bdc2010-06-16 07:35:02 +00001463
Evan Cheng51eb2c32007-06-18 08:37:25 +00001464 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001465 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001466 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1467 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001468 BBI1->NonPredSize -= NumDups1;
1469 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001470
1471 // Skip past the dups on each side separately since there may be
1472 // differing dbg_value entries.
1473 for (unsigned i = 0; i < NumDups1; ++DI1) {
1474 if (!DI1->isDebugValue())
1475 ++i;
1476 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001477 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001478 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001479 if (!DI2->isDebugValue())
1480 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001481 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001482
Matthias Braund616ccc2013-10-11 19:04:37 +00001483 // Compute a set of registers which must not be killed by instructions in BB1:
1484 // This is everything used+live in BB2 after the duplicated instructions. We
1485 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001486 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001487 for (const MachineInstr &MI :
1488 make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
Matthias Braunb1e05582016-08-17 02:51:59 +00001489 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001490
Matthias Braun08f47042016-08-17 02:52:01 +00001491 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Pete Cooper7605e372015-05-05 20:14:22 +00001492 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
Matthias Braunb1e05582016-08-17 02:51:59 +00001493 Redefs.stepForward(MI, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001494 }
Matthias Braun08f47042016-08-17 02:52:01 +00001495 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1496 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001497
Diana Picus68be1eb2016-08-14 02:10:18 +00001498 // Remove branch from the 'true' block, unless it was not analyzable.
1499 // Non-analyzable branches need to be preserved, since in such cases,
1500 // the CFG structure is not an actual diamond (the join block may not
1501 // be present).
1502 if (BBI1->IsBrAnalyzable)
Matthias Braun08f47042016-08-17 02:52:01 +00001503 BBI1->NonPredSize -= TII->RemoveBranch(MBB1);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001504 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001505 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001506 for (unsigned i = 0; i != NumDups2; ) {
1507 // NumDups2 only counted non-dbg_value instructions, so this won't
1508 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001509 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001510 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001511 // skip dbg_value instructions
1512 if (!DI1->isDebugValue())
1513 ++i;
1514 }
Matthias Braun08f47042016-08-17 02:52:01 +00001515 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001516
Matthias Braund616ccc2013-10-11 19:04:37 +00001517 // Kill flags in the true block for registers living into the false block
1518 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001519 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001520
Diana Picus68be1eb2016-08-14 02:10:18 +00001521 // Remove 'false' block branch (unless it was not analyzable), and find
1522 // the last instruction to predicate.
1523 if (BBI2->IsBrAnalyzable)
Matthias Braun08f47042016-08-17 02:52:01 +00001524 BBI2->NonPredSize -= TII->RemoveBranch(MBB2);
1525 DI2 = MBB2.end();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001526 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001527 // NumDups2 only counted non-dbg_value instructions, so this won't
1528 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001529 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001530 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001531 // skip dbg_value instructions
1532 if (!DI2->isDebugValue())
1533 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001534 }
Evan Cheng4266a792011-12-19 22:01:30 +00001535
1536 // Remember which registers would later be defined by the false block.
1537 // This allows us not to predicate instructions in the true block that would
1538 // later be re-defined. That is, rather than
1539 // subeq r0, r1, #1
1540 // addne r0, r1, #1
1541 // generate:
1542 // sub r0, r1, #1
1543 // addne r0, r1, #1
1544 SmallSet<unsigned, 4> RedefsByFalse;
1545 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001546 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1547 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001548 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001549 continue;
1550 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001551 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001552 if (!MO.isReg())
1553 continue;
1554 unsigned Reg = MO.getReg();
1555 if (!Reg)
1556 continue;
1557 if (MO.isDef()) {
1558 Defs.push_back(Reg);
1559 } else if (!RedefsByFalse.count(Reg)) {
1560 // These are defined before ctrl flow reach the 'false' instructions.
1561 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001562 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1563 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001564 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001565 }
1566 }
1567
Matthias Braunb1e05582016-08-17 02:51:59 +00001568 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001569 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001570 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1571 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001572 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001573 }
1574 }
1575 }
1576 }
1577
1578 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001579 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001580
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001581 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1582 // a non-predicated in BBI2, then we don't want to predicate the one from
1583 // BBI2. The reason is that if we merged these blocks, we would end up with
1584 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001585 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1586 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1587 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1588 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1589 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001590 --DI2;
1591 }
1592
Evan Cheng4266a792011-12-19 22:01:30 +00001593 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001594 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001595
Evan Cheng0598b2d2007-06-18 22:44:57 +00001596 // Merge the true block into the entry of the diamond.
Diana Picus68be1eb2016-08-14 02:10:18 +00001597 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1598 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001599
Bob Wilson2371f4f2009-05-13 23:25:24 +00001600 // If the if-converted block falls through or unconditionally branches into
1601 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001602 // fold the tail block in as well. Otherwise, unless it falls through to the
1603 // tail, add a unconditional branch to it.
1604 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001605 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001606 bool CanMergeTail = !TailBBI.HasFallThrough &&
1607 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001608 // The if-converted block can still have a predicated terminator
1609 // (e.g. a predicated return). If that is the case, we cannot merge
1610 // it with the tail block.
1611 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001612 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001613 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001614 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1615 // check if there are any other predecessors besides those.
1616 unsigned NumPreds = TailBB->pred_size();
1617 if (NumPreds > 1)
1618 CanMergeTail = false;
1619 else if (NumPreds == 1 && CanMergeTail) {
1620 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Matthias Braun08f47042016-08-17 02:52:01 +00001621 if (*PI != &MBB1 && *PI != &MBB2)
Bob Wilson1e5da552010-06-29 00:55:23 +00001622 CanMergeTail = false;
1623 }
1624 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001625 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001626 TailBBI.IsDone = true;
1627 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001628 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001629 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001630 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001631 }
Evan Chenge26c0912007-05-21 22:22:58 +00001632 }
1633
Bob Wilson1e5da552010-06-29 00:55:23 +00001634 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1635 // which can happen here if TailBB is unanalyzable and is merged, so
1636 // explicitly remove BBI1 and BBI2 as successors.
Matthias Braun08f47042016-08-17 02:52:01 +00001637 BBI.BB->removeSuccessor(&MBB1);
1638 BBI.BB->removeSuccessor(&MBB2, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001639 RemoveExtraEdges(BBI);
1640
Evan Cheng79484222007-06-05 23:46:14 +00001641 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001642 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001643 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001644
1645 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001646 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001647}
1648
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001649static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001650 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001651 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001652 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001653 return false;
1654
Matthias Braunb1e05582016-08-17 02:51:59 +00001655 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001656 if (!MO.isReg())
1657 continue;
1658 unsigned Reg = MO.getReg();
1659 if (!Reg)
1660 continue;
1661 if (MO.isDef() && !LaterRedefs.count(Reg))
1662 return false;
1663 }
1664
1665 return true;
1666}
1667
Matthias Braun2c931792016-08-17 02:51:57 +00001668/// Predicate instructions from the start of the block to the specified end with
1669/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001670void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001671 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001672 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001673 SmallSet<unsigned, 4> *LaterRedefs) {
1674 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001675 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001676 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001677 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001678 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001679 // It may be possible not to predicate an instruction if it's the 'true'
1680 // side of a diamond and the 'false' side may re-define the instruction's
1681 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001682 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001683 AnyUnpred = true;
1684 continue;
1685 }
1686 // If any instruction is predicated, then every instruction after it must
1687 // be predicated.
1688 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001689 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001690#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001691 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001692#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001693 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001694 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001695
Bob Wilson45814342010-06-19 05:33:57 +00001696 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001697 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001698 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001699 }
Evan Chengd0e66912007-05-23 07:23:16 +00001700
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001701 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001702
Evan Cheng92fb5452007-06-15 07:36:12 +00001703 BBI.IsAnalyzed = false;
1704 BBI.NonPredSize = 0;
1705
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001706 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001707 if (AnyUnpred)
1708 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001709}
1710
Matthias Braun2c931792016-08-17 02:51:57 +00001711/// Copy and predicate instructions from source BB to the destination block.
1712/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00001713void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001714 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001715 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001716 MachineFunction &MF = *ToBBI.BB->getParent();
1717
Matthias Braun08f47042016-08-17 02:52:01 +00001718 MachineBasicBlock &FromMBB = *FromBBI.BB;
1719 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001720 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001721 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001722 break;
1723
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001724 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001725 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001726 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001727 unsigned ExtraPredCost = TII->getPredicationCost(I);
1728 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001729 if (NumCycles > 1)
1730 ToBBI.ExtraCost += NumCycles-1;
1731 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001732
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001733 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001734 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001735#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001736 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001737#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001738 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001739 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001740 }
1741
Bob Wilson45814342010-06-19 05:33:57 +00001742 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001743 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001744 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001745
1746 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001747 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001748 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001749 }
1750
Bob Wilson1e5da552010-06-29 00:55:23 +00001751 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00001752 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
1753 FromMBB.succ_end());
1754 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001755 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001756
Matthias Braunb1e05582016-08-17 02:51:59 +00001757 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00001758 // Fallthrough edge can't be transferred.
1759 if (Succ == FallThrough)
1760 continue;
1761 ToBBI.BB->addSuccessor(Succ);
1762 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001763 }
1764
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001765 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1766 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001767
1768 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1769 ToBBI.IsAnalyzed = false;
1770
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001771 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001772}
1773
Matthias Braun2c931792016-08-17 02:51:57 +00001774/// Move all instructions from FromBB to the end of ToBB. This will leave
1775/// FromBB as an empty block, so remove all of its successor edges except for
1776/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
1777/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00001778void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00001779 MachineBasicBlock &FromMBB = *FromBBI.BB;
1780 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001781 "Removing a BB whose address is taken!");
1782
Matthias Braun08f47042016-08-17 02:52:01 +00001783 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001784 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00001785 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001786 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00001787 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001788
1789 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00001790 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001791 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00001792 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00001793
Cong Houb9e8d482015-12-17 01:29:08 +00001794 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1795 // unknown probabilities into known ones.
1796 // FIXME: This usage is too tricky and in the future we would like to
1797 // eliminate all unknown probabilities in MBB.
1798 ToBBI.BB->normalizeSuccProbs();
1799
Matthias Braun08f47042016-08-17 02:52:01 +00001800 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
1801 FromMBB.succ_end());
1802 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001803 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00001804 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
1805 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001806 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00001807 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
1808 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
1809 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00001810 // edge probability being merged to other edges when this edge is removed
1811 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00001812 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00001813 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00001814 }
1815
Matthias Braunb1e05582016-08-17 02:51:59 +00001816 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00001817 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001818 if (Succ == FallThrough)
1819 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001820
Cong Houd97c1002015-12-01 05:29:22 +00001821 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001822 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001823 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00001824 // which is a portion of the edge probability from FromMBB to Succ. The
1825 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00001826 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00001827 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001828
Matthias Braun08f47042016-08-17 02:52:01 +00001829 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
1830 // only happens when if-converting a diamond CFG and FromMBB is the
1831 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
1832 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00001833 // new successors.
1834 if (!To2FromProb.isZero())
1835 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001836 }
1837
Matthias Braun08f47042016-08-17 02:52:01 +00001838 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001839
1840 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001841 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001842 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00001843 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00001844 // don't have to set C as A's successor as it already is. We only need to
1845 // update the edge probability on A->C. Note that B will not be
1846 // immediately removed from A's successors. It is possible that B->D is
1847 // not removed either if D is a fallthrough of B. Later the edge A->D
1848 // (generated here) and B->D will be combined into one edge. To maintain
1849 // correct edge probability of this combined edge, we need to set the edge
1850 // probability of A->B to zero, which is already done above. The edge
1851 // probability on A->D is calculated by scaling the original probability
1852 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001853 //
1854 // Before ifcvt: After ifcvt (assume B->D is kept):
1855 //
1856 // A A
1857 // /| /|\
1858 // / B / B|
1859 // | /| | ||
1860 // |/ | | |/
1861 // C D C D
1862 //
1863 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001864 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00001865 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001866 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001867 else
Cong Houd97c1002015-12-01 05:29:22 +00001868 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001869 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001870 }
1871
Bob Wilson2371f4f2009-05-13 23:25:24 +00001872 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00001873 if (NBB && !FromMBB.isSuccessor(NBB))
1874 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00001875
Cong Houc1069892015-12-13 09:26:17 +00001876 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1877 // we've done above.
1878 ToBBI.BB->normalizeSuccProbs();
1879
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001880 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001881 FromBBI.Predicate.clear();
1882
Evan Chengd0e66912007-05-23 07:23:16 +00001883 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001884 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001885 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001886 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001887 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001888 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001889
Evan Cheng4dd31a72007-06-11 22:26:22 +00001890 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001891 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001892 ToBBI.IsAnalyzed = false;
1893 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001894}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001895
1896FunctionPass *
1897llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00001898 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00001899}