blob: b8799a563fcb4a1fda98249b9c26b3a94a3ec7bf [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//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Chengf5e53a52007-05-16 02:00:57 +000014#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000020#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000021#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000026#include "llvm/CodeGen/TargetSchedule.h"
Evan Cheng8264e272011-06-29 01:14:12 +000027#include "llvm/MC/MCInstrItineraries.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"
36
Evan Chengf5e53a52007-05-16 02:00:57 +000037using namespace llvm;
38
Chandler Carruth1b9dde02014-04-22 02:02:50 +000039#define DEBUG_TYPE "ifcvt"
40
Chris Lattner769c86b2008-01-07 05:40:58 +000041// Hidden options for help debugging.
42static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
43static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
44static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000045static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000047static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000051static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000053static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000054 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000055static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000056 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000057static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000058 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000059static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
60 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000061
Evan Cheng2117d1f2007-06-09 01:03:43 +000062STATISTIC(NumSimple, "Number of simple if-conversions performed");
63STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
64STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000065STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000066STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
67STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
68STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
69STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000070STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000071STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000072
73namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000074 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000075 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000076 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000077 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000078 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
79 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000080 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000081 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000082 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000083 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000084 };
85
86 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
87 /// if-conversion feasibility analysis. This includes results from
88 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000089 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000090 /// diamond shape), its size, whether it's predicable, and whether any
91 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000092 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000093 /// IsDone - True if BB is not to be considered for ifcvt.
94 /// IsBeingAnalyzed - True if BB is currently being analyzed.
95 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
96 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
97 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
98 /// HasFallThrough - True if BB may fallthrough to the following BB.
99 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000100 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000101 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000102 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000103 /// ExtraCost - Extra cost for multi-cycle instructions.
104 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000105 /// BB - Corresponding MachineBasicBlock.
106 /// TrueBB / FalseBB- See AnalyzeBranch().
107 /// BrCond - Conditions for end of block conditional branches.
108 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000109 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000110 bool IsDone : 1;
111 bool IsBeingAnalyzed : 1;
112 bool IsAnalyzed : 1;
113 bool IsEnqueued : 1;
114 bool IsBrAnalyzable : 1;
115 bool HasFallThrough : 1;
116 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000117 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000118 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000119 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000120 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000121 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000122 MachineBasicBlock *BB;
123 MachineBasicBlock *TrueBB;
124 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000125 SmallVector<MachineOperand, 4> BrCond;
126 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000127 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000128 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
129 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000130 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000131 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
132 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000133 };
134
Bob Wilson59475732010-06-15 18:19:27 +0000135 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 /// BBI - Corresponding BBInfo.
137 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000138 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000139 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000140 /// NumDups - Number of instructions that would be duplicated due
141 /// to this if-conversion. (For diamonds, the number of
142 /// identical instructions at the beginnings of both
143 /// paths).
144 /// NumDups2 - For diamonds, the number of identical instructions
145 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000146 struct IfcvtToken {
147 BBInfo &BBI;
148 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000149 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000150 unsigned NumDups;
151 unsigned NumDups2;
152 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000153 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000154 };
155
156 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
157 /// basic block number.
158 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000159 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000160
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000161 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000162 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000163 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000164 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000165 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000166 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000167
Juergen Ributzka310034e2013-12-14 06:52:56 +0000168 LivePhysRegs Redefs;
169 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000170
Evan Chengc5adcca2012-06-08 21:53:50 +0000171 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000172 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000173 int FnNum;
Evan Chengf5e53a52007-05-16 02:00:57 +0000174 public:
175 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000176 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
177 initializeIfConverterPass(*PassRegistry::getPassRegistry());
178 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000179
Craig Topper4584cd52014-03-07 09:26:03 +0000180 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000181 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000182 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000183 MachineFunctionPass::getAnalysisUsage(AU);
184 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000185
Craig Topper4584cd52014-03-07 09:26:03 +0000186 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000187
188 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000189 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000190 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000191 const BranchProbability &Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000192 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000193 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000194 const BranchProbability &Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000195 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
196 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000197 void ScanInstructions(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000198 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
199 std::vector<IfcvtToken*> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000200 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000201 bool isTriangle = false, bool RevBranch = false);
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000202 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000203 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000204 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000205 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
206 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000207 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
208 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000209 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000210 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000211 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000212 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000213 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000214 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000215 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000216 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000217
Evan Chengdebf9c52010-11-03 00:45:17 +0000218 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
219 unsigned Cycle, unsigned Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000220 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000221 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000222 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000223 }
224
Evan Chengdebf9c52010-11-03 00:45:17 +0000225 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
226 unsigned TCycle, unsigned TExtra,
227 MachineBasicBlock &FBB,
228 unsigned FCycle, unsigned FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000229 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000230 return TCycle > 0 && FCycle > 0 &&
231 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000232 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000233 }
234
Evan Chengbe9859e2007-06-07 02:12:15 +0000235 // blockAlwaysFallThrough - Block ends without a terminator.
236 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000237 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000238 }
239
Evan Cheng3a51c852007-06-16 09:34:52 +0000240 // IfcvtTokenCmp - Used to sort if-conversion candidates.
241 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000242 int Incr1 = (C1->Kind == ICDiamond)
243 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
244 int Incr2 = (C2->Kind == ICDiamond)
245 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
246 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000247 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000248 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000249 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000250 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000251 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000252 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000253 // Favors diamond over triangle, etc.
254 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
255 return true;
256 else if (C1->Kind == C2->Kind)
257 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
258 }
259 }
260 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000261 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000262 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000263
Evan Chengf5e53a52007-05-16 02:00:57 +0000264 char IfConverter::ID = 0;
265}
266
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000267char &llvm::IfConverterID = IfConverter::ID;
268
Owen Anderson8ac477f2010-10-12 19:48:12 +0000269INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000270INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000271INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000272
Evan Chengf5e53a52007-05-16 02:00:57 +0000273bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher3d4276f2015-01-27 07:31:29 +0000274 const TargetSubtargetInfo &ST = MF.getSubtarget();
275 TLI = ST.getTargetLowering();
276 TII = ST.getInstrInfo();
277 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000278 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000279 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000280 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000281 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000282
Evan Chengf5e53a52007-05-16 02:00:57 +0000283 if (!TII) return false;
284
Evan Chengc5adcca2012-06-08 21:53:50 +0000285 PreRegAlloc = MRI->isSSA();
286
287 bool BFChange = false;
288 if (!PreRegAlloc) {
289 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000290 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000291 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000292 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000293 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000294
David Greene72e47cd2010-01-04 22:02:01 +0000295 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000296 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000297
298 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000299 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000300 return false;
301 }
David Greene72e47cd2010-01-04 22:02:01 +0000302 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000303
Evan Chengf5e53a52007-05-16 02:00:57 +0000304 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000305 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000306
Evan Cheng3a51c852007-06-16 09:34:52 +0000307 std::vector<IfcvtToken*> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000308 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000309 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
310 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
311 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000312 // Do an initial analysis for each basic block and find all the potential
313 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000314 bool Change = false;
315 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000316 while (!Tokens.empty()) {
317 IfcvtToken *Token = Tokens.back();
318 Tokens.pop_back();
319 BBInfo &BBI = Token->BBI;
320 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000321 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000322 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000323
324 delete Token;
Evan Cheng312b7232007-06-04 06:47:22 +0000325
Evan Cheng4dd31a72007-06-11 22:26:22 +0000326 // If the block has been evicted out of the queue or it has already been
327 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000328 if (BBI.IsDone)
329 BBI.IsEnqueued = false;
330 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000331 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000332
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000333 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000334
Evan Cheng312b7232007-06-04 06:47:22 +0000335 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000336 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000337 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000338 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000339 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000340 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000341 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000342 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
343 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000344 << "): BB#" << BBI.BB->getNumber() << " ("
345 << ((Kind == ICSimpleFalse)
346 ? BBI.FalseBB->getNumber()
347 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000348 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000349 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000350 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000351 if (isFalse) ++NumSimpleFalse;
352 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000353 }
Evan Cheng312b7232007-06-04 06:47:22 +0000354 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000355 }
Evan Chengd0e66912007-05-23 07:23:16 +0000356 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000357 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000358 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000359 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000360 bool isFalse = Kind == ICTriangleFalse;
361 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000362 if (DisableTriangle && !isFalse && !isRev) break;
363 if (DisableTriangleR && !isFalse && isRev) break;
364 if (DisableTriangleF && isFalse && !isRev) break;
365 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000366 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000367 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000368 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000369 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000370 DEBUG(dbgs() << " rev");
371 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000372 << BBI.TrueBB->getNumber() << ",F:"
373 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000374 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000375 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000376 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000377 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000378 if (isRev) ++NumTriangleFRev;
379 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000380 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000381 if (isRev) ++NumTriangleRev;
382 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000383 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000384 }
Evan Chengd0e66912007-05-23 07:23:16 +0000385 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000386 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000387 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000388 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000389 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000390 << BBI.TrueBB->getNumber() << ",F:"
391 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000392 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000393 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000394 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000395 break;
396 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000397 }
398
Evan Cheng312b7232007-06-04 06:47:22 +0000399 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000400
Evan Cheng92fb5452007-06-15 07:36:12 +0000401 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
402 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
403 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000404 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000405 }
Evan Chengd0e66912007-05-23 07:23:16 +0000406
Evan Chengd0e66912007-05-23 07:23:16 +0000407 if (!Change)
408 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000409 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000410 }
Evan Cheng478b8052007-05-18 01:55:58 +0000411
Evan Cheng3a51c852007-06-16 09:34:52 +0000412 // Delete tokens in case of early exit.
413 while (!Tokens.empty()) {
414 IfcvtToken *Token = Tokens.back();
415 Tokens.pop_back();
416 delete Token;
417 }
418
419 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000420 BBAnalysis.clear();
421
Evan Chengcf9e8a92010-06-18 22:17:13 +0000422 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000423 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000424 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000425 getAnalysisIfAvailable<MachineModuleInfo>());
426 }
427
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000428 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000429 return MadeChange;
430}
431
Evan Cheng3a51c852007-06-16 09:34:52 +0000432/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
433/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000434static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000435 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000436 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
437 E = BB->succ_end(); SI != E; ++SI) {
438 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000439 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000440 return SuccBB;
441 }
Craig Topperc0196b12014-04-14 00:51:57 +0000442 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000443}
444
Evan Cheng3a51c852007-06-16 09:34:52 +0000445/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000446/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000447bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000448 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000449 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
450 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000451 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000452 std::swap(BBI.TrueBB, BBI.FalseBB);
453 return true;
454 }
455 return false;
456}
457
Evan Cheng2117d1f2007-06-09 01:03:43 +0000458/// getNextBlock - Returns the next block in the function blocks ordering. If
459/// it is the end, returns NULL.
460static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
461 MachineFunction::iterator I = BB;
462 MachineFunction::iterator E = BB->getParent()->end();
463 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000464 return nullptr;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000465 return I;
466}
467
Evan Cheng7783f822007-06-08 09:36:04 +0000468/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000469/// predecessor) forms a valid simple shape for ifcvt. It also returns the
470/// number of instructions that the ifcvt would need to duplicate if performed
471/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000472bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000473 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000474 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000475 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000476 return false;
477
Evan Chenga955c022007-06-19 21:45:13 +0000478 if (TrueBBI.IsBrAnalyzable)
479 return false;
480
Evan Cheng23402fc2007-06-15 21:18:05 +0000481 if (TrueBBI.BB->pred_size() > 1) {
482 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000483 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000484 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000485 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000486 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000487 }
488
Evan Chenga955c022007-06-19 21:45:13 +0000489 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000490}
491
Evan Cheng7783f822007-06-08 09:36:04 +0000492/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000493/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000494/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000495/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000496/// returns the number of instructions that the ifcvt would need to duplicate
497/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000498bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000499 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000500 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000501 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000502 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000503 return false;
504
Evan Cheng23402fc2007-06-15 21:18:05 +0000505 if (TrueBBI.BB->pred_size() > 1) {
506 if (TrueBBI.CannotBeCopied)
507 return false;
508
Evan Cheng92fb5452007-06-15 07:36:12 +0000509 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000510 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000511 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000512 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000513 --Size;
514 else {
515 MachineBasicBlock *FExit = FalseBranch
516 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
517 if (FExit)
518 // Require a conditional branch
519 ++Size;
520 }
521 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000522 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000523 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000524 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000525 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000526
Evan Cheng7783f822007-06-08 09:36:04 +0000527 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
528 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengbe9859e2007-06-07 02:12:15 +0000529 MachineFunction::iterator I = TrueBBI.BB;
530 if (++I == TrueBBI.BB->getParent()->end())
531 return false;
Evan Cheng7783f822007-06-08 09:36:04 +0000532 TExit = I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000533 }
Evan Cheng7783f822007-06-08 09:36:04 +0000534 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000535}
536
Evan Cheng7783f822007-06-08 09:36:04 +0000537/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000538/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000539bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
540 unsigned &Dups1, unsigned &Dups2) const {
541 Dups1 = Dups2 = 0;
542 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
543 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000544 return false;
545
Evan Cheng2117d1f2007-06-09 01:03:43 +0000546 MachineBasicBlock *TT = TrueBBI.TrueBB;
547 MachineBasicBlock *FT = FalseBBI.TrueBB;
548
549 if (!TT && blockAlwaysFallThrough(TrueBBI))
550 TT = getNextBlock(TrueBBI.BB);
551 if (!FT && blockAlwaysFallThrough(FalseBBI))
552 FT = getNextBlock(FalseBBI.BB);
553 if (TT != FT)
554 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000555 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000556 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000557 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
558 return false;
559
560 // FIXME: Allow true block to have an early exit?
561 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
562 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000563 return false;
564
Bob Wilsone1961fe2010-10-26 00:02:24 +0000565 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000566 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
567 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000568 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
569 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
570 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000571 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000572 if (TIB->isDebugValue()) {
573 while (TIB != TIE && TIB->isDebugValue())
574 ++TIB;
575 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000576 break;
577 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000578 if (FIB->isDebugValue()) {
579 while (FIB != FIE && FIB->isDebugValue())
580 ++FIB;
581 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000582 break;
583 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000584 if (!TIB->isIdenticalTo(FIB))
585 break;
586 ++Dups1;
587 ++TIB;
588 ++FIB;
589 }
590
591 // Now, in preparation for counting duplicate instructions at the ends of the
592 // blocks, move the end iterators up past any branch instructions.
593 while (TIE != TIB) {
594 --TIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000595 if (!TIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000596 break;
597 }
598 while (FIE != FIB) {
599 --FIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000600 if (!FIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000601 break;
602 }
603
604 // If Dups1 includes all of a block, then don't count duplicate
605 // instructions at the end of the blocks.
606 if (TIB == TIE || FIB == FIE)
607 return true;
608
609 // Count duplicate instructions at the ends of the blocks.
610 while (TIE != TIB && FIE != FIB) {
611 // Skip dbg_value instructions. These do not count.
612 if (TIE->isDebugValue()) {
613 while (TIE != TIB && TIE->isDebugValue())
614 --TIE;
615 if (TIE == TIB)
616 break;
617 }
618 if (FIE->isDebugValue()) {
619 while (FIE != FIB && FIE->isDebugValue())
620 --FIE;
621 if (FIE == FIB)
622 break;
623 }
624 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000625 break;
626 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000627 --TIE;
628 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000629 }
630
631 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000632}
633
Evan Cheng4dd31a72007-06-11 22:26:22 +0000634/// ScanInstructions - Scan all the instructions in the block to determine if
635/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000636/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000637/// instruction which can clobber a predicate (e.g. condition code register).
638/// If so, the block is not predicable unless it's the last instruction.
639void IfConverter::ScanInstructions(BBInfo &BBI) {
640 if (BBI.IsDone)
641 return;
642
Evan Chengc5adcca2012-06-08 21:53:50 +0000643 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000644 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000645 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000646 BBI.BrCond.clear();
647 BBI.IsBrAnalyzable =
648 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000649 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000650
651 if (BBI.BrCond.size()) {
652 // No false branch. This BB must end with a conditional branch and a
653 // fallthrough.
654 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000655 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000656 if (!BBI.FalseBB) {
657 // Malformed bcc? True and false blocks are the same?
658 BBI.IsUnpredicable = true;
659 return;
660 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000661 }
662
663 // Then scan all the instructions.
664 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000665 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000666 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000667 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000668 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
669 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000670 if (I->isDebugValue())
671 continue;
672
Evan Cheng7f8e5632011-12-07 07:15:52 +0000673 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000674 BBI.CannotBeCopied = true;
675
Evan Cheng4dd31a72007-06-11 22:26:22 +0000676 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000677 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000678
Joey Goulya5153cb2013-09-09 14:21:49 +0000679 // A conditional branch is not predicable, but it may be eliminated.
680 if (isCondBr)
681 continue;
682
683 if (!isPredicated) {
684 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000685 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
686 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000687 if (NumCycles > 1)
688 BBI.ExtraCost += NumCycles-1;
689 BBI.ExtraCost2 += ExtraPredCost;
690 } else if (!AlreadyPredicated) {
691 // FIXME: This instruction is already predicated before the
692 // if-conversion pass. It's probably something like a conditional move.
693 // Mark this block unpredicable for now.
694 BBI.IsUnpredicable = true;
695 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000696 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000697
698 if (BBI.ClobbersPred && !isPredicated) {
699 // Predicate modification instruction should end the block (except for
700 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000701 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000702 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000703 BBI.IsUnpredicable = true;
704 return;
705 }
706
Evan Chengfbc73092007-07-10 17:50:43 +0000707 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
708 // still potentially predicable.
709 std::vector<MachineOperand> PredDefs;
710 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000711 BBI.ClobbersPred = true;
712
Evan Cheng1f4062f2009-11-21 06:20:26 +0000713 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000714 BBI.IsUnpredicable = true;
715 return;
716 }
717 }
718}
719
720/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
721/// predicated by the specified predicate.
722bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000723 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000724 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000725 // If the block is dead or unpredicable, then it cannot be predicated.
726 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000727 return false;
728
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000729 // If it is already predicated but we couldn't analyze its terminator, the
730 // latter might fallthrough, but we can't determine where to.
731 // Conservatively avoid if-converting again.
732 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
733 return false;
734
Quentin Colombetbdab2272013-07-24 20:20:37 +0000735 // If it is already predicated, check if the new predicate subsumes
736 // its predicate.
737 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000738 return false;
739
740 if (BBI.BrCond.size()) {
741 if (!isTriangle)
742 return false;
743
Bob Wilson2371f4f2009-05-13 23:25:24 +0000744 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000745 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
746 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000747 if (RevBranch) {
748 if (TII->ReverseBranchCondition(Cond))
749 return false;
750 }
751 if (TII->ReverseBranchCondition(RevPred) ||
752 !TII->SubsumesPredicate(Cond, RevPred))
753 return false;
754 }
755
756 return true;
757}
758
Evan Cheng7783f822007-06-08 09:36:04 +0000759/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000760/// the specified block. Record its successors and whether it looks like an
761/// if-conversion candidate.
Evan Cheng3a51c852007-06-16 09:34:52 +0000762IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
763 std::vector<IfcvtToken*> &Tokens) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000764 BBInfo &BBI = BBAnalysis[BB->getNumber()];
765
Evan Cheng4dd31a72007-06-11 22:26:22 +0000766 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
767 return BBI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000768
Evan Cheng4dd31a72007-06-11 22:26:22 +0000769 BBI.BB = BB;
770 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000771
772 ScanInstructions(BBI);
773
Jakub Staszaka4a18f02011-07-10 02:00:16 +0000774 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
775 // considered for ifcvt anymore.
776 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000777 BBI.IsBeingAnalyzed = false;
778 BBI.IsAnalyzed = true;
779 return BBI;
Evan Cheng9030b982007-06-06 10:16:17 +0000780 }
781
Evan Cheng4dd31a72007-06-11 22:26:22 +0000782 // Do not ifcvt if either path is a back edge to the entry block.
783 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
784 BBI.IsBeingAnalyzed = false;
785 BBI.IsAnalyzed = true;
786 return BBI;
787 }
788
Evan Chengb9bff582009-06-15 21:24:34 +0000789 // Do not ifcvt if true and false fallthrough blocks are the same.
790 if (!BBI.FalseBB) {
791 BBI.IsBeingAnalyzed = false;
792 BBI.IsAnalyzed = true;
793 return BBI;
794 }
795
Evan Cheng3a51c852007-06-16 09:34:52 +0000796 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
797 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000798
799 if (TrueBBI.IsDone && FalseBBI.IsDone) {
800 BBI.IsBeingAnalyzed = false;
801 BBI.IsAnalyzed = true;
802 return BBI;
803 }
804
Owen Anderson4f6bf042008-08-14 22:49:33 +0000805 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng312b7232007-06-04 06:47:22 +0000806 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Cheng7783f822007-06-08 09:36:04 +0000807
Evan Cheng3a51c852007-06-16 09:34:52 +0000808 unsigned Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000809 unsigned Dups2 = 0;
Evan Chengc5adcca2012-06-08 21:53:50 +0000810 bool TNeedSub = !TrueBBI.Predicate.empty();
811 bool FNeedSub = !FalseBBI.Predicate.empty();
Evan Cheng3a51c852007-06-16 09:34:52 +0000812 bool Enqueued = false;
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000813
Jakub Staszak15e5b742011-08-03 22:34:43 +0000814 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
815
Evan Cheng51eb2c32007-06-18 08:37:25 +0000816 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000817 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000818 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilsonefd360c2010-10-26 00:02:21 +0000819 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000820 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000821 Prediction) &&
Evan Cheng7783f822007-06-08 09:36:04 +0000822 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
823 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000824 // Diamond:
825 // EBB
826 // / \_
827 // | |
828 // TBB FBB
829 // \ /
Evan Cheng0f745da2007-05-18 00:20:58 +0000830 // TailBB
Evan Cheng79484222007-06-05 23:46:14 +0000831 // Note TailBB can be empty.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000832 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
833 Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000834 Enqueued = true;
835 }
836
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000837 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000838 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000839 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000840 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
841 // Triangle:
842 // EBB
843 // | \_
844 // | |
845 // | TBB
846 // | /
847 // FBB
848 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
849 Enqueued = true;
850 }
Bob Wilson81051442010-06-15 22:18:54 +0000851
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000852 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000853 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000854 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000855 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
856 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
857 Enqueued = true;
858 }
859
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000860 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000861 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000862 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000863 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
864 // Simple (split, no rejoin):
865 // EBB
866 // | \_
867 // | |
868 // | TBB---> exit
Bob Wilson81051442010-06-15 22:18:54 +0000869 // |
Evan Cheng3a51c852007-06-16 09:34:52 +0000870 // FBB
871 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
872 Enqueued = true;
873 }
874
875 if (CanRevCond) {
876 // Try the other path...
Owen Andersonf31f33e2010-10-01 22:45:50 +0000877 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000878 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000879 MeetIfcvtSizeLimit(*FalseBBI.BB,
880 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000881 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000882 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
883 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
884 Enqueued = true;
885 }
886
Owen Andersonf31f33e2010-10-01 22:45:50 +0000887 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000888 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000889 MeetIfcvtSizeLimit(*FalseBBI.BB,
890 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000891 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000892 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
893 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
894 Enqueued = true;
895 }
896
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000897 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000898 MeetIfcvtSizeLimit(*FalseBBI.BB,
899 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000900 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000901 FeasibilityAnalysis(FalseBBI, RevCond)) {
902 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
903 Enqueued = true;
Evan Cheng312b7232007-06-04 06:47:22 +0000904 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000905 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000906
Evan Cheng3a51c852007-06-16 09:34:52 +0000907 BBI.IsEnqueued = Enqueued;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000908 BBI.IsBeingAnalyzed = false;
909 BBI.IsAnalyzed = true;
910 return BBI;
Evan Cheng2e82cef2007-05-18 18:14:37 +0000911}
912
Evan Cheng905a8f42007-05-30 19:49:19 +0000913/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000914/// candidates.
915void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Cheng3a51c852007-06-16 09:34:52 +0000916 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng9808d312011-04-27 19:32:43 +0000917 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
918 MachineBasicBlock *BB = I;
919 AnalyzeBlock(BB, Tokens);
Evan Chengf5e53a52007-05-16 02:00:57 +0000920 }
Evan Cheng905a8f42007-05-30 19:49:19 +0000921
Evan Cheng20e05992007-06-01 00:12:12 +0000922 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000923 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000924}
925
Evan Cheng288f1542007-06-08 22:01:07 +0000926/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
927/// that all the intervening blocks are empty (given BB can fall through to its
928/// next block).
929static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000930 MachineFunction::iterator PI = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000931 MachineFunction::iterator I = std::next(PI);
Evan Cheng2c1acd62007-06-05 07:05:25 +0000932 MachineFunction::iterator TI = ToBB;
933 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000934 while (I != TI) {
935 // Check isSuccessor to avoid case where the next block is empty, but
936 // it's not a successor.
937 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Cheng312b7232007-06-04 06:47:22 +0000938 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000939 PI = I++;
940 }
Evan Cheng312b7232007-06-04 06:47:22 +0000941 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000942}
943
Evan Cheng51eb2c32007-06-18 08:37:25 +0000944/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
945/// to determine if it can be if-converted. If predecessor is already enqueued,
946/// dequeue it!
947void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000948 for (const auto &Predecessor : BB->predecessors()) {
949 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000950 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000951 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000952 PBBI.IsAnalyzed = false;
953 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000954 }
955}
956
Evan Chengc2237ce2007-05-29 22:31:16 +0000957/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
958///
959static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
960 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000961 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000962 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000963 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +0000964}
965
Evan Cheng288f1542007-06-08 22:01:07 +0000966/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
967/// successors.
968void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +0000969 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000970 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000971 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
972 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +0000973}
974
Matthias Braund616ccc2013-10-11 19:04:37 +0000975/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
976/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +0000977static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Matthias Braund616ccc2013-10-11 19:04:37 +0000978 for (ConstMIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
979 if (!Ops->isReg() || !Ops->isKill())
980 continue;
981 unsigned Reg = Ops->getReg();
982 if (Reg == 0)
983 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +0000984 Redefs.removeReg(Reg);
Evan Chengf128bdc2010-06-16 07:35:02 +0000985 }
Matthias Braund616ccc2013-10-11 19:04:37 +0000986 for (MIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
987 if (!Ops->isReg() || !Ops->isDef())
988 continue;
989 unsigned Reg = Ops->getReg();
Juergen Ributzka310034e2013-12-14 06:52:56 +0000990 if (Reg == 0 || Redefs.contains(Reg))
Matthias Braund616ccc2013-10-11 19:04:37 +0000991 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +0000992 Redefs.addReg(Reg);
Matthias Braund616ccc2013-10-11 19:04:37 +0000993
994 MachineOperand &Op = *Ops;
995 MachineInstr *MI = Op.getParent();
996 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
997 MIB.addReg(Reg, RegState::Implicit | RegState::Undef);
998 }
999}
1000
1001/**
1002 * Remove kill flags from operands with a registers in the @p DontKill set.
1003 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001004static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001005 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1006 if (!O->isReg() || !O->isKill())
1007 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001008 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001009 O->setIsKill(false);
1010 }
1011}
1012
1013/**
1014 * Walks a range of machine instructions and removes kill flags for registers
1015 * in the @p DontKill set.
1016 */
1017static void RemoveKills(MachineBasicBlock::iterator I,
1018 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001019 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001020 const MCRegisterInfo &MCRI) {
1021 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001022 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001023}
1024
Evan Cheng312b7232007-06-04 06:47:22 +00001025/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001026///
Evan Cheng3a51c852007-06-16 09:34:52 +00001027bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001028 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1029 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1030 BBInfo *CvtBBI = &TrueBBI;
1031 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001032
Owen Anderson4f6bf042008-08-14 22:49:33 +00001033 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001034 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001035 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001036
Evan Cheng51eb2c32007-06-18 08:37:25 +00001037 if (CvtBBI->IsDone ||
1038 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001039 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001040 BBI.IsAnalyzed = false;
1041 CvtBBI->IsAnalyzed = false;
1042 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001043 }
Evan Chengd0e66912007-05-23 07:23:16 +00001044
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001045 if (CvtBBI->BB->hasAddressTaken())
1046 // Conservatively abort if-conversion if BB's address is taken.
1047 return false;
1048
Evan Cheng3a51c852007-06-16 09:34:52 +00001049 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001050 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001051 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001052
Bob Wilson45814342010-06-19 05:33:57 +00001053 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001054 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001055 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001056 Redefs.addLiveIns(CvtBBI->BB);
1057 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001058
1059 // Compute a set of registers which must not be killed by instructions in
1060 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001061 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001062 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001063
Evan Cheng92fb5452007-06-15 07:36:12 +00001064 if (CvtBBI->BB->pred_size() > 1) {
1065 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001066 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001067 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001068 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001069
1070 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1071 // explicitly remove CvtBBI as a successor.
1072 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001073 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001074 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001075 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001076
Evan Cheng92fb5452007-06-15 07:36:12 +00001077 // Merge converted block into entry block.
1078 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1079 MergeBlocks(BBI, *CvtBBI);
1080 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001081
Evan Chenge4ec9182007-06-06 02:08:52 +00001082 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001083 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001084 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001085 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001086 // Now ifcvt'd block will look like this:
1087 // BB:
1088 // ...
1089 // t, f = cmp
1090 // if t op
1091 // b BBf
1092 //
1093 // We cannot further ifcvt this block because the unconditional branch
1094 // will have to be predicated on the new condition, that will not be
1095 // available if cmp executes.
1096 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001097 }
Evan Chenge26c0912007-05-21 22:22:58 +00001098
Evan Cheng288f1542007-06-08 22:01:07 +00001099 RemoveExtraEdges(BBI);
1100
Evan Chengd0e66912007-05-23 07:23:16 +00001101 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001102 if (!IterIfcvt)
1103 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001104 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001105 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001106
1107 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001108 return true;
1109}
1110
Manman Renb6819182014-01-29 23:18:47 +00001111/// Scale down weights to fit into uint32_t. NewTrue is the new weight
1112/// for successor TrueBB, and NewFalse is the new weight for successor
1113/// FalseBB.
1114static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1115 MachineBasicBlock *MBB,
1116 const MachineBasicBlock *TrueBB,
1117 const MachineBasicBlock *FalseBB,
1118 const MachineBranchProbabilityInfo *MBPI) {
1119 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1120 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1121 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1122 SE = MBB->succ_end();
1123 SI != SE; ++SI) {
1124 if (*SI == TrueBB)
1125 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1126 else if (*SI == FalseBB)
1127 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1128 else
1129 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1130 }
1131}
1132
Evan Chengaf716102007-05-16 21:54:37 +00001133/// IfConvertTriangle - If convert a triangle sub-CFG.
1134///
Evan Cheng3a51c852007-06-16 09:34:52 +00001135bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001136 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001137 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1138 BBInfo *CvtBBI = &TrueBBI;
1139 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001140 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001141
Owen Anderson4f6bf042008-08-14 22:49:33 +00001142 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001143 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001144 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001145
Evan Cheng51eb2c32007-06-18 08:37:25 +00001146 if (CvtBBI->IsDone ||
1147 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001148 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001149 BBI.IsAnalyzed = false;
1150 CvtBBI->IsAnalyzed = false;
1151 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001152 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001153
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001154 if (CvtBBI->BB->hasAddressTaken())
1155 // Conservatively abort if-conversion if BB's address is taken.
1156 return false;
1157
Evan Cheng3a51c852007-06-16 09:34:52 +00001158 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001159 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001160 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001161
Evan Cheng3a51c852007-06-16 09:34:52 +00001162 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001163 if (ReverseBranchCondition(*CvtBBI)) {
1164 // BB has been changed, modify its predecessors (except for this
1165 // one) so they don't get ifcvt'ed based on bad intel.
1166 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1167 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1168 MachineBasicBlock *PBB = *PI;
1169 if (PBB == BBI.BB)
1170 continue;
1171 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1172 if (PBBI.IsEnqueued) {
1173 PBBI.IsAnalyzed = false;
1174 PBBI.IsEnqueued = false;
1175 }
Evan Chengadd97762007-06-14 23:34:09 +00001176 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001177 }
1178 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001179
Bob Wilson45814342010-06-19 05:33:57 +00001180 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001181 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001182 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001183 Redefs.addLiveIns(CvtBBI->BB);
1184 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001185
Andrew Trick276dd452013-10-14 20:45:17 +00001186 DontKill.clear();
1187
Craig Topperc0196b12014-04-14 00:51:57 +00001188 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Manman Ren37c92672014-02-07 00:38:56 +00001189 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
Manman Renb6819182014-01-29 23:18:47 +00001190 uint32_t WeightScale = 0;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001191
Manman Renb6819182014-01-29 23:18:47 +00001192 if (HasEarlyExit) {
Manman Ren37c92672014-02-07 00:38:56 +00001193 // Get weights before modifying CvtBBI->BB and BBI.BB.
Manman Renb6819182014-01-29 23:18:47 +00001194 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1195 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
Manman Ren37c92672014-02-07 00:38:56 +00001196 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1197 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001198 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
1199 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001200
Bob Wilson1e5da552010-06-29 00:55:23 +00001201 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001202 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001203 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001204 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001205 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001206
1207 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1208 // explicitly remove CvtBBI as a successor.
1209 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001210 } else {
1211 // Predicate the 'true' block after removing its branch.
1212 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001213 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001214
Evan Cheng0598b2d2007-06-18 22:44:57 +00001215 // Now merge the entry of the triangle with the true block.
1216 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001217 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001218 }
1219
Evan Cheng312b7232007-06-04 06:47:22 +00001220 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001221 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001222 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1223 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001224 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001225 llvm_unreachable("Unable to reverse branch condition!");
Craig Topperc0196b12014-04-14 00:51:57 +00001226 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001227 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Manman Renb6819182014-01-29 23:18:47 +00001228 // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1229 // New_Weight(BBI.BB, NextBBI->BB) =
1230 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1231 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1232 // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1233 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1234
Manman Renb6819182014-01-29 23:18:47 +00001235 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1236 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
1237 // We need to scale down all weights of BBI.BB to fit uint32_t.
1238 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1239 // the next block.
1240 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1241 CvtBBI->FalseBB, MBPI);
Evan Cheng92fb5452007-06-15 07:36:12 +00001242 }
Evan Cheng7783f822007-06-08 09:36:04 +00001243
1244 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001245 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001246 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001247 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001248 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001249 if (!isFallThrough) {
1250 // Only merge them if the true block does not fallthrough to the false
1251 // block. By not merging them, we make it possible to iteratively
1252 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001253 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001254 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1255 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001256 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001257 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001258 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001259 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1260 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001261 }
Evan Cheng7783f822007-06-08 09:36:04 +00001262 // Mixed predicated and unpredicated code. This cannot be iteratively
1263 // predicated.
1264 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001265 }
Evan Chenge26c0912007-05-21 22:22:58 +00001266
Evan Cheng288f1542007-06-08 22:01:07 +00001267 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001268
Evan Chengd0e66912007-05-23 07:23:16 +00001269 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001270 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001271 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001272 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001273 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001274 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001275 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001276
1277 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001278 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001279}
1280
Evan Chengaf716102007-05-16 21:54:37 +00001281/// IfConvertDiamond - If convert a diamond sub-CFG.
1282///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001283bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1284 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001285 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001286 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001287 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001288 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001289 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001290 if (blockAlwaysFallThrough(TrueBBI))
1291 TailBB = FalseBBI.TrueBB;
1292 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001293 }
Evan Chenge26c0912007-05-21 22:22:58 +00001294
Evan Cheng51eb2c32007-06-18 08:37:25 +00001295 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1296 TrueBBI.BB->pred_size() > 1 ||
1297 FalseBBI.BB->pred_size() > 1) {
1298 // Something has changed. It's no longer safe to predicate these blocks.
1299 BBI.IsAnalyzed = false;
1300 TrueBBI.IsAnalyzed = false;
1301 FalseBBI.IsAnalyzed = false;
1302 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001303 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001304
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001305 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1306 // Conservatively abort if-conversion if either BB has its address taken.
1307 return false;
1308
Bob Wilson1e5da552010-06-29 00:55:23 +00001309 // Put the predicated instructions from the 'true' block before the
1310 // instructions from the 'false' block, unless the true block would clobber
1311 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001312 BBInfo *BBI1 = &TrueBBI;
1313 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001314 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001315 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001316 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001317 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1318 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001319
Evan Cheng3a51c852007-06-16 09:34:52 +00001320 // Figure out the more profitable ordering.
1321 bool DoSwap = false;
1322 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1323 DoSwap = true;
1324 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001325 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001326 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001327 }
1328 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001329 std::swap(BBI1, BBI2);
1330 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001331 }
Evan Cheng79484222007-06-05 23:46:14 +00001332
Evan Cheng51eb2c32007-06-18 08:37:25 +00001333 // Remove the conditional branch from entry to the blocks.
1334 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1335
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001336 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001337 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001338 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001339 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001340
Evan Cheng51eb2c32007-06-18 08:37:25 +00001341 // Remove the duplicated instructions at the beginnings of both paths.
1342 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1343 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbach412800d2010-06-14 21:30:32 +00001344 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1345 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1346 // Skip dbg_value instructions
1347 while (DI1 != DIE1 && DI1->isDebugValue())
1348 ++DI1;
1349 while (DI2 != DIE2 && DI2->isDebugValue())
1350 ++DI2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001351 BBI1->NonPredSize -= NumDups1;
1352 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001353
1354 // Skip past the dups on each side separately since there may be
1355 // differing dbg_value entries.
1356 for (unsigned i = 0; i < NumDups1; ++DI1) {
1357 if (!DI1->isDebugValue())
1358 ++i;
1359 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001360 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001361 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001362 if (!DI2->isDebugValue())
1363 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001364 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001365
Matthias Braund616ccc2013-10-11 19:04:37 +00001366 // Compute a set of registers which must not be killed by instructions in BB1:
1367 // This is everything used+live in BB2 after the duplicated instructions. We
1368 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001369 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001370 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1371 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001372 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001373 }
1374
1375 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1376 ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001377 Redefs.stepForward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001378 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001379 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1380 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1381
Evan Cheng4266a792011-12-19 22:01:30 +00001382 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng79484222007-06-05 23:46:14 +00001383 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001384 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001385 for (unsigned i = 0; i != NumDups2; ) {
1386 // NumDups2 only counted non-dbg_value instructions, so this won't
1387 // run off the head of the list.
1388 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001389 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001390 // skip dbg_value instructions
1391 if (!DI1->isDebugValue())
1392 ++i;
1393 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001394 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001395
Matthias Braund616ccc2013-10-11 19:04:37 +00001396 // Kill flags in the true block for registers living into the false block
1397 // must be removed.
1398 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1399
Evan Cheng4266a792011-12-19 22:01:30 +00001400 // Remove 'false' block branch and find the last instruction to predicate.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001401 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1402 DI2 = BBI2->BB->end();
1403 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001404 // NumDups2 only counted non-dbg_value instructions, so this won't
1405 // run off the head of the list.
1406 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001407 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001408 // skip dbg_value instructions
1409 if (!DI2->isDebugValue())
1410 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001411 }
Evan Cheng4266a792011-12-19 22:01:30 +00001412
1413 // Remember which registers would later be defined by the false block.
1414 // This allows us not to predicate instructions in the true block that would
1415 // later be re-defined. That is, rather than
1416 // subeq r0, r1, #1
1417 // addne r0, r1, #1
1418 // generate:
1419 // sub r0, r1, #1
1420 // addne r0, r1, #1
1421 SmallSet<unsigned, 4> RedefsByFalse;
1422 SmallSet<unsigned, 4> ExtUses;
1423 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1424 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1425 if (FI->isDebugValue())
1426 continue;
1427 SmallVector<unsigned, 4> Defs;
1428 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1429 const MachineOperand &MO = FI->getOperand(i);
1430 if (!MO.isReg())
1431 continue;
1432 unsigned Reg = MO.getReg();
1433 if (!Reg)
1434 continue;
1435 if (MO.isDef()) {
1436 Defs.push_back(Reg);
1437 } else if (!RedefsByFalse.count(Reg)) {
1438 // These are defined before ctrl flow reach the 'false' instructions.
1439 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001440 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1441 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001442 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001443 }
1444 }
1445
1446 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1447 unsigned Reg = Defs[i];
1448 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001449 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1450 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001451 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001452 }
1453 }
1454 }
1455 }
1456
1457 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001458 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001459
1460 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001461 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001462
Evan Cheng0598b2d2007-06-18 22:44:57 +00001463 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001464 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1465 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001466
Bob Wilson2371f4f2009-05-13 23:25:24 +00001467 // If the if-converted block falls through or unconditionally branches into
1468 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001469 // fold the tail block in as well. Otherwise, unless it falls through to the
1470 // tail, add a unconditional branch to it.
1471 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001472 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001473 bool CanMergeTail = !TailBBI.HasFallThrough &&
1474 !TailBBI.BB->hasAddressTaken();
Bob Wilson1e5da552010-06-29 00:55:23 +00001475 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1476 // check if there are any other predecessors besides those.
1477 unsigned NumPreds = TailBB->pred_size();
1478 if (NumPreds > 1)
1479 CanMergeTail = false;
1480 else if (NumPreds == 1 && CanMergeTail) {
1481 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1482 if (*PI != BBI1->BB && *PI != BBI2->BB)
1483 CanMergeTail = false;
1484 }
1485 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001486 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001487 TailBBI.IsDone = true;
1488 } else {
Bob Wilson1e5da552010-06-29 00:55:23 +00001489 BBI.BB->addSuccessor(TailBB);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001490 InsertUncondBranch(BBI.BB, TailBB, TII);
1491 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001492 }
Evan Chenge26c0912007-05-21 22:22:58 +00001493 }
1494
Bob Wilson1e5da552010-06-29 00:55:23 +00001495 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1496 // which can happen here if TailBB is unanalyzable and is merged, so
1497 // explicitly remove BBI1 and BBI2 as successors.
1498 BBI.BB->removeSuccessor(BBI1->BB);
1499 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng288f1542007-06-08 22:01:07 +00001500 RemoveExtraEdges(BBI);
1501
Evan Cheng79484222007-06-05 23:46:14 +00001502 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001503 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001504 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001505
1506 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001507 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001508}
1509
Evan Cheng4266a792011-12-19 22:01:30 +00001510static bool MaySpeculate(const MachineInstr *MI,
1511 SmallSet<unsigned, 4> &LaterRedefs,
1512 const TargetInstrInfo *TII) {
1513 bool SawStore = true;
Craig Topperc0196b12014-04-14 00:51:57 +00001514 if (!MI->isSafeToMove(TII, nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001515 return false;
1516
1517 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1518 const MachineOperand &MO = MI->getOperand(i);
1519 if (!MO.isReg())
1520 continue;
1521 unsigned Reg = MO.getReg();
1522 if (!Reg)
1523 continue;
1524 if (MO.isDef() && !LaterRedefs.count(Reg))
1525 return false;
1526 }
1527
1528 return true;
1529}
1530
Evan Cheng51eb2c32007-06-18 08:37:25 +00001531/// PredicateBlock - Predicate instructions from the start of the block to the
1532/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001533void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001534 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001535 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001536 SmallSet<unsigned, 4> *LaterRedefs) {
1537 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001538 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001539 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001540 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001541 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001542 // It may be possible not to predicate an instruction if it's the 'true'
1543 // side of a diamond and the 'false' side may re-define the instruction's
1544 // defs.
1545 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1546 AnyUnpred = true;
1547 continue;
1548 }
1549 // If any instruction is predicated, then every instruction after it must
1550 // be predicated.
1551 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001552 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001553#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001554 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001555#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001556 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001557 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001558
Bob Wilson45814342010-06-19 05:33:57 +00001559 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001560 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001561 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001562 }
Evan Chengd0e66912007-05-23 07:23:16 +00001563
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001564 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001565
Evan Cheng92fb5452007-06-15 07:36:12 +00001566 BBI.IsAnalyzed = false;
1567 BBI.NonPredSize = 0;
1568
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001569 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001570 if (AnyUnpred)
1571 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001572}
1573
Evan Cheng92fb5452007-06-15 07:36:12 +00001574/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1575/// the destination block. Skip end of block branches if IgnoreBr is true.
1576void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001577 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001578 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001579 MachineFunction &MF = *ToBBI.BB->getParent();
1580
Evan Cheng92fb5452007-06-15 07:36:12 +00001581 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1582 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001583 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001584 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001585 break;
1586
Dan Gohman3b460302008-07-07 23:14:23 +00001587 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001588 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001589 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001590 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1591 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001592 if (NumCycles > 1)
1593 ToBBI.ExtraCost += NumCycles-1;
1594 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001595
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001596 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001597 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001598#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001599 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001600#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001601 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001602 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001603 }
1604
Bob Wilson45814342010-06-19 05:33:57 +00001605 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001606 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001607 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001608
1609 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001610 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001611 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001612 }
1613
Bob Wilson1e5da552010-06-29 00:55:23 +00001614 if (!IgnoreBr) {
1615 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1616 FromBBI.BB->succ_end());
1617 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001618 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001619
Bob Wilson1e5da552010-06-29 00:55:23 +00001620 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1621 MachineBasicBlock *Succ = Succs[i];
1622 // Fallthrough edge can't be transferred.
1623 if (Succ == FallThrough)
1624 continue;
1625 ToBBI.BB->addSuccessor(Succ);
1626 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001627 }
1628
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001629 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1630 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001631
1632 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1633 ToBBI.IsAnalyzed = false;
1634
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001635 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001636}
1637
Evan Cheng0f745da2007-05-18 00:20:58 +00001638/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001639/// This will leave FromBB as an empty block, so remove all of its
1640/// successor edges except for the fall-through edge. If AddEdges is true,
1641/// i.e., when FromBBI's branch is being moved, add those successor edges to
1642/// ToBBI.
1643void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001644 assert(!FromBBI.BB->hasAddressTaken() &&
1645 "Removing a BB whose address is taken!");
1646
Evan Cheng0f745da2007-05-18 00:20:58 +00001647 ToBBI.BB->splice(ToBBI.BB->end(),
1648 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001649
Evan Chengbe9859e2007-06-07 02:12:15 +00001650 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1651 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001652 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001653 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng312b7232007-06-04 06:47:22 +00001654
Evan Chengbe9859e2007-06-07 02:12:15 +00001655 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1656 MachineBasicBlock *Succ = Succs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001657 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001658 if (Succ == FallThrough)
1659 continue;
1660 FromBBI.BB->removeSuccessor(Succ);
Jakob Stoklund Olesene0ef4742013-01-24 23:59:08 +00001661 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
Bob Wilson1e5da552010-06-29 00:55:23 +00001662 ToBBI.BB->addSuccessor(Succ);
Evan Chengbe9859e2007-06-07 02:12:15 +00001663 }
1664
Bob Wilson2371f4f2009-05-13 23:25:24 +00001665 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001666 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001667 FromBBI.BB->addSuccessor(NBB);
1668
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001669 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001670 FromBBI.Predicate.clear();
1671
Evan Chengd0e66912007-05-23 07:23:16 +00001672 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001673 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001674 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001675 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001676 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001677 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001678
Evan Cheng4dd31a72007-06-11 22:26:22 +00001679 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001680 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001681 ToBBI.IsAnalyzed = false;
1682 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001683}