blob: 42cb0487e25f3086d50cd1eb42645ef4485a6ddb [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
Jacques Pienaar71c30a12016-07-15 14:41:04 +000090 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000091 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000092 /// diamond shape), its size, whether it's predicable, and whether any
93 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000094 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000095 /// IsDone - True if BB is not to be considered for ifcvt.
96 /// IsBeingAnalyzed - True if BB is currently being analyzed.
97 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
98 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +000099 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000100 /// HasFallThrough - True if BB may fallthrough to the following BB.
101 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000102 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000103 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000104 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000105 /// ExtraCost - Extra cost for multi-cycle instructions.
106 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000107 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000108 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000109 /// BrCond - Conditions for end of block conditional branches.
110 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000111 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000112 bool IsDone : 1;
113 bool IsBeingAnalyzed : 1;
114 bool IsAnalyzed : 1;
115 bool IsEnqueued : 1;
116 bool IsBrAnalyzable : 1;
117 bool HasFallThrough : 1;
118 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000119 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000120 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000121 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000122 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000123 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000124 MachineBasicBlock *BB;
125 MachineBasicBlock *TrueBB;
126 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000127 SmallVector<MachineOperand, 4> BrCond;
128 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000129 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000130 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
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;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000167 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000168
Juergen Ributzka310034e2013-12-14 06:52:56 +0000169 LivePhysRegs Redefs;
170 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000171
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000174 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000175 std::function<bool(const Function &)> PredicateFtor;
176
Evan Chengf5e53a52007-05-16 02:00:57 +0000177 public:
178 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000179 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000180 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000181 initializeIfConverterPass(*PassRegistry::getPassRegistry());
182 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000183
Craig Topper4584cd52014-03-07 09:26:03 +0000184 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000185 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000186 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000187 MachineFunctionPass::getAnalysisUsage(AU);
188 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000189
Craig Topper4584cd52014-03-07 09:26:03 +0000190 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000191
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
194 MachineFunctionProperties::Property::AllVRegsAllocated);
195 }
196
Evan Chengf5e53a52007-05-16 02:00:57 +0000197 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000198 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000199 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000200 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000201 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000202 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000203 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000204 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
205 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000206 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000207 void AnalyzeBlock(MachineBasicBlock *MBB,
208 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000209 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000210 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000211 void AnalyzeBlocks(MachineFunction &MF,
212 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000213 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000214 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000215 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
216 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000217 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
218 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000219 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000220 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000221 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000222 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000223 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000224 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000225 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000226 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000227
Evan Chengdebf9c52010-11-03 00:45:17 +0000228 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
229 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000230 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000231 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000232 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000233 }
234
Evan Chengdebf9c52010-11-03 00:45:17 +0000235 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
236 unsigned TCycle, unsigned TExtra,
237 MachineBasicBlock &FBB,
238 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000239 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000240 return TCycle > 0 && FCycle > 0 &&
241 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000242 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000243 }
244
Evan Chengbe9859e2007-06-07 02:12:15 +0000245 // blockAlwaysFallThrough - Block ends without a terminator.
246 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000247 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000248 }
249
Evan Cheng3a51c852007-06-16 09:34:52 +0000250 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000251 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
252 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000253 int Incr1 = (C1->Kind == ICDiamond)
254 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
255 int Incr2 = (C2->Kind == ICDiamond)
256 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
257 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000258 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000259 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000260 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000261 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000262 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000263 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000264 // Favors diamond over triangle, etc.
265 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
266 return true;
267 else if (C1->Kind == C2->Kind)
268 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
269 }
270 }
271 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000272 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000273 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000274
Evan Chengf5e53a52007-05-16 02:00:57 +0000275 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000276}
Evan Chengf5e53a52007-05-16 02:00:57 +0000277
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000278char &llvm::IfConverterID = IfConverter::ID;
279
Owen Anderson8ac477f2010-10-12 19:48:12 +0000280INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000281INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000282INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000283
Evan Chengf5e53a52007-05-16 02:00:57 +0000284bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000285 if (skipFunction(*MF.getFunction()) ||
286 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000287 return false;
288
Eric Christopher3d4276f2015-01-27 07:31:29 +0000289 const TargetSubtargetInfo &ST = MF.getSubtarget();
290 TLI = ST.getTargetLowering();
291 TII = ST.getInstrInfo();
292 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000293 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000294 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000295 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000296 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000297
Evan Chengf5e53a52007-05-16 02:00:57 +0000298 if (!TII) return false;
299
Evan Chengc5adcca2012-06-08 21:53:50 +0000300 PreRegAlloc = MRI->isSSA();
301
302 bool BFChange = false;
303 if (!PreRegAlloc) {
304 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000305 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000306 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000307 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000308 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000309
David Greene72e47cd2010-01-04 22:02:01 +0000310 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000311 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000312
313 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000314 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000315 return false;
316 }
David Greene72e47cd2010-01-04 22:02:01 +0000317 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000318
Evan Chengf5e53a52007-05-16 02:00:57 +0000319 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000320 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000321
Justin Lebar3a7bc572016-02-22 17:51:28 +0000322 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000323 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000324 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
325 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
326 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000327 // Do an initial analysis for each basic block and find all the potential
328 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000329 bool Change = false;
330 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000331 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000332 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000333 Tokens.pop_back();
334 BBInfo &BBI = Token->BBI;
335 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000336 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000337 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000338
Evan Cheng4dd31a72007-06-11 22:26:22 +0000339 // If the block has been evicted out of the queue or it has already been
340 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000341 if (BBI.IsDone)
342 BBI.IsEnqueued = false;
343 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000344 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000345
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000346 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000347
Evan Cheng312b7232007-06-04 06:47:22 +0000348 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000349 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000350 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000351 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000352 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000353 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000354 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000355 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
356 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000357 << "): BB#" << BBI.BB->getNumber() << " ("
358 << ((Kind == ICSimpleFalse)
359 ? BBI.FalseBB->getNumber()
360 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000361 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000362 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000363 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000364 if (isFalse) ++NumSimpleFalse;
365 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000366 }
Evan Cheng312b7232007-06-04 06:47:22 +0000367 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000368 }
Evan Chengd0e66912007-05-23 07:23:16 +0000369 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000370 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000371 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000372 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000373 bool isFalse = Kind == ICTriangleFalse;
374 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000375 if (DisableTriangle && !isFalse && !isRev) break;
376 if (DisableTriangleR && !isFalse && isRev) break;
377 if (DisableTriangleF && isFalse && !isRev) break;
378 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000379 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000380 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000381 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000382 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000383 DEBUG(dbgs() << " rev");
384 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000385 << BBI.TrueBB->getNumber() << ",F:"
386 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000387 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000388 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000389 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000390 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000391 if (isRev) ++NumTriangleFRev;
392 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000393 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000394 if (isRev) ++NumTriangleRev;
395 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000396 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000397 }
Evan Chengd0e66912007-05-23 07:23:16 +0000398 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000399 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000400 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000401 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000402 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000403 << BBI.TrueBB->getNumber() << ",F:"
404 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000405 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000406 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000407 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000408 break;
409 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000410 }
411
Evan Cheng312b7232007-06-04 06:47:22 +0000412 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000413
Evan Cheng92fb5452007-06-15 07:36:12 +0000414 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
415 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
416 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000417 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000418 }
Evan Chengd0e66912007-05-23 07:23:16 +0000419
Evan Chengd0e66912007-05-23 07:23:16 +0000420 if (!Change)
421 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000422 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000423 }
Evan Cheng478b8052007-05-18 01:55:58 +0000424
Evan Cheng3a51c852007-06-16 09:34:52 +0000425 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000426 BBAnalysis.clear();
427
Evan Chengcf9e8a92010-06-18 22:17:13 +0000428 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000429 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000430 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000431 getAnalysisIfAvailable<MachineModuleInfo>());
432 }
433
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000434 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000435 return MadeChange;
436}
437
Evan Cheng3a51c852007-06-16 09:34:52 +0000438/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
439/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000440static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000441 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000442 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
443 E = BB->succ_end(); SI != E; ++SI) {
444 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000445 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000446 return SuccBB;
447 }
Craig Topperc0196b12014-04-14 00:51:57 +0000448 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000449}
450
Evan Cheng3a51c852007-06-16 09:34:52 +0000451/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000452/// branch. Swap block's 'true' and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000453bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000454 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000455 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
456 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000457 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000458 std::swap(BBI.TrueBB, BBI.FalseBB);
459 return true;
460 }
461 return false;
462}
463
Evan Cheng2117d1f2007-06-09 01:03:43 +0000464/// getNextBlock - Returns the next block in the function blocks ordering. If
465/// it is the end, returns NULL.
466static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000467 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000468 MachineFunction::iterator E = BB->getParent()->end();
469 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000470 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000471 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000472}
473
Evan Cheng7783f822007-06-08 09:36:04 +0000474/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000475/// predecessor) forms a valid simple shape for ifcvt. It also returns the
476/// number of instructions that the ifcvt would need to duplicate if performed
477/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000478bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000479 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000480 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000481 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000482 return false;
483
Evan Chenga955c022007-06-19 21:45:13 +0000484 if (TrueBBI.IsBrAnalyzable)
485 return false;
486
Evan Cheng23402fc2007-06-15 21:18:05 +0000487 if (TrueBBI.BB->pred_size() > 1) {
488 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000489 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000490 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000491 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000492 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000493 }
494
Evan Chenga955c022007-06-19 21:45:13 +0000495 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000496}
497
Evan Cheng7783f822007-06-08 09:36:04 +0000498/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000499/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000500/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000501/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000502/// returns the number of instructions that the ifcvt would need to duplicate
503/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000504bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000505 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000506 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000507 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000508 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000509 return false;
510
Evan Cheng23402fc2007-06-15 21:18:05 +0000511 if (TrueBBI.BB->pred_size() > 1) {
512 if (TrueBBI.CannotBeCopied)
513 return false;
514
Evan Cheng92fb5452007-06-15 07:36:12 +0000515 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000516 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000517 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000518 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000519 --Size;
520 else {
521 MachineBasicBlock *FExit = FalseBranch
522 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
523 if (FExit)
524 // Require a conditional branch
525 ++Size;
526 }
527 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000528 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000529 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000530 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000531 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000532
Evan Cheng7783f822007-06-08 09:36:04 +0000533 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
534 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000535 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000536 if (++I == TrueBBI.BB->getParent()->end())
537 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000538 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000539 }
Evan Cheng7783f822007-06-08 09:36:04 +0000540 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000541}
542
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000543static void countDuplicatedInstructions(
544 MachineBasicBlock::iterator &TIB,
545 MachineBasicBlock::iterator &FIB,
546 MachineBasicBlock::iterator &TIE,
547 MachineBasicBlock::iterator &FIE,
548 unsigned &Dups1, unsigned &Dups2,
549 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
550 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000551
Bob Wilsone1961fe2010-10-26 00:02:24 +0000552 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000553 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000554 if (TIB->isDebugValue()) {
555 while (TIB != TIE && TIB->isDebugValue())
556 ++TIB;
557 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000558 break;
559 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000560 if (FIB->isDebugValue()) {
561 while (FIB != FIE && FIB->isDebugValue())
562 ++FIB;
563 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000564 break;
565 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000566 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000567 break;
568 ++Dups1;
569 ++TIB;
570 ++FIB;
571 }
572
573 // Now, in preparation for counting duplicate instructions at the ends of the
574 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000575 // If both blocks are returning don't skip the branches, since they will
576 // likely be both identical return instructions. In such cases the return
577 // can be left unpredicated.
578 // Check for already containing all of the block.
579 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000580 return;
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000581 --TIE;
582 --FIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000583 if (!TBB.succ_empty() || !FBB.succ_empty()) {
584 if (SkipConditionalBranches) {
585 while (TIE != TIB && TIE->isBranch())
586 --TIE;
587 while (FIE != FIB && FIE->isBranch())
588 --FIE;
589 } else {
590 while (TIE != TIB && TIE->isUnconditionalBranch())
591 --TIE;
592 while (FIE != FIB && FIE->isUnconditionalBranch())
593 --FIE;
594 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000595 }
596
597 // If Dups1 includes all of a block, then don't count duplicate
598 // instructions at the end of the blocks.
599 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000600 return;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000601
602 // Count duplicate instructions at the ends of the blocks.
603 while (TIE != TIB && FIE != FIB) {
604 // Skip dbg_value instructions. These do not count.
605 if (TIE->isDebugValue()) {
606 while (TIE != TIB && TIE->isDebugValue())
607 --TIE;
608 if (TIE == TIB)
609 break;
610 }
611 if (FIE->isDebugValue()) {
612 while (FIE != FIB && FIE->isDebugValue())
613 --FIE;
614 if (FIE == FIB)
615 break;
616 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000617 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000618 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000619 // If we are trying to make sure the conditional branches are the same, we
620 // still don't want to count them.
621 if (SkipConditionalBranches || !TIE->isBranch())
622 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000623 --TIE;
624 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000625 }
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000626}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000627
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000628/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
629/// with their common predecessor) forms a valid diamond shape for ifcvt.
630bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
631 unsigned &Dups1, unsigned &Dups2) const {
632 Dups1 = Dups2 = 0;
633 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
634 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
635 return false;
636
637 MachineBasicBlock *TT = TrueBBI.TrueBB;
638 MachineBasicBlock *FT = FalseBBI.TrueBB;
639
640 if (!TT && blockAlwaysFallThrough(TrueBBI))
641 TT = getNextBlock(TrueBBI.BB);
642 if (!FT && blockAlwaysFallThrough(FalseBBI))
643 FT = getNextBlock(FalseBBI.BB);
644 if (TT != FT)
645 return false;
646 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
647 return false;
648 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
649 return false;
650
651 // FIXME: Allow true block to have an early exit?
652 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
653 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
654 return false;
655
656 // Count duplicate instructions at the beginning and end of the true and
657 // false blocks.
658 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
659 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
660 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
661 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
662 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
663 *TrueBBI.BB, *FalseBBI.BB,
664 /* SkipConditionalBranches */ true);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000665 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000666}
667
Evan Cheng4dd31a72007-06-11 22:26:22 +0000668/// ScanInstructions - Scan all the instructions in the block to determine if
669/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000670/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000671/// instruction which can clobber a predicate (e.g. condition code register).
672/// If so, the block is not predicable unless it's the last instruction.
673void IfConverter::ScanInstructions(BBInfo &BBI) {
674 if (BBI.IsDone)
675 return;
676
Evan Chengc5adcca2012-06-08 21:53:50 +0000677 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000678 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000679 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000680 BBI.BrCond.clear();
681 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000682 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000683 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000684
685 if (BBI.BrCond.size()) {
686 // No false branch. This BB must end with a conditional branch and a
687 // fallthrough.
688 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000689 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000690 if (!BBI.FalseBB) {
691 // Malformed bcc? True and false blocks are the same?
692 BBI.IsUnpredicable = true;
693 return;
694 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000695 }
696
697 // Then scan all the instructions.
698 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000699 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000700 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000701 BBI.ClobbersPred = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000702 for (auto &MI : *BBI.BB) {
703 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000704 continue;
705
Justin Lebar7dba2e02016-04-15 01:38:41 +0000706 // It's unsafe to duplicate convergent instructions in this context, so set
707 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
708 // following CFG, which is subject to our "simple" transformation.
709 //
710 // BB0 // if (c1) goto BB1; else goto BB2;
711 // / \
712 // BB1 |
713 // | BB2 // if (c2) goto TBB; else goto FBB;
714 // | / |
715 // | / |
716 // TBB |
717 // | |
718 // | FBB
719 // |
720 // exit
721 //
722 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
723 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
724 // TBB contains a convergent instruction. This is safe iff doing so does
725 // not add a control-flow dependency to the convergent instruction -- i.e.,
726 // it's safe iff the set of control flows that leads us to the convergent
727 // instruction does not get smaller after the transformation.
728 //
729 // Originally we executed TBB if c1 || c2. After the transformation, there
730 // are two copies of TBB's instructions. We get to the first if c1, and we
731 // get to the second if !c1 && c2.
732 //
733 // There are clearly fewer ways to satisfy the condition "c1" than
734 // "c1 || c2". Since we've shrunk the set of control flows which lead to
735 // our convergent instruction, the transformation is unsafe.
736 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000737 BBI.CannotBeCopied = true;
738
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000739 bool isPredicated = TII->isPredicated(MI);
740 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000741
Joey Goulya5153cb2013-09-09 14:21:49 +0000742 // A conditional branch is not predicable, but it may be eliminated.
743 if (isCondBr)
744 continue;
745
746 if (!isPredicated) {
747 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000748 unsigned ExtraPredCost = TII->getPredicationCost(MI);
749 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000750 if (NumCycles > 1)
751 BBI.ExtraCost += NumCycles-1;
752 BBI.ExtraCost2 += ExtraPredCost;
753 } else if (!AlreadyPredicated) {
754 // FIXME: This instruction is already predicated before the
755 // if-conversion pass. It's probably something like a conditional move.
756 // Mark this block unpredicable for now.
757 BBI.IsUnpredicable = true;
758 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000759 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000760
761 if (BBI.ClobbersPred && !isPredicated) {
762 // Predicate modification instruction should end the block (except for
763 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000764 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000765 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000766 BBI.IsUnpredicable = true;
767 return;
768 }
769
Evan Chengfbc73092007-07-10 17:50:43 +0000770 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
771 // still potentially predicable.
772 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000773 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000774 BBI.ClobbersPred = true;
775
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000776 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000777 BBI.IsUnpredicable = true;
778 return;
779 }
780 }
781}
782
783/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
784/// predicated by the specified predicate.
785bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000786 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000787 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000788 // If the block is dead or unpredicable, then it cannot be predicated.
789 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000790 return false;
791
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000792 // If it is already predicated but we couldn't analyze its terminator, the
793 // latter might fallthrough, but we can't determine where to.
794 // Conservatively avoid if-converting again.
795 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
796 return false;
797
Quentin Colombetbdab2272013-07-24 20:20:37 +0000798 // If it is already predicated, check if the new predicate subsumes
799 // its predicate.
800 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000801 return false;
802
803 if (BBI.BrCond.size()) {
804 if (!isTriangle)
805 return false;
806
Bob Wilson2371f4f2009-05-13 23:25:24 +0000807 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000808 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
809 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000810 if (RevBranch) {
811 if (TII->ReverseBranchCondition(Cond))
812 return false;
813 }
814 if (TII->ReverseBranchCondition(RevPred) ||
815 !TII->SubsumesPredicate(Cond, RevPred))
816 return false;
817 }
818
819 return true;
820}
821
Evan Cheng7783f822007-06-08 09:36:04 +0000822/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000823/// the specified block. Record its successors and whether it looks like an
824/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000825void IfConverter::AnalyzeBlock(
826 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000827 struct BBState {
828 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
829 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000830
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000831 /// This flag is true if MBB's successors have been analyzed.
832 bool SuccsAnalyzed;
833 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000834
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000835 // Push MBB to the stack.
836 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000837
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000838 while (!BBStack.empty()) {
839 BBState &State = BBStack.back();
840 MachineBasicBlock *BB = State.MBB;
841 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000842
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000843 if (!State.SuccsAnalyzed) {
844 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
845 BBStack.pop_back();
846 continue;
847 }
Evan Cheng9030b982007-06-06 10:16:17 +0000848
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000849 BBI.BB = BB;
850 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000851
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000852 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000853
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000854 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
855 // not considered for ifcvt anymore.
856 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
857 BBI.IsBeingAnalyzed = false;
858 BBI.IsAnalyzed = true;
859 BBStack.pop_back();
860 continue;
861 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000862
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000863 // Do not ifcvt if either path is a back edge to the entry block.
864 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
865 BBI.IsBeingAnalyzed = false;
866 BBI.IsAnalyzed = true;
867 BBStack.pop_back();
868 continue;
869 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000870
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000871 // Do not ifcvt if true and false fallthrough blocks are the same.
872 if (!BBI.FalseBB) {
873 BBI.IsBeingAnalyzed = false;
874 BBI.IsAnalyzed = true;
875 BBStack.pop_back();
876 continue;
877 }
Evan Cheng7783f822007-06-08 09:36:04 +0000878
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000879 // Push the False and True blocks to the stack.
880 State.SuccsAnalyzed = true;
881 BBStack.push_back(BBI.FalseBB);
882 BBStack.push_back(BBI.TrueBB);
883 continue;
884 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000885
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000886 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
887 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000888
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000889 if (TrueBBI.IsDone && FalseBBI.IsDone) {
890 BBI.IsBeingAnalyzed = false;
891 BBI.IsAnalyzed = true;
892 BBStack.pop_back();
893 continue;
894 }
895
896 SmallVector<MachineOperand, 4>
897 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
898 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
899
900 unsigned Dups = 0;
901 unsigned Dups2 = 0;
902 bool TNeedSub = !TrueBBI.Predicate.empty();
903 bool FNeedSub = !FalseBBI.Predicate.empty();
904 bool Enqueued = false;
905
906 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
907
908 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
909 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
910 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
911 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000912 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000913 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000914 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
915 FeasibilityAnalysis(FalseBBI, RevCond)) {
916 // Diamond:
917 // EBB
918 // / \_
919 // | |
920 // TBB FBB
921 // \ /
922 // TailBB
923 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000924 Tokens.push_back(llvm::make_unique<IfcvtToken>(
925 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000926 Enqueued = true;
927 }
928
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000929 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
930 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
931 TrueBBI.ExtraCost2, Prediction) &&
932 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
933 // Triangle:
934 // EBB
935 // | \_
936 // | |
937 // | TBB
938 // | /
939 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000940 Tokens.push_back(
941 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000942 Enqueued = true;
943 }
944
945 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
946 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
947 TrueBBI.ExtraCost2, Prediction) &&
948 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000949 Tokens.push_back(
950 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000951 Enqueued = true;
952 }
953
954 if (ValidSimple(TrueBBI, Dups, Prediction) &&
955 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
956 TrueBBI.ExtraCost2, Prediction) &&
957 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
958 // Simple (split, no rejoin):
959 // EBB
960 // | \_
961 // | |
962 // | TBB---> exit
963 // |
964 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000965 Tokens.push_back(
966 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000967 Enqueued = true;
968 }
969
970 if (CanRevCond) {
971 // Try the other path...
972 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
973 Prediction.getCompl()) &&
974 MeetIfcvtSizeLimit(*FalseBBI.BB,
975 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
976 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
977 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000978 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
979 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000980 Enqueued = true;
981 }
982
983 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
984 Prediction.getCompl()) &&
985 MeetIfcvtSizeLimit(*FalseBBI.BB,
986 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000987 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000988 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000989 Tokens.push_back(
990 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000991 Enqueued = true;
992 }
993
994 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
995 MeetIfcvtSizeLimit(*FalseBBI.BB,
996 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
997 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
998 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000999 Tokens.push_back(
1000 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001001 Enqueued = true;
1002 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001003 }
1004
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001005 BBI.IsEnqueued = Enqueued;
1006 BBI.IsBeingAnalyzed = false;
1007 BBI.IsAnalyzed = true;
1008 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001009 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001010}
1011
Evan Cheng905a8f42007-05-30 19:49:19 +00001012/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +00001013/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001014void IfConverter::AnalyzeBlocks(
1015 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001016 for (auto &BB : MF)
1017 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001018
Evan Cheng20e05992007-06-01 00:12:12 +00001019 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001020 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001021}
1022
Evan Cheng288f1542007-06-08 22:01:07 +00001023/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
1024/// that all the intervening blocks are empty (given BB can fall through to its
1025/// next block).
1026static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001027 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001028 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001029 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +00001030 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001031 while (I != TI) {
1032 // Check isSuccessor to avoid case where the next block is empty, but
1033 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001034 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001035 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001036 PI = I++;
1037 }
Evan Cheng312b7232007-06-04 06:47:22 +00001038 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001039}
1040
Evan Cheng51eb2c32007-06-18 08:37:25 +00001041/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
1042/// to determine if it can be if-converted. If predecessor is already enqueued,
1043/// dequeue it!
1044void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001045 for (const auto &Predecessor : BB->predecessors()) {
1046 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +00001047 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001048 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001049 PBBI.IsAnalyzed = false;
1050 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001051 }
1052}
1053
Evan Chengc2237ce2007-05-29 22:31:16 +00001054/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
1055///
1056static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
1057 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001058 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001059 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +00001060 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001061}
1062
Evan Cheng288f1542007-06-08 22:01:07 +00001063/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1064/// successors.
1065void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001066 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001067 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001068 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001069 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001070}
1071
Matthias Braund616ccc2013-10-11 19:04:37 +00001072/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Peter Collingbourneaf567592016-06-24 18:57:29 +00001073/// values defined in MI which are not live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001074static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001075 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001076 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001077
Pete Cooper7605e372015-05-05 20:14:22 +00001078 // Now add the implicit uses for each of the clobbered values.
1079 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001080 // FIXME: Const cast here is nasty, but better than making StepForward
1081 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001082 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1083 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001084 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001085 if (Op.isRegMask()) {
1086 // First handle regmasks. They clobber any entries in the mask which
1087 // means that we need a def for those registers.
Peter Collingbourneaf567592016-06-24 18:57:29 +00001088 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001089
1090 // We also need to add an implicit def of this register for the later
1091 // use to read from.
1092 // For the register allocator to have allocated a register clobbered
1093 // by the call which is used later, it must be the case that
1094 // the call doesn't return.
1095 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1096 continue;
1097 }
1098 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001099 if (Op.isDead()) {
1100 // If we found a dead def, but it needs to be live, then remove the dead
1101 // flag.
1102 if (Redefs.contains(Op.getReg()))
1103 Op.setIsDead(false);
1104 }
Peter Collingbourneaf567592016-06-24 18:57:29 +00001105 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001106 }
1107}
1108
1109/**
1110 * Remove kill flags from operands with a registers in the @p DontKill set.
1111 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001112static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001113 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001114 if (!O->isReg() || !O->isKill())
1115 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001116 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001117 O->setIsKill(false);
1118 }
1119}
1120
1121/**
1122 * Walks a range of machine instructions and removes kill flags for registers
1123 * in the @p DontKill set.
1124 */
1125static void RemoveKills(MachineBasicBlock::iterator I,
1126 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001127 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001128 const MCRegisterInfo &MCRI) {
1129 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001130 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001131}
1132
Evan Cheng312b7232007-06-04 06:47:22 +00001133/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001134///
Evan Cheng3a51c852007-06-16 09:34:52 +00001135bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001136 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1137 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1138 BBInfo *CvtBBI = &TrueBBI;
1139 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001140
Owen Anderson4f6bf042008-08-14 22:49:33 +00001141 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001142 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001143 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001144
Evan Cheng51eb2c32007-06-18 08:37:25 +00001145 if (CvtBBI->IsDone ||
1146 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001147 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001148 BBI.IsAnalyzed = false;
1149 CvtBBI->IsAnalyzed = false;
1150 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001151 }
Evan Chengd0e66912007-05-23 07:23:16 +00001152
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001153 if (CvtBBI->BB->hasAddressTaken())
1154 // Conservatively abort if-conversion if BB's address is taken.
1155 return false;
1156
Evan Cheng3a51c852007-06-16 09:34:52 +00001157 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001158 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001159 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001160
Bob Wilson45814342010-06-19 05:33:57 +00001161 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001162 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001163 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001164 Redefs.addLiveIns(*CvtBBI->BB);
1165 Redefs.addLiveIns(*NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001166
1167 // Compute a set of registers which must not be killed by instructions in
1168 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001169 DontKill.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001170 DontKill.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001171
Evan Cheng92fb5452007-06-15 07:36:12 +00001172 if (CvtBBI->BB->pred_size() > 1) {
1173 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001174 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001175 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001176 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001177
1178 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1179 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001180 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001181 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001182 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001183 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001184
Evan Cheng92fb5452007-06-15 07:36:12 +00001185 // Merge converted block into entry block.
1186 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1187 MergeBlocks(BBI, *CvtBBI);
1188 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001189
Evan Chenge4ec9182007-06-06 02:08:52 +00001190 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001191 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001192 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001193 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001194 // Now ifcvt'd block will look like this:
1195 // BB:
1196 // ...
1197 // t, f = cmp
1198 // if t op
1199 // b BBf
1200 //
1201 // We cannot further ifcvt this block because the unconditional branch
1202 // will have to be predicated on the new condition, that will not be
1203 // available if cmp executes.
1204 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001205 }
Evan Chenge26c0912007-05-21 22:22:58 +00001206
Evan Cheng288f1542007-06-08 22:01:07 +00001207 RemoveExtraEdges(BBI);
1208
Evan Chengd0e66912007-05-23 07:23:16 +00001209 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001210 if (!IterIfcvt)
1211 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001212 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001213 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001214
1215 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001216 return true;
1217}
1218
Evan Chengaf716102007-05-16 21:54:37 +00001219/// IfConvertTriangle - If convert a triangle sub-CFG.
1220///
Evan Cheng3a51c852007-06-16 09:34:52 +00001221bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001222 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001223 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1224 BBInfo *CvtBBI = &TrueBBI;
1225 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001226 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001227
Owen Anderson4f6bf042008-08-14 22:49:33 +00001228 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001229 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001230 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001231
Evan Cheng51eb2c32007-06-18 08:37:25 +00001232 if (CvtBBI->IsDone ||
1233 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001234 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001235 BBI.IsAnalyzed = false;
1236 CvtBBI->IsAnalyzed = false;
1237 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001238 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001239
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001240 if (CvtBBI->BB->hasAddressTaken())
1241 // Conservatively abort if-conversion if BB's address is taken.
1242 return false;
1243
Evan Cheng3a51c852007-06-16 09:34:52 +00001244 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001245 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001246 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001247
Evan Cheng3a51c852007-06-16 09:34:52 +00001248 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001249 if (ReverseBranchCondition(*CvtBBI)) {
1250 // BB has been changed, modify its predecessors (except for this
1251 // one) so they don't get ifcvt'ed based on bad intel.
1252 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1253 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1254 MachineBasicBlock *PBB = *PI;
1255 if (PBB == BBI.BB)
1256 continue;
1257 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1258 if (PBBI.IsEnqueued) {
1259 PBBI.IsAnalyzed = false;
1260 PBBI.IsEnqueued = false;
1261 }
Evan Chengadd97762007-06-14 23:34:09 +00001262 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001263 }
1264 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001265
Bob Wilson45814342010-06-19 05:33:57 +00001266 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001267 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001268 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001269 Redefs.addLiveIns(*CvtBBI->BB);
1270 Redefs.addLiveIns(*NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001271
Andrew Trick276dd452013-10-14 20:45:17 +00001272 DontKill.clear();
1273
Craig Topperc0196b12014-04-14 00:51:57 +00001274 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001275 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001276
Manman Renb6819182014-01-29 23:18:47 +00001277 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001278 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1279 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1280 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1281 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1282 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001283 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001284
Bob Wilson1e5da552010-06-29 00:55:23 +00001285 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001286 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001287 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001288 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001289 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001290
1291 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1292 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001293 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001294 } else {
1295 // Predicate the 'true' block after removing its branch.
1296 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001297 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001298
Evan Cheng0598b2d2007-06-18 22:44:57 +00001299 // Now merge the entry of the triangle with the true block.
1300 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001301 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001302 }
1303
Evan Cheng312b7232007-06-04 06:47:22 +00001304 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001305 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001306 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1307 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001308 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001309 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001310
Cong Houd97c1002015-12-01 05:29:22 +00001311 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1312 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1313 // Prob(BBI.BB, NextBBI->BB) +
1314 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1315 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1316 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1317 auto NewTrueBB = getNextBlock(BBI.BB);
1318 auto NewNext = BBNext + BBCvt * CvtNext;
1319 auto NewTrueBBIter =
1320 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001321 if (NewTrueBBIter != BBI.BB->succ_end())
1322 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001323
1324 auto NewFalse = BBCvt * CvtFalse;
1325 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1326 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001327 }
Evan Cheng7783f822007-06-08 09:36:04 +00001328
1329 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001330 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001331 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001332 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001333 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001334 if (!isFallThrough) {
1335 // Only merge them if the true block does not fallthrough to the false
1336 // block. By not merging them, we make it possible to iteratively
1337 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001338 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001339 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1340 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001341 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001342 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001343 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001344 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1345 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001346 }
Evan Cheng7783f822007-06-08 09:36:04 +00001347 // Mixed predicated and unpredicated code. This cannot be iteratively
1348 // predicated.
1349 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001350 }
Evan Chenge26c0912007-05-21 22:22:58 +00001351
Evan Cheng288f1542007-06-08 22:01:07 +00001352 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001353
Evan Chengd0e66912007-05-23 07:23:16 +00001354 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001355 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001356 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001357 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001358 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001359 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001360 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001361
1362 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001363 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001364}
1365
Evan Chengaf716102007-05-16 21:54:37 +00001366/// IfConvertDiamond - If convert a diamond sub-CFG.
1367///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001368bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1369 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001370 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001371 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001372 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001373 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001374 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001375 if (blockAlwaysFallThrough(TrueBBI))
1376 TailBB = FalseBBI.TrueBB;
1377 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001378 }
Evan Chenge26c0912007-05-21 22:22:58 +00001379
Evan Cheng51eb2c32007-06-18 08:37:25 +00001380 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1381 TrueBBI.BB->pred_size() > 1 ||
1382 FalseBBI.BB->pred_size() > 1) {
1383 // Something has changed. It's no longer safe to predicate these blocks.
1384 BBI.IsAnalyzed = false;
1385 TrueBBI.IsAnalyzed = false;
1386 FalseBBI.IsAnalyzed = false;
1387 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001388 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001389
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001390 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1391 // Conservatively abort if-conversion if either BB has its address taken.
1392 return false;
1393
Bob Wilson1e5da552010-06-29 00:55:23 +00001394 // Put the predicated instructions from the 'true' block before the
1395 // instructions from the 'false' block, unless the true block would clobber
1396 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001397 BBInfo *BBI1 = &TrueBBI;
1398 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001399 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001400 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001401 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001402 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1403 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001404
Evan Cheng3a51c852007-06-16 09:34:52 +00001405 // Figure out the more profitable ordering.
1406 bool DoSwap = false;
1407 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1408 DoSwap = true;
1409 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001410 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001411 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001412 }
1413 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001414 std::swap(BBI1, BBI2);
1415 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001416 }
Evan Cheng79484222007-06-05 23:46:14 +00001417
Evan Cheng51eb2c32007-06-18 08:37:25 +00001418 // Remove the conditional branch from entry to the blocks.
1419 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1420
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001421 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001422 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001423 Redefs.init(TRI);
Matthias Braund1aabb22016-05-03 00:24:32 +00001424 Redefs.addLiveIns(*BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001425
Evan Cheng51eb2c32007-06-18 08:37:25 +00001426 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001427 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001428 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1429 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001430 BBI1->NonPredSize -= NumDups1;
1431 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001432
1433 // Skip past the dups on each side separately since there may be
1434 // differing dbg_value entries.
1435 for (unsigned i = 0; i < NumDups1; ++DI1) {
1436 if (!DI1->isDebugValue())
1437 ++i;
1438 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001439 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001440 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001441 if (!DI2->isDebugValue())
1442 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001443 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001444
Matthias Braund616ccc2013-10-11 19:04:37 +00001445 // Compute a set of registers which must not be killed by instructions in BB1:
1446 // This is everything used+live in BB2 after the duplicated instructions. We
1447 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001448 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001449 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1450 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001451 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001452 }
1453
1454 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1455 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001456 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1457 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001458 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001459 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1460 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1461
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001462 // Remove branch from the 'true' block, unless it was not analyzable.
1463 // Non-analyzable branches need to be preserved, since in such cases,
1464 // the CFG structure is not an actual diamond (the join block may not
1465 // be present).
1466 if (BBI1->IsBrAnalyzable)
1467 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1468 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001469 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001470 for (unsigned i = 0; i != NumDups2; ) {
1471 // NumDups2 only counted non-dbg_value instructions, so this won't
1472 // run off the head of the list.
1473 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001474 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001475 // skip dbg_value instructions
1476 if (!DI1->isDebugValue())
1477 ++i;
1478 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001479 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001480
Matthias Braund616ccc2013-10-11 19:04:37 +00001481 // Kill flags in the true block for registers living into the false block
1482 // must be removed.
1483 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1484
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001485 // Remove 'false' block branch (unless it was not analyzable), and find
1486 // the last instruction to predicate.
1487 if (BBI2->IsBrAnalyzable)
1488 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001489 DI2 = BBI2->BB->end();
1490 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001491 // NumDups2 only counted non-dbg_value instructions, so this won't
1492 // run off the head of the list.
1493 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001494 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001495 // skip dbg_value instructions
1496 if (!DI2->isDebugValue())
1497 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001498 }
Evan Cheng4266a792011-12-19 22:01:30 +00001499
1500 // Remember which registers would later be defined by the false block.
1501 // This allows us not to predicate instructions in the true block that would
1502 // later be re-defined. That is, rather than
1503 // subeq r0, r1, #1
1504 // addne r0, r1, #1
1505 // generate:
1506 // sub r0, r1, #1
1507 // addne r0, r1, #1
1508 SmallSet<unsigned, 4> RedefsByFalse;
1509 SmallSet<unsigned, 4> ExtUses;
1510 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1511 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1512 if (FI->isDebugValue())
1513 continue;
1514 SmallVector<unsigned, 4> Defs;
1515 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1516 const MachineOperand &MO = FI->getOperand(i);
1517 if (!MO.isReg())
1518 continue;
1519 unsigned Reg = MO.getReg();
1520 if (!Reg)
1521 continue;
1522 if (MO.isDef()) {
1523 Defs.push_back(Reg);
1524 } else if (!RedefsByFalse.count(Reg)) {
1525 // These are defined before ctrl flow reach the 'false' instructions.
1526 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001527 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1528 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001529 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001530 }
1531 }
1532
1533 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1534 unsigned Reg = Defs[i];
1535 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001536 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1537 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001538 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001539 }
1540 }
1541 }
1542 }
1543
1544 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001545 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001546
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001547 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1548 // a non-predicated in BBI2, then we don't want to predicate the one from
1549 // BBI2. The reason is that if we merged these blocks, we would end up with
1550 // two predicated terminators in the same block.
1551 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1552 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1553 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001554 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1555 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001556 --DI2;
1557 }
1558
Evan Cheng4266a792011-12-19 22:01:30 +00001559 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001560 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001561
Evan Cheng0598b2d2007-06-18 22:44:57 +00001562 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001563 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1564 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001565
Bob Wilson2371f4f2009-05-13 23:25:24 +00001566 // If the if-converted block falls through or unconditionally branches into
1567 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001568 // fold the tail block in as well. Otherwise, unless it falls through to the
1569 // tail, add a unconditional branch to it.
1570 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001571 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001572 bool CanMergeTail = !TailBBI.HasFallThrough &&
1573 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001574 // The if-converted block can still have a predicated terminator
1575 // (e.g. a predicated return). If that is the case, we cannot merge
1576 // it with the tail block.
1577 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001578 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001579 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001580 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1581 // check if there are any other predecessors besides those.
1582 unsigned NumPreds = TailBB->pred_size();
1583 if (NumPreds > 1)
1584 CanMergeTail = false;
1585 else if (NumPreds == 1 && CanMergeTail) {
1586 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1587 if (*PI != BBI1->BB && *PI != BBI2->BB)
1588 CanMergeTail = false;
1589 }
1590 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001591 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001592 TailBBI.IsDone = true;
1593 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001594 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001595 InsertUncondBranch(BBI.BB, TailBB, TII);
1596 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001597 }
Evan Chenge26c0912007-05-21 22:22:58 +00001598 }
1599
Bob Wilson1e5da552010-06-29 00:55:23 +00001600 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1601 // which can happen here if TailBB is unanalyzable and is merged, so
1602 // explicitly remove BBI1 and BBI2 as successors.
1603 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001604 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001605 RemoveExtraEdges(BBI);
1606
Evan Cheng79484222007-06-05 23:46:14 +00001607 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001608 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001609 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001610
1611 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001612 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001613}
1614
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001615static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001616 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001617 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001618 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001619 return false;
1620
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001621 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1622 const MachineOperand &MO = MI.getOperand(i);
Evan Cheng4266a792011-12-19 22:01:30 +00001623 if (!MO.isReg())
1624 continue;
1625 unsigned Reg = MO.getReg();
1626 if (!Reg)
1627 continue;
1628 if (MO.isDef() && !LaterRedefs.count(Reg))
1629 return false;
1630 }
1631
1632 return true;
1633}
1634
Evan Cheng51eb2c32007-06-18 08:37:25 +00001635/// PredicateBlock - Predicate instructions from the start of the block to the
1636/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001637void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001638 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001639 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001640 SmallSet<unsigned, 4> *LaterRedefs) {
1641 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001642 bool MaySpec = LaterRedefs != nullptr;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001643 for (MachineInstr &I : llvm::make_range(BBI.BB->begin(), E)) {
1644 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001645 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001646 // It may be possible not to predicate an instruction if it's the 'true'
1647 // side of a diamond and the 'false' side may re-define the instruction's
1648 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001649 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001650 AnyUnpred = true;
1651 continue;
1652 }
1653 // If any instruction is predicated, then every instruction after it must
1654 // be predicated.
1655 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001656 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001657#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001658 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001659#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001660 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001661 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001662
Bob Wilson45814342010-06-19 05:33:57 +00001663 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001664 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001665 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001666 }
Evan Chengd0e66912007-05-23 07:23:16 +00001667
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001668 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001669
Evan Cheng92fb5452007-06-15 07:36:12 +00001670 BBI.IsAnalyzed = false;
1671 BBI.NonPredSize = 0;
1672
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001673 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001674 if (AnyUnpred)
1675 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001676}
1677
Evan Cheng92fb5452007-06-15 07:36:12 +00001678/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1679/// the destination block. Skip end of block branches if IgnoreBr is true.
1680void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001681 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001682 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001683 MachineFunction &MF = *ToBBI.BB->getParent();
1684
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001685 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001686 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001687 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001688 break;
1689
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001690 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001691 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001692 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001693 unsigned ExtraPredCost = TII->getPredicationCost(I);
1694 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001695 if (NumCycles > 1)
1696 ToBBI.ExtraCost += NumCycles-1;
1697 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001698
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001699 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001700 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001701#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001702 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001703#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001704 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001705 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001706 }
1707
Bob Wilson45814342010-06-19 05:33:57 +00001708 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001709 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001710 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001711
1712 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001713 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001714 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001715 }
1716
Bob Wilson1e5da552010-06-29 00:55:23 +00001717 if (!IgnoreBr) {
1718 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1719 FromBBI.BB->succ_end());
1720 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001721 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001722
Bob Wilson1e5da552010-06-29 00:55:23 +00001723 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1724 MachineBasicBlock *Succ = Succs[i];
1725 // Fallthrough edge can't be transferred.
1726 if (Succ == FallThrough)
1727 continue;
1728 ToBBI.BB->addSuccessor(Succ);
1729 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001730 }
1731
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001732 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1733 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001734
1735 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1736 ToBBI.IsAnalyzed = false;
1737
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001738 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001739}
1740
Evan Cheng0f745da2007-05-18 00:20:58 +00001741/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001742/// This will leave FromBB as an empty block, so remove all of its
1743/// successor edges except for the fall-through edge. If AddEdges is true,
1744/// i.e., when FromBBI's branch is being moved, add those successor edges to
1745/// ToBBI.
1746void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001747 assert(!FromBBI.BB->hasAddressTaken() &&
1748 "Removing a BB whose address is taken!");
1749
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001750 // In case FromBBI.BB contains terminators (e.g. return instruction),
1751 // first move the non-terminator instructions, then the terminators.
1752 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1753 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1754 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1755
1756 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001757 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001758 ToTI = ToBBI.BB->end();
1759 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001760
Cong Houb9e8d482015-12-17 01:29:08 +00001761 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1762 // unknown probabilities into known ones.
1763 // FIXME: This usage is too tricky and in the future we would like to
1764 // eliminate all unknown probabilities in MBB.
1765 ToBBI.BB->normalizeSuccProbs();
1766
Cong Houd40105d2015-09-18 20:22:41 +00001767 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1768 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001769 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001770 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001771 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001772 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001773 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001774 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001775 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1776 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1777 // edge probability being merged to other edges when this edge is removed
1778 // later.
1779 ToBBI.BB->setSuccProbability(
1780 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1781 BranchProbability::getZero());
1782 }
1783
Cong Houd40105d2015-09-18 20:22:41 +00001784 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1785 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001786 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001787 if (Succ == FallThrough)
1788 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001789
Cong Houd97c1002015-12-01 05:29:22 +00001790 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001791 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001792 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1793 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1794 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1795 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1796 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001797
Cong Houd97c1002015-12-01 05:29:22 +00001798 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001799 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1800 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001801 // could just use the probabilities on FromBBI.BB's out-edges when adding
1802 // new successors.
1803 if (!To2FromProb.isZero())
1804 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001805 }
1806
Evan Chengbe9859e2007-06-07 02:12:15 +00001807 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001808
1809 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001810 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001811 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001812 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1813 // don't have to set C as A's successor as it already is. We only need to
1814 // update the edge probability on A->C. Note that B will not be
1815 // immediately removed from A's successors. It is possible that B->D is
1816 // not removed either if D is a fallthrough of B. Later the edge A->D
1817 // (generated here) and B->D will be combined into one edge. To maintain
1818 // correct edge probability of this combined edge, we need to set the edge
1819 // probability of A->B to zero, which is already done above. The edge
1820 // probability on A->D is calculated by scaling the original probability
1821 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001822 //
1823 // Before ifcvt: After ifcvt (assume B->D is kept):
1824 //
1825 // A A
1826 // /| /|\
1827 // / B / B|
1828 // | /| | ||
1829 // |/ | | |/
1830 // C D C D
1831 //
1832 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001833 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001834 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001835 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001836 else
Cong Houd97c1002015-12-01 05:29:22 +00001837 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001838 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001839 }
1840
Bob Wilson2371f4f2009-05-13 23:25:24 +00001841 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001842 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001843 FromBBI.BB->addSuccessor(NBB);
1844
Cong Houc1069892015-12-13 09:26:17 +00001845 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1846 // we've done above.
1847 ToBBI.BB->normalizeSuccProbs();
1848
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001849 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001850 FromBBI.Predicate.clear();
1851
Evan Chengd0e66912007-05-23 07:23:16 +00001852 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001853 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001854 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001855 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001856 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001857 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001858
Evan Cheng4dd31a72007-06-11 22:26:22 +00001859 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001860 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001861 ToBBI.IsAnalyzed = false;
1862 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001863}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001864
1865FunctionPass *
1866llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00001867 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00001868}