blob: c2586b5bf8ce275930c269aa5df70d16d4e909b0 [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.
Evan Cheng4dd31a72007-06-11 22:26:22 +000085 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000086 };
87
88 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
89 /// if-conversion feasibility analysis. This includes results from
90 /// 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.
99 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
100 /// 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.
108 /// TrueBB / FalseBB- See AnalyzeBranch().
109 /// 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),
131 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000132 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000133 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
134 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 };
136
Bob Wilson59475732010-06-15 18:19:27 +0000137 /// IfcvtToken - 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;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000151 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000152 unsigned NumDups;
153 unsigned NumDups2;
154 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000155 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000156 };
157
158 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
159 /// basic block number.
160 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;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000166 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000167 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000168 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000169
Juergen Ributzka310034e2013-12-14 06:52:56 +0000170 LivePhysRegs Redefs;
171 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000172
Evan Chengc5adcca2012-06-08 21:53:50 +0000173 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000174 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000175 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000176 std::function<bool(const Function &)> PredicateFtor;
177
Evan Chengf5e53a52007-05-16 02:00:57 +0000178 public:
179 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000180 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000181 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000182 initializeIfConverterPass(*PassRegistry::getPassRegistry());
183 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000184
Craig Topper4584cd52014-03-07 09:26:03 +0000185 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000186 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000187 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000188 MachineFunctionPass::getAnalysisUsage(AU);
189 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000190
Craig Topper4584cd52014-03-07 09:26:03 +0000191 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000192
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000193 MachineFunctionProperties getRequiredProperties() const override {
194 return MachineFunctionProperties().set(
195 MachineFunctionProperties::Property::AllVRegsAllocated);
196 }
197
Evan Chengf5e53a52007-05-16 02:00:57 +0000198 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000199 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000200 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000201 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000202 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000203 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000204 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000205 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
206 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000207 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000208 void AnalyzeBlock(MachineBasicBlock *MBB,
209 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000210 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000211 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000212 void AnalyzeBlocks(MachineFunction &MF,
213 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000214 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000215 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000216 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
217 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000218 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
219 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000220 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000221 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000222 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000223 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000224 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000225 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000226 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000227 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000228
Evan Chengdebf9c52010-11-03 00:45:17 +0000229 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
230 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000231 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000232 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000233 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000234 }
235
Evan Chengdebf9c52010-11-03 00:45:17 +0000236 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
237 unsigned TCycle, unsigned TExtra,
238 MachineBasicBlock &FBB,
239 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000240 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000241 return TCycle > 0 && FCycle > 0 &&
242 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000243 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000244 }
245
Evan Chengbe9859e2007-06-07 02:12:15 +0000246 // blockAlwaysFallThrough - Block ends without a terminator.
247 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000248 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000249 }
250
Evan Cheng3a51c852007-06-16 09:34:52 +0000251 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000252 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
253 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000254 int Incr1 = (C1->Kind == ICDiamond)
255 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
256 int Incr2 = (C2->Kind == ICDiamond)
257 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
258 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000259 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000260 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000261 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000262 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000263 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000264 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000265 // Favors diamond over triangle, etc.
266 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
267 return true;
268 else if (C1->Kind == C2->Kind)
269 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
270 }
271 }
272 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000273 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000274 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000275
Evan Chengf5e53a52007-05-16 02:00:57 +0000276 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000277}
Evan Chengf5e53a52007-05-16 02:00:57 +0000278
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000279char &llvm::IfConverterID = IfConverter::ID;
280
Owen Anderson8ac477f2010-10-12 19:48:12 +0000281INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000282INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000283INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000284
Evan Chengf5e53a52007-05-16 02:00:57 +0000285bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000286 if (skipFunction(*MF.getFunction()) ||
287 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000288 return false;
289
Eric Christopher3d4276f2015-01-27 07:31:29 +0000290 const TargetSubtargetInfo &ST = MF.getSubtarget();
291 TLI = ST.getTargetLowering();
292 TII = ST.getInstrInfo();
293 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000294 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000295 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000296 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000297 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000298
Evan Chengf5e53a52007-05-16 02:00:57 +0000299 if (!TII) return false;
300
Evan Chengc5adcca2012-06-08 21:53:50 +0000301 PreRegAlloc = MRI->isSSA();
302
303 bool BFChange = false;
304 if (!PreRegAlloc) {
305 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000306 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000307 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000308 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000309 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000310
David Greene72e47cd2010-01-04 22:02:01 +0000311 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000312 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000313
314 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000315 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000316 return false;
317 }
David Greene72e47cd2010-01-04 22:02:01 +0000318 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000319
Evan Chengf5e53a52007-05-16 02:00:57 +0000320 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000321 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000322
Justin Lebar3a7bc572016-02-22 17:51:28 +0000323 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000324 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000325 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
326 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
327 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000328 // Do an initial analysis for each basic block and find all the potential
329 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000330 bool Change = false;
331 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000332 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000333 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000334 Tokens.pop_back();
335 BBInfo &BBI = Token->BBI;
336 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000337 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000338 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000339
Evan Cheng4dd31a72007-06-11 22:26:22 +0000340 // If the block has been evicted out of the queue or it has already been
341 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000342 if (BBI.IsDone)
343 BBI.IsEnqueued = false;
344 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000345 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000346
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000347 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000348
Evan Cheng312b7232007-06-04 06:47:22 +0000349 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000350 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000351 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000352 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000353 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000354 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000355 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000356 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
357 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000358 << "): BB#" << BBI.BB->getNumber() << " ("
359 << ((Kind == ICSimpleFalse)
360 ? BBI.FalseBB->getNumber()
361 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000362 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000363 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000364 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000365 if (isFalse) ++NumSimpleFalse;
366 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000367 }
Evan Cheng312b7232007-06-04 06:47:22 +0000368 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000369 }
Evan Chengd0e66912007-05-23 07:23:16 +0000370 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000371 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000372 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000373 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000374 bool isFalse = Kind == ICTriangleFalse;
375 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000376 if (DisableTriangle && !isFalse && !isRev) break;
377 if (DisableTriangleR && !isFalse && isRev) break;
378 if (DisableTriangleF && isFalse && !isRev) break;
379 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000380 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000381 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000382 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000383 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000384 DEBUG(dbgs() << " rev");
385 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000386 << BBI.TrueBB->getNumber() << ",F:"
387 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000388 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000389 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000390 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000391 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000392 if (isRev) ++NumTriangleFRev;
393 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000394 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000395 if (isRev) ++NumTriangleRev;
396 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000397 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000398 }
Evan Chengd0e66912007-05-23 07:23:16 +0000399 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000400 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000401 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000402 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000403 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000404 << BBI.TrueBB->getNumber() << ",F:"
405 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000406 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000407 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000408 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000409 break;
410 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000411 }
412
Evan Cheng312b7232007-06-04 06:47:22 +0000413 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000414
Evan Cheng92fb5452007-06-15 07:36:12 +0000415 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
416 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
417 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000418 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000419 }
Evan Chengd0e66912007-05-23 07:23:16 +0000420
Evan Chengd0e66912007-05-23 07:23:16 +0000421 if (!Change)
422 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000423 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000424 }
Evan Cheng478b8052007-05-18 01:55:58 +0000425
Evan Cheng3a51c852007-06-16 09:34:52 +0000426 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000427 BBAnalysis.clear();
428
Evan Chengcf9e8a92010-06-18 22:17:13 +0000429 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000430 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000431 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000432 getAnalysisIfAvailable<MachineModuleInfo>());
433 }
434
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000435 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000436 return MadeChange;
437}
438
Evan Cheng3a51c852007-06-16 09:34:52 +0000439/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
440/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000441static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000442 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000443 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
444 E = BB->succ_end(); SI != E; ++SI) {
445 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000446 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000447 return SuccBB;
448 }
Craig Topperc0196b12014-04-14 00:51:57 +0000449 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000450}
451
Evan Cheng3a51c852007-06-16 09:34:52 +0000452/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000453/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000454bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000455 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000456 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
457 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000458 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000459 std::swap(BBI.TrueBB, BBI.FalseBB);
460 return true;
461 }
462 return false;
463}
464
Evan Cheng2117d1f2007-06-09 01:03:43 +0000465/// getNextBlock - Returns the next block in the function blocks ordering. If
466/// it is the end, returns NULL.
467static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000468 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000469 MachineFunction::iterator E = BB->getParent()->end();
470 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000471 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000472 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000473}
474
Evan Cheng7783f822007-06-08 09:36:04 +0000475/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000476/// predecessor) forms a valid simple shape for ifcvt. It also returns the
477/// number of instructions that the ifcvt would need to duplicate if performed
478/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000479bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000480 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000481 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000482 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000483 return false;
484
Evan Chenga955c022007-06-19 21:45:13 +0000485 if (TrueBBI.IsBrAnalyzable)
486 return false;
487
Evan Cheng23402fc2007-06-15 21:18:05 +0000488 if (TrueBBI.BB->pred_size() > 1) {
489 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000490 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000491 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000492 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000493 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000494 }
495
Evan Chenga955c022007-06-19 21:45:13 +0000496 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000497}
498
Evan Cheng7783f822007-06-08 09:36:04 +0000499/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000500/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000501/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000502/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000503/// returns the number of instructions that the ifcvt would need to duplicate
504/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000505bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000506 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000507 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000508 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000509 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000510 return false;
511
Evan Cheng23402fc2007-06-15 21:18:05 +0000512 if (TrueBBI.BB->pred_size() > 1) {
513 if (TrueBBI.CannotBeCopied)
514 return false;
515
Evan Cheng92fb5452007-06-15 07:36:12 +0000516 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000517 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000518 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000519 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000520 --Size;
521 else {
522 MachineBasicBlock *FExit = FalseBranch
523 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
524 if (FExit)
525 // Require a conditional branch
526 ++Size;
527 }
528 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000529 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000530 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000531 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000532 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000533
Evan Cheng7783f822007-06-08 09:36:04 +0000534 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
535 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000536 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000537 if (++I == TrueBBI.BB->getParent()->end())
538 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000539 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000540 }
Evan Cheng7783f822007-06-08 09:36:04 +0000541 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000542}
543
Evan Cheng7783f822007-06-08 09:36:04 +0000544/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000545/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000546bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
547 unsigned &Dups1, unsigned &Dups2) const {
548 Dups1 = Dups2 = 0;
549 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
550 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000551 return false;
552
Evan Cheng2117d1f2007-06-09 01:03:43 +0000553 MachineBasicBlock *TT = TrueBBI.TrueBB;
554 MachineBasicBlock *FT = FalseBBI.TrueBB;
555
556 if (!TT && blockAlwaysFallThrough(TrueBBI))
557 TT = getNextBlock(TrueBBI.BB);
558 if (!FT && blockAlwaysFallThrough(FalseBBI))
559 FT = getNextBlock(FalseBBI.BB);
560 if (TT != FT)
561 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000562 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000563 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000564 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
565 return false;
566
567 // FIXME: Allow true block to have an early exit?
568 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
569 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000570 return false;
571
Bob Wilsone1961fe2010-10-26 00:02:24 +0000572 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000573 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
574 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000575 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
576 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
577 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000578 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000579 if (TIB->isDebugValue()) {
580 while (TIB != TIE && TIB->isDebugValue())
581 ++TIB;
582 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000583 break;
584 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000585 if (FIB->isDebugValue()) {
586 while (FIB != FIE && FIB->isDebugValue())
587 ++FIB;
588 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000589 break;
590 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000591 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000592 break;
593 ++Dups1;
594 ++TIB;
595 ++FIB;
596 }
597
598 // Now, in preparation for counting duplicate instructions at the ends of the
599 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000600 // If both blocks are returning don't skip the branches, since they will
601 // likely be both identical return instructions. In such cases the return
602 // can be left unpredicated.
603 // Check for already containing all of the block.
604 if (TIB == TIE || FIB == FIE)
605 return true;
606 --TIE;
607 --FIE;
608 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
609 while (TIE != TIB && TIE->isBranch())
610 --TIE;
611 while (FIE != FIB && FIE->isBranch())
612 --FIE;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000613 }
614
615 // If Dups1 includes all of a block, then don't count duplicate
616 // instructions at the end of the blocks.
617 if (TIB == TIE || FIB == FIE)
618 return true;
619
620 // Count duplicate instructions at the ends of the blocks.
621 while (TIE != TIB && FIE != FIB) {
622 // Skip dbg_value instructions. These do not count.
623 if (TIE->isDebugValue()) {
624 while (TIE != TIB && TIE->isDebugValue())
625 --TIE;
626 if (TIE == TIB)
627 break;
628 }
629 if (FIE->isDebugValue()) {
630 while (FIE != FIB && FIE->isDebugValue())
631 --FIE;
632 if (FIE == FIB)
633 break;
634 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000635 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000636 break;
637 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000638 --TIE;
639 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000640 }
641
642 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000643}
644
Evan Cheng4dd31a72007-06-11 22:26:22 +0000645/// ScanInstructions - Scan all the instructions in the block to determine if
646/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000647/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000648/// instruction which can clobber a predicate (e.g. condition code register).
649/// If so, the block is not predicable unless it's the last instruction.
650void IfConverter::ScanInstructions(BBInfo &BBI) {
651 if (BBI.IsDone)
652 return;
653
Evan Chengc5adcca2012-06-08 21:53:50 +0000654 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000655 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000656 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000657 BBI.BrCond.clear();
658 BBI.IsBrAnalyzable =
659 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000660 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000661
662 if (BBI.BrCond.size()) {
663 // No false branch. This BB must end with a conditional branch and a
664 // fallthrough.
665 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000666 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000667 if (!BBI.FalseBB) {
668 // Malformed bcc? True and false blocks are the same?
669 BBI.IsUnpredicable = true;
670 return;
671 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000672 }
673
674 // Then scan all the instructions.
675 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000676 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000677 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000678 BBI.ClobbersPred = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000679 for (auto &MI : *BBI.BB) {
680 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000681 continue;
682
Justin Lebar7dba2e02016-04-15 01:38:41 +0000683 // It's unsafe to duplicate convergent instructions in this context, so set
684 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
685 // following CFG, which is subject to our "simple" transformation.
686 //
687 // BB0 // if (c1) goto BB1; else goto BB2;
688 // / \
689 // BB1 |
690 // | BB2 // if (c2) goto TBB; else goto FBB;
691 // | / |
692 // | / |
693 // TBB |
694 // | |
695 // | FBB
696 // |
697 // exit
698 //
699 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
700 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
701 // TBB contains a convergent instruction. This is safe iff doing so does
702 // not add a control-flow dependency to the convergent instruction -- i.e.,
703 // it's safe iff the set of control flows that leads us to the convergent
704 // instruction does not get smaller after the transformation.
705 //
706 // Originally we executed TBB if c1 || c2. After the transformation, there
707 // are two copies of TBB's instructions. We get to the first if c1, and we
708 // get to the second if !c1 && c2.
709 //
710 // There are clearly fewer ways to satisfy the condition "c1" than
711 // "c1 || c2". Since we've shrunk the set of control flows which lead to
712 // our convergent instruction, the transformation is unsafe.
713 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000714 BBI.CannotBeCopied = true;
715
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000716 bool isPredicated = TII->isPredicated(MI);
717 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000718
Joey Goulya5153cb2013-09-09 14:21:49 +0000719 // A conditional branch is not predicable, but it may be eliminated.
720 if (isCondBr)
721 continue;
722
723 if (!isPredicated) {
724 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000725 unsigned ExtraPredCost = TII->getPredicationCost(MI);
726 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000727 if (NumCycles > 1)
728 BBI.ExtraCost += NumCycles-1;
729 BBI.ExtraCost2 += ExtraPredCost;
730 } else if (!AlreadyPredicated) {
731 // FIXME: This instruction is already predicated before the
732 // if-conversion pass. It's probably something like a conditional move.
733 // Mark this block unpredicable for now.
734 BBI.IsUnpredicable = true;
735 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000736 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000737
738 if (BBI.ClobbersPred && !isPredicated) {
739 // Predicate modification instruction should end the block (except for
740 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000741 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000742 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000743 BBI.IsUnpredicable = true;
744 return;
745 }
746
Evan Chengfbc73092007-07-10 17:50:43 +0000747 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
748 // still potentially predicable.
749 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000750 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000751 BBI.ClobbersPred = true;
752
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000753 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000754 BBI.IsUnpredicable = true;
755 return;
756 }
757 }
758}
759
760/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
761/// predicated by the specified predicate.
762bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000763 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000764 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000765 // If the block is dead or unpredicable, then it cannot be predicated.
766 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000767 return false;
768
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000769 // If it is already predicated but we couldn't analyze its terminator, the
770 // latter might fallthrough, but we can't determine where to.
771 // Conservatively avoid if-converting again.
772 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
773 return false;
774
Quentin Colombetbdab2272013-07-24 20:20:37 +0000775 // If it is already predicated, check if the new predicate subsumes
776 // its predicate.
777 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000778 return false;
779
780 if (BBI.BrCond.size()) {
781 if (!isTriangle)
782 return false;
783
Bob Wilson2371f4f2009-05-13 23:25:24 +0000784 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000785 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
786 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000787 if (RevBranch) {
788 if (TII->ReverseBranchCondition(Cond))
789 return false;
790 }
791 if (TII->ReverseBranchCondition(RevPred) ||
792 !TII->SubsumesPredicate(Cond, RevPred))
793 return false;
794 }
795
796 return true;
797}
798
Evan Cheng7783f822007-06-08 09:36:04 +0000799/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000800/// the specified block. Record its successors and whether it looks like an
801/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000802void IfConverter::AnalyzeBlock(
803 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000804 struct BBState {
805 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
806 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000807
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000808 /// This flag is true if MBB's successors have been analyzed.
809 bool SuccsAnalyzed;
810 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000811
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000812 // Push MBB to the stack.
813 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000814
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000815 while (!BBStack.empty()) {
816 BBState &State = BBStack.back();
817 MachineBasicBlock *BB = State.MBB;
818 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000819
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000820 if (!State.SuccsAnalyzed) {
821 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
822 BBStack.pop_back();
823 continue;
824 }
Evan Cheng9030b982007-06-06 10:16:17 +0000825
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000826 BBI.BB = BB;
827 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000828
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000829 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000830
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000831 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
832 // not considered for ifcvt anymore.
833 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
834 BBI.IsBeingAnalyzed = false;
835 BBI.IsAnalyzed = true;
836 BBStack.pop_back();
837 continue;
838 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000839
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000840 // Do not ifcvt if either path is a back edge to the entry block.
841 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
842 BBI.IsBeingAnalyzed = false;
843 BBI.IsAnalyzed = true;
844 BBStack.pop_back();
845 continue;
846 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000847
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000848 // Do not ifcvt if true and false fallthrough blocks are the same.
849 if (!BBI.FalseBB) {
850 BBI.IsBeingAnalyzed = false;
851 BBI.IsAnalyzed = true;
852 BBStack.pop_back();
853 continue;
854 }
Evan Cheng7783f822007-06-08 09:36:04 +0000855
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000856 // Push the False and True blocks to the stack.
857 State.SuccsAnalyzed = true;
858 BBStack.push_back(BBI.FalseBB);
859 BBStack.push_back(BBI.TrueBB);
860 continue;
861 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000862
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000863 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
864 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000865
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000866 if (TrueBBI.IsDone && FalseBBI.IsDone) {
867 BBI.IsBeingAnalyzed = false;
868 BBI.IsAnalyzed = true;
869 BBStack.pop_back();
870 continue;
871 }
872
873 SmallVector<MachineOperand, 4>
874 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
875 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
876
877 unsigned Dups = 0;
878 unsigned Dups2 = 0;
879 bool TNeedSub = !TrueBBI.Predicate.empty();
880 bool FNeedSub = !FalseBBI.Predicate.empty();
881 bool Enqueued = false;
882
883 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
884
885 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
886 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
887 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
888 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000889 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000890 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000891 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
892 FeasibilityAnalysis(FalseBBI, RevCond)) {
893 // Diamond:
894 // EBB
895 // / \_
896 // | |
897 // TBB FBB
898 // \ /
899 // TailBB
900 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000901 Tokens.push_back(llvm::make_unique<IfcvtToken>(
902 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000903 Enqueued = true;
904 }
905
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000906 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
907 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
908 TrueBBI.ExtraCost2, Prediction) &&
909 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
910 // Triangle:
911 // EBB
912 // | \_
913 // | |
914 // | TBB
915 // | /
916 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000917 Tokens.push_back(
918 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000919 Enqueued = true;
920 }
921
922 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
923 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
924 TrueBBI.ExtraCost2, Prediction) &&
925 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000926 Tokens.push_back(
927 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000928 Enqueued = true;
929 }
930
931 if (ValidSimple(TrueBBI, Dups, Prediction) &&
932 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
933 TrueBBI.ExtraCost2, Prediction) &&
934 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
935 // Simple (split, no rejoin):
936 // EBB
937 // | \_
938 // | |
939 // | TBB---> exit
940 // |
941 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000942 Tokens.push_back(
943 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000944 Enqueued = true;
945 }
946
947 if (CanRevCond) {
948 // Try the other path...
949 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
950 Prediction.getCompl()) &&
951 MeetIfcvtSizeLimit(*FalseBBI.BB,
952 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
953 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
954 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000955 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
956 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000957 Enqueued = true;
958 }
959
960 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
961 Prediction.getCompl()) &&
962 MeetIfcvtSizeLimit(*FalseBBI.BB,
963 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000964 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000965 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000966 Tokens.push_back(
967 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000968 Enqueued = true;
969 }
970
971 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
972 MeetIfcvtSizeLimit(*FalseBBI.BB,
973 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
974 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
975 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000976 Tokens.push_back(
977 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000978 Enqueued = true;
979 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000980 }
981
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000982 BBI.IsEnqueued = Enqueued;
983 BBI.IsBeingAnalyzed = false;
984 BBI.IsAnalyzed = true;
985 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000986 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000987}
988
Evan Cheng905a8f42007-05-30 19:49:19 +0000989/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000990/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000991void IfConverter::AnalyzeBlocks(
992 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000993 for (auto &BB : MF)
994 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000995
Evan Cheng20e05992007-06-01 00:12:12 +0000996 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000997 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000998}
999
Evan Cheng288f1542007-06-08 22:01:07 +00001000/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1001/// that all the intervening blocks are empty (given BB can fall through to its
1002/// next block).
1003static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001004 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001005 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001006 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001007 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001008 while (I != TI) {
1009 // Check isSuccessor to avoid case where the next block is empty, but
1010 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001011 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001012 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001013 PI = I++;
1014 }
Evan Cheng312b7232007-06-04 06:47:22 +00001015 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001016}
1017
Evan Cheng51eb2c32007-06-18 08:37:25 +00001018/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1019/// to determine if it can be if-converted. If predecessor is already enqueued,
1020/// dequeue it!
1021void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001022 for (const auto &Predecessor : BB->predecessors()) {
1023 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001024 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001025 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001026 PBBI.IsAnalyzed = false;
1027 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001028 }
1029}
1030
Evan Chengc2237ce2007-05-29 22:31:16 +00001031/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1032///
1033static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1034 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001035 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001036 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001037 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001038}
1039
Evan Cheng288f1542007-06-08 22:01:07 +00001040/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1041/// successors.
1042void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001043 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001044 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001045 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1046 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001047}
1048
Matthias Braund616ccc2013-10-11 19:04:37 +00001049/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1050/// values defined in MI which are not live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001051static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001052 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001053 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001054
Pete Cooper7605e372015-05-05 20:14:22 +00001055 // Now add the implicit uses for each of the clobbered values.
1056 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001057 // FIXME: Const cast here is nasty, but better than making StepForward
1058 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001059 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1060 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001061 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001062 if (Op.isRegMask()) {
1063 // First handle regmasks. They clobber any entries in the mask which
1064 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001065 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001066
1067 // We also need to add an implicit def of this register for the later
1068 // use to read from.
1069 // For the register allocator to have allocated a register clobbered
1070 // by the call which is used later, it must be the case that
1071 // the call doesn't return.
1072 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1073 continue;
1074 }
1075 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001076 if (Op.isDead()) {
1077 // If we found a dead def, but it needs to be live, then remove the dead
1078 // flag.
1079 if (Redefs.contains(Op.getReg()))
1080 Op.setIsDead(false);
1081 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001082 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001083 }
1084}
1085
1086/**
1087 * Remove kill flags from operands with a registers in the @p DontKill set.
1088 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001089static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001090 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001091 if (!O->isReg() || !O->isKill())
1092 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001093 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001094 O->setIsKill(false);
1095 }
1096}
1097
1098/**
1099 * Walks a range of machine instructions and removes kill flags for registers
1100 * in the @p DontKill set.
1101 */
1102static void RemoveKills(MachineBasicBlock::iterator I,
1103 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001104 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001105 const MCRegisterInfo &MCRI) {
1106 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001107 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001108}
1109
Evan Cheng312b7232007-06-04 06:47:22 +00001110/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001111///
Evan Cheng3a51c852007-06-16 09:34:52 +00001112bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001113 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1114 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1115 BBInfo *CvtBBI = &TrueBBI;
1116 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001117
Owen Anderson4f6bf042008-08-14 22:49:33 +00001118 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001119 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001120 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001121
Evan Cheng51eb2c32007-06-18 08:37:25 +00001122 if (CvtBBI->IsDone ||
1123 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001124 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001125 BBI.IsAnalyzed = false;
1126 CvtBBI->IsAnalyzed = false;
1127 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001128 }
Evan Chengd0e66912007-05-23 07:23:16 +00001129
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001130 if (CvtBBI->BB->hasAddressTaken())
1131 // Conservatively abort if-conversion if BB's address is taken.
1132 return false;
1133
Evan Cheng3a51c852007-06-16 09:34:52 +00001134 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001135 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001136 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001137
Bob Wilson45814342010-06-19 05:33:57 +00001138 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001139 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001140 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001141 Redefs.addLiveIns(*CvtBBI->BB);
1142 Redefs.addLiveIns(*NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001143
1144 // Compute a set of registers which must not be killed by instructions in
1145 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001146 DontKill.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001147 DontKill.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001148
Evan Cheng92fb5452007-06-15 07:36:12 +00001149 if (CvtBBI->BB->pred_size() > 1) {
1150 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001151 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001152 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001153 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001154
1155 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1156 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001157 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001158 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001159 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001160 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001161
Evan Cheng92fb5452007-06-15 07:36:12 +00001162 // Merge converted block into entry block.
1163 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1164 MergeBlocks(BBI, *CvtBBI);
1165 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001166
Evan Chenge4ec9182007-06-06 02:08:52 +00001167 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001168 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001169 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001170 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001171 // Now ifcvt'd block will look like this:
1172 // BB:
1173 // ...
1174 // t, f = cmp
1175 // if t op
1176 // b BBf
1177 //
1178 // We cannot further ifcvt this block because the unconditional branch
1179 // will have to be predicated on the new condition, that will not be
1180 // available if cmp executes.
1181 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001182 }
Evan Chenge26c0912007-05-21 22:22:58 +00001183
Evan Cheng288f1542007-06-08 22:01:07 +00001184 RemoveExtraEdges(BBI);
1185
Evan Chengd0e66912007-05-23 07:23:16 +00001186 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001187 if (!IterIfcvt)
1188 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001189 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001190 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001191
1192 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001193 return true;
1194}
1195
Evan Chengaf716102007-05-16 21:54:37 +00001196/// IfConvertTriangle - If convert a triangle sub-CFG.
1197///
Evan Cheng3a51c852007-06-16 09:34:52 +00001198bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001199 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001200 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1201 BBInfo *CvtBBI = &TrueBBI;
1202 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001203 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001204
Owen Anderson4f6bf042008-08-14 22:49:33 +00001205 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001206 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001207 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001208
Evan Cheng51eb2c32007-06-18 08:37:25 +00001209 if (CvtBBI->IsDone ||
1210 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001211 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001212 BBI.IsAnalyzed = false;
1213 CvtBBI->IsAnalyzed = false;
1214 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001215 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001216
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001217 if (CvtBBI->BB->hasAddressTaken())
1218 // Conservatively abort if-conversion if BB's address is taken.
1219 return false;
1220
Evan Cheng3a51c852007-06-16 09:34:52 +00001221 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001222 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001223 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001224
Evan Cheng3a51c852007-06-16 09:34:52 +00001225 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001226 if (ReverseBranchCondition(*CvtBBI)) {
1227 // BB has been changed, modify its predecessors (except for this
1228 // one) so they don't get ifcvt'ed based on bad intel.
1229 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1230 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1231 MachineBasicBlock *PBB = *PI;
1232 if (PBB == BBI.BB)
1233 continue;
1234 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1235 if (PBBI.IsEnqueued) {
1236 PBBI.IsAnalyzed = false;
1237 PBBI.IsEnqueued = false;
1238 }
Evan Chengadd97762007-06-14 23:34:09 +00001239 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001240 }
1241 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001242
Bob Wilson45814342010-06-19 05:33:57 +00001243 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001244 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001245 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001246 Redefs.addLiveIns(*CvtBBI->BB);
1247 Redefs.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001248
Andrew Trick276dd452013-10-14 20:45:17 +00001249 DontKill.clear();
1250
Craig Topperc0196b12014-04-14 00:51:57 +00001251 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001252 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001253
Manman Renb6819182014-01-29 23:18:47 +00001254 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001255 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1256 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1257 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1258 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1259 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001260 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001261
Bob Wilson1e5da552010-06-29 00:55:23 +00001262 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001263 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001264 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001265 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001266 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001267
1268 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1269 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001270 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001271 } else {
1272 // Predicate the 'true' block after removing its branch.
1273 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001274 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001275
Evan Cheng0598b2d2007-06-18 22:44:57 +00001276 // Now merge the entry of the triangle with the true block.
1277 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001278 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001279 }
1280
Evan Cheng312b7232007-06-04 06:47:22 +00001281 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001282 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001283 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1284 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001285 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001286 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001287
Cong Houd97c1002015-12-01 05:29:22 +00001288 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1289 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1290 // Prob(BBI.BB, NextBBI->BB) +
1291 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1292 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1293 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1294 auto NewTrueBB = getNextBlock(BBI.BB);
1295 auto NewNext = BBNext + BBCvt * CvtNext;
1296 auto NewTrueBBIter =
1297 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001298 if (NewTrueBBIter != BBI.BB->succ_end())
1299 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001300
1301 auto NewFalse = BBCvt * CvtFalse;
1302 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1303 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001304 }
Evan Cheng7783f822007-06-08 09:36:04 +00001305
1306 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001307 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001308 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001309 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001310 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001311 if (!isFallThrough) {
1312 // Only merge them if the true block does not fallthrough to the false
1313 // block. By not merging them, we make it possible to iteratively
1314 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001315 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001316 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1317 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001318 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001319 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001320 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001321 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1322 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001323 }
Evan Cheng7783f822007-06-08 09:36:04 +00001324 // Mixed predicated and unpredicated code. This cannot be iteratively
1325 // predicated.
1326 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001327 }
Evan Chenge26c0912007-05-21 22:22:58 +00001328
Evan Cheng288f1542007-06-08 22:01:07 +00001329 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001330
Evan Chengd0e66912007-05-23 07:23:16 +00001331 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001332 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001333 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001334 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001335 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001336 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001337 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001338
1339 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001340 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001341}
1342
Evan Chengaf716102007-05-16 21:54:37 +00001343/// IfConvertDiamond - If convert a diamond sub-CFG.
1344///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001345bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1346 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001347 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001348 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001349 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001350 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001351 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001352 if (blockAlwaysFallThrough(TrueBBI))
1353 TailBB = FalseBBI.TrueBB;
1354 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001355 }
Evan Chenge26c0912007-05-21 22:22:58 +00001356
Evan Cheng51eb2c32007-06-18 08:37:25 +00001357 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1358 TrueBBI.BB->pred_size() > 1 ||
1359 FalseBBI.BB->pred_size() > 1) {
1360 // Something has changed. It's no longer safe to predicate these blocks.
1361 BBI.IsAnalyzed = false;
1362 TrueBBI.IsAnalyzed = false;
1363 FalseBBI.IsAnalyzed = false;
1364 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001365 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001366
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001367 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1368 // Conservatively abort if-conversion if either BB has its address taken.
1369 return false;
1370
Bob Wilson1e5da552010-06-29 00:55:23 +00001371 // Put the predicated instructions from the 'true' block before the
1372 // instructions from the 'false' block, unless the true block would clobber
1373 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001374 BBInfo *BBI1 = &TrueBBI;
1375 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001376 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001377 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001378 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001379 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1380 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001381
Evan Cheng3a51c852007-06-16 09:34:52 +00001382 // Figure out the more profitable ordering.
1383 bool DoSwap = false;
1384 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1385 DoSwap = true;
1386 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001387 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001388 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001389 }
1390 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001391 std::swap(BBI1, BBI2);
1392 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001393 }
Evan Cheng79484222007-06-05 23:46:14 +00001394
Evan Cheng51eb2c32007-06-18 08:37:25 +00001395 // Remove the conditional branch from entry to the blocks.
1396 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1397
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001398 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001399 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001400 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001401 Redefs.addLiveIns(*BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001402
Evan Cheng51eb2c32007-06-18 08:37:25 +00001403 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001404 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001405 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1406 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001407 BBI1->NonPredSize -= NumDups1;
1408 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001409
1410 // Skip past the dups on each side separately since there may be
1411 // differing dbg_value entries.
1412 for (unsigned i = 0; i < NumDups1; ++DI1) {
1413 if (!DI1->isDebugValue())
1414 ++i;
1415 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001416 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001417 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001418 if (!DI2->isDebugValue())
1419 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001420 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001421
Matthias Braund616ccc2013-10-11 19:04:37 +00001422 // Compute a set of registers which must not be killed by instructions in BB1:
1423 // This is everything used+live in BB2 after the duplicated instructions. We
1424 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001425 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001426 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1427 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001428 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001429 }
1430
1431 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1432 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001433 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1434 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001435 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001436 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1437 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1438
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001439 // Remove branch from the 'true' block, unless it was not analyzable.
1440 // Non-analyzable branches need to be preserved, since in such cases,
1441 // the CFG structure is not an actual diamond (the join block may not
1442 // be present).
1443 if (BBI1->IsBrAnalyzable)
1444 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1445 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001446 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001447 for (unsigned i = 0; i != NumDups2; ) {
1448 // NumDups2 only counted non-dbg_value instructions, so this won't
1449 // run off the head of the list.
1450 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001451 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001452 // skip dbg_value instructions
1453 if (!DI1->isDebugValue())
1454 ++i;
1455 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001456 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001457
Matthias Braund616ccc2013-10-11 19:04:37 +00001458 // Kill flags in the true block for registers living into the false block
1459 // must be removed.
1460 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1461
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001462 // Remove 'false' block branch (unless it was not analyzable), and find
1463 // the last instruction to predicate.
1464 if (BBI2->IsBrAnalyzable)
1465 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001466 DI2 = BBI2->BB->end();
1467 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001468 // NumDups2 only counted non-dbg_value instructions, so this won't
1469 // run off the head of the list.
1470 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001471 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001472 // skip dbg_value instructions
1473 if (!DI2->isDebugValue())
1474 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001475 }
Evan Cheng4266a792011-12-19 22:01:30 +00001476
1477 // Remember which registers would later be defined by the false block.
1478 // This allows us not to predicate instructions in the true block that would
1479 // later be re-defined. That is, rather than
1480 // subeq r0, r1, #1
1481 // addne r0, r1, #1
1482 // generate:
1483 // sub r0, r1, #1
1484 // addne r0, r1, #1
1485 SmallSet<unsigned, 4> RedefsByFalse;
1486 SmallSet<unsigned, 4> ExtUses;
1487 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1488 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1489 if (FI->isDebugValue())
1490 continue;
1491 SmallVector<unsigned, 4> Defs;
1492 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1493 const MachineOperand &MO = FI->getOperand(i);
1494 if (!MO.isReg())
1495 continue;
1496 unsigned Reg = MO.getReg();
1497 if (!Reg)
1498 continue;
1499 if (MO.isDef()) {
1500 Defs.push_back(Reg);
1501 } else if (!RedefsByFalse.count(Reg)) {
1502 // These are defined before ctrl flow reach the 'false' instructions.
1503 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001504 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1505 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001506 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001507 }
1508 }
1509
1510 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1511 unsigned Reg = Defs[i];
1512 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001513 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1514 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001515 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001516 }
1517 }
1518 }
1519 }
1520
1521 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001522 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001523
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001524 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1525 // a non-predicated in BBI2, then we don't want to predicate the one from
1526 // BBI2. The reason is that if we merged these blocks, we would end up with
1527 // two predicated terminators in the same block.
1528 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1529 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1530 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001531 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1532 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001533 --DI2;
1534 }
1535
Evan Cheng4266a792011-12-19 22:01:30 +00001536 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001537 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001538
Evan Cheng0598b2d2007-06-18 22:44:57 +00001539 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001540 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1541 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001542
Bob Wilson2371f4f2009-05-13 23:25:24 +00001543 // If the if-converted block falls through or unconditionally branches into
1544 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001545 // fold the tail block in as well. Otherwise, unless it falls through to the
1546 // tail, add a unconditional branch to it.
1547 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001548 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001549 bool CanMergeTail = !TailBBI.HasFallThrough &&
1550 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001551 // The if-converted block can still have a predicated terminator
1552 // (e.g. a predicated return). If that is the case, we cannot merge
1553 // it with the tail block.
1554 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001555 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001556 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001557 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1558 // check if there are any other predecessors besides those.
1559 unsigned NumPreds = TailBB->pred_size();
1560 if (NumPreds > 1)
1561 CanMergeTail = false;
1562 else if (NumPreds == 1 && CanMergeTail) {
1563 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1564 if (*PI != BBI1->BB && *PI != BBI2->BB)
1565 CanMergeTail = false;
1566 }
1567 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001568 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001569 TailBBI.IsDone = true;
1570 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001571 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001572 InsertUncondBranch(BBI.BB, TailBB, TII);
1573 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001574 }
Evan Chenge26c0912007-05-21 22:22:58 +00001575 }
1576
Bob Wilson1e5da552010-06-29 00:55:23 +00001577 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1578 // which can happen here if TailBB is unanalyzable and is merged, so
1579 // explicitly remove BBI1 and BBI2 as successors.
1580 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001581 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001582 RemoveExtraEdges(BBI);
1583
Evan Cheng79484222007-06-05 23:46:14 +00001584 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001585 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001586 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001587
1588 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001589 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001590}
1591
Evan Cheng4266a792011-12-19 22:01:30 +00001592static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001593 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001594 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001595 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001596 return false;
1597
1598 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1599 const MachineOperand &MO = MI->getOperand(i);
1600 if (!MO.isReg())
1601 continue;
1602 unsigned Reg = MO.getReg();
1603 if (!Reg)
1604 continue;
1605 if (MO.isDef() && !LaterRedefs.count(Reg))
1606 return false;
1607 }
1608
1609 return true;
1610}
1611
Evan Cheng51eb2c32007-06-18 08:37:25 +00001612/// PredicateBlock - Predicate instructions from the start of the block to the
1613/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001614void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001615 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001616 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001617 SmallSet<unsigned, 4> *LaterRedefs) {
1618 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001619 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001620 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001621 if (I->isDebugValue() || TII->isPredicated(*I))
Evan Chengd0e66912007-05-23 07:23:16 +00001622 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001623 // It may be possible not to predicate an instruction if it's the 'true'
1624 // side of a diamond and the 'false' side may re-define the instruction's
1625 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001626 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001627 AnyUnpred = true;
1628 continue;
1629 }
1630 // If any instruction is predicated, then every instruction after it must
1631 // be predicated.
1632 MaySpec = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001633 if (!TII->PredicateInstruction(*I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001634#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001635 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001636#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001637 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001638 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001639
Bob Wilson45814342010-06-19 05:33:57 +00001640 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001641 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001642 UpdatePredRedefs(*I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001643 }
Evan Chengd0e66912007-05-23 07:23:16 +00001644
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001645 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001646
Evan Cheng92fb5452007-06-15 07:36:12 +00001647 BBI.IsAnalyzed = false;
1648 BBI.NonPredSize = 0;
1649
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001650 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001651 if (AnyUnpred)
1652 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001653}
1654
Evan Cheng92fb5452007-06-15 07:36:12 +00001655/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1656/// the destination block. Skip end of block branches if IgnoreBr is true.
1657void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001658 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001659 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001660 MachineFunction &MF = *ToBBI.BB->getParent();
1661
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001662 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001663 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001664 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001665 break;
1666
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001667 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001668 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001669 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001670 unsigned ExtraPredCost = TII->getPredicationCost(I);
1671 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001672 if (NumCycles > 1)
1673 ToBBI.ExtraCost += NumCycles-1;
1674 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001675
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001676 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001677 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001678#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001679 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001680#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001681 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001682 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001683 }
1684
Bob Wilson45814342010-06-19 05:33:57 +00001685 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001686 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001687 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001688
1689 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001690 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001691 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001692 }
1693
Bob Wilson1e5da552010-06-29 00:55:23 +00001694 if (!IgnoreBr) {
1695 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1696 FromBBI.BB->succ_end());
1697 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001698 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001699
Bob Wilson1e5da552010-06-29 00:55:23 +00001700 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1701 MachineBasicBlock *Succ = Succs[i];
1702 // Fallthrough edge can't be transferred.
1703 if (Succ == FallThrough)
1704 continue;
1705 ToBBI.BB->addSuccessor(Succ);
1706 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001707 }
1708
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001709 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1710 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001711
1712 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1713 ToBBI.IsAnalyzed = false;
1714
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001715 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001716}
1717
Evan Cheng0f745da2007-05-18 00:20:58 +00001718/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001719/// This will leave FromBB as an empty block, so remove all of its
1720/// successor edges except for the fall-through edge. If AddEdges is true,
1721/// i.e., when FromBBI's branch is being moved, add those successor edges to
1722/// ToBBI.
1723void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001724 assert(!FromBBI.BB->hasAddressTaken() &&
1725 "Removing a BB whose address is taken!");
1726
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001727 // In case FromBBI.BB contains terminators (e.g. return instruction),
1728 // first move the non-terminator instructions, then the terminators.
1729 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1730 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1731 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1732
1733 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001734 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001735 ToTI = ToBBI.BB->end();
1736 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001737
Cong Houb9e8d482015-12-17 01:29:08 +00001738 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1739 // unknown probabilities into known ones.
1740 // FIXME: This usage is too tricky and in the future we would like to
1741 // eliminate all unknown probabilities in MBB.
1742 ToBBI.BB->normalizeSuccProbs();
1743
Cong Houd40105d2015-09-18 20:22:41 +00001744 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1745 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001746 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001747 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001748 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001749 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001750 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001751 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001752 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1753 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1754 // edge probability being merged to other edges when this edge is removed
1755 // later.
1756 ToBBI.BB->setSuccProbability(
1757 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1758 BranchProbability::getZero());
1759 }
1760
Cong Houd40105d2015-09-18 20:22:41 +00001761 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1762 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001763 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001764 if (Succ == FallThrough)
1765 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001766
Cong Houd97c1002015-12-01 05:29:22 +00001767 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001768 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001769 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1770 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1771 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1772 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1773 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001774
Cong Houd97c1002015-12-01 05:29:22 +00001775 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001776 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1777 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001778 // could just use the probabilities on FromBBI.BB's out-edges when adding
1779 // new successors.
1780 if (!To2FromProb.isZero())
1781 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001782 }
1783
Evan Chengbe9859e2007-06-07 02:12:15 +00001784 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001785
1786 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001787 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001788 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001789 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1790 // don't have to set C as A's successor as it already is. We only need to
1791 // update the edge probability on A->C. Note that B will not be
1792 // immediately removed from A's successors. It is possible that B->D is
1793 // not removed either if D is a fallthrough of B. Later the edge A->D
1794 // (generated here) and B->D will be combined into one edge. To maintain
1795 // correct edge probability of this combined edge, we need to set the edge
1796 // probability of A->B to zero, which is already done above. The edge
1797 // probability on A->D is calculated by scaling the original probability
1798 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001799 //
1800 // Before ifcvt: After ifcvt (assume B->D is kept):
1801 //
1802 // A A
1803 // /| /|\
1804 // / B / B|
1805 // | /| | ||
1806 // |/ | | |/
1807 // C D C D
1808 //
1809 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001810 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001811 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001812 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001813 else
Cong Houd97c1002015-12-01 05:29:22 +00001814 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001815 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001816 }
1817
Bob Wilson2371f4f2009-05-13 23:25:24 +00001818 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001819 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001820 FromBBI.BB->addSuccessor(NBB);
1821
Cong Houc1069892015-12-13 09:26:17 +00001822 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1823 // we've done above.
1824 ToBBI.BB->normalizeSuccProbs();
1825
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001826 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001827 FromBBI.Predicate.clear();
1828
Evan Chengd0e66912007-05-23 07:23:16 +00001829 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001830 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001831 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001832 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001833 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001834 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001835
Evan Cheng4dd31a72007-06-11 22:26:22 +00001836 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001837 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001838 ToBBI.IsAnalyzed = false;
1839 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001840}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001841
1842FunctionPass *
1843llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1844 return new IfConverter(Ftor);
1845}