blob: a4ce9c6f0192bce820182e107d49d929f6f1ac1e [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebar46123a82016-02-22 18:17:27 +000010// This file implements the machine instruction level if-conversion pass.
Evan Chengf5e53a52007-05-16 02:00:57 +000011//
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 Chenge93ccc02007-06-08 19:10:51 +000027#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000028#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000029#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000035#include <algorithm>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036
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;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000174 std::function<bool(const Function &)> PredicateFtor;
175
Evan Chengf5e53a52007-05-16 02:00:57 +0000176 public:
177 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000178 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
179 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000180 initializeIfConverterPass(*PassRegistry::getPassRegistry());
181 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000182
Craig Topper4584cd52014-03-07 09:26:03 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000184 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000185 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000186 MachineFunctionPass::getAnalysisUsage(AU);
187 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000188
Craig Topper4584cd52014-03-07 09:26:03 +0000189 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000190
191 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000192 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000193 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000194 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000195 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000196 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000197 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000198 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
199 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000200 void ScanInstructions(BBInfo &BBI);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000201 void AnalyzeBlock(MachineBasicBlock *MBB,
202 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000203 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000204 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000205 void AnalyzeBlocks(MachineFunction &MF,
206 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000207 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000208 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000209 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
210 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000211 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
212 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000213 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000214 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000215 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000216 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000217 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000218 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000219 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000220 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000221
Evan Chengdebf9c52010-11-03 00:45:17 +0000222 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
223 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000224 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000225 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000226 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000227 }
228
Evan Chengdebf9c52010-11-03 00:45:17 +0000229 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
230 unsigned TCycle, unsigned TExtra,
231 MachineBasicBlock &FBB,
232 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000233 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000234 return TCycle > 0 && FCycle > 0 &&
235 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000236 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000237 }
238
Evan Chengbe9859e2007-06-07 02:12:15 +0000239 // blockAlwaysFallThrough - Block ends without a terminator.
240 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000241 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000242 }
243
Evan Cheng3a51c852007-06-16 09:34:52 +0000244 // IfcvtTokenCmp - Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000245 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
246 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000247 int Incr1 = (C1->Kind == ICDiamond)
248 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
249 int Incr2 = (C2->Kind == ICDiamond)
250 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
251 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000252 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000253 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000254 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000255 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000256 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000257 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000258 // Favors diamond over triangle, etc.
259 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
260 return true;
261 else if (C1->Kind == C2->Kind)
262 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
263 }
264 }
265 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000266 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000267 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000268
Evan Chengf5e53a52007-05-16 02:00:57 +0000269 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000270}
Evan Chengf5e53a52007-05-16 02:00:57 +0000271
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000272char &llvm::IfConverterID = IfConverter::ID;
273
Owen Anderson8ac477f2010-10-12 19:48:12 +0000274INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000275INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000276INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000277
Evan Chengf5e53a52007-05-16 02:00:57 +0000278bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Akira Hatanaka4a616192015-06-08 18:50:43 +0000279 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
280 return false;
281
Eric Christopher3d4276f2015-01-27 07:31:29 +0000282 const TargetSubtargetInfo &ST = MF.getSubtarget();
283 TLI = ST.getTargetLowering();
284 TII = ST.getInstrInfo();
285 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000286 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000287 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000288 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000289 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000290
Evan Chengf5e53a52007-05-16 02:00:57 +0000291 if (!TII) return false;
292
Evan Chengc5adcca2012-06-08 21:53:50 +0000293 PreRegAlloc = MRI->isSSA();
294
295 bool BFChange = false;
296 if (!PreRegAlloc) {
297 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000298 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000299 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000300 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000301 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000302
David Greene72e47cd2010-01-04 22:02:01 +0000303 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000304 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000305
306 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000307 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000308 return false;
309 }
David Greene72e47cd2010-01-04 22:02:01 +0000310 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000311
Evan Chengf5e53a52007-05-16 02:00:57 +0000312 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000313 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000314
Justin Lebar3a7bc572016-02-22 17:51:28 +0000315 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000316 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000317 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
318 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
319 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000320 // Do an initial analysis for each basic block and find all the potential
321 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000322 bool Change = false;
323 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000324 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000325 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000326 Tokens.pop_back();
327 BBInfo &BBI = Token->BBI;
328 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000329 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000330 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000331
Evan Cheng4dd31a72007-06-11 22:26:22 +0000332 // If the block has been evicted out of the queue or it has already been
333 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000334 if (BBI.IsDone)
335 BBI.IsEnqueued = false;
336 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000337 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000338
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000339 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000340
Evan Cheng312b7232007-06-04 06:47:22 +0000341 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000342 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000343 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000344 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000345 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000346 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000347 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000348 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
349 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000350 << "): BB#" << BBI.BB->getNumber() << " ("
351 << ((Kind == ICSimpleFalse)
352 ? BBI.FalseBB->getNumber()
353 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000354 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000355 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000356 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000357 if (isFalse) ++NumSimpleFalse;
358 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000359 }
Evan Cheng312b7232007-06-04 06:47:22 +0000360 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000361 }
Evan Chengd0e66912007-05-23 07:23:16 +0000362 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000363 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000364 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000365 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000366 bool isFalse = Kind == ICTriangleFalse;
367 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000368 if (DisableTriangle && !isFalse && !isRev) break;
369 if (DisableTriangleR && !isFalse && isRev) break;
370 if (DisableTriangleF && isFalse && !isRev) break;
371 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000372 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000373 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000374 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000375 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000376 DEBUG(dbgs() << " rev");
377 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000378 << BBI.TrueBB->getNumber() << ",F:"
379 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000380 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000381 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000382 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000383 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000384 if (isRev) ++NumTriangleFRev;
385 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000386 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000387 if (isRev) ++NumTriangleRev;
388 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000389 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000390 }
Evan Chengd0e66912007-05-23 07:23:16 +0000391 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000392 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000393 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000394 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000395 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000396 << BBI.TrueBB->getNumber() << ",F:"
397 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000398 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000399 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000400 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000401 break;
402 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000403 }
404
Evan Cheng312b7232007-06-04 06:47:22 +0000405 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000406
Evan Cheng92fb5452007-06-15 07:36:12 +0000407 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
408 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
409 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000410 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000411 }
Evan Chengd0e66912007-05-23 07:23:16 +0000412
Evan Chengd0e66912007-05-23 07:23:16 +0000413 if (!Change)
414 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000415 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000416 }
Evan Cheng478b8052007-05-18 01:55:58 +0000417
Evan Cheng3a51c852007-06-16 09:34:52 +0000418 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000419 BBAnalysis.clear();
420
Evan Chengcf9e8a92010-06-18 22:17:13 +0000421 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000422 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000423 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000424 getAnalysisIfAvailable<MachineModuleInfo>());
425 }
426
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000427 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000428 return MadeChange;
429}
430
Evan Cheng3a51c852007-06-16 09:34:52 +0000431/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
432/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000433static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000434 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000435 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
436 E = BB->succ_end(); SI != E; ++SI) {
437 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000438 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000439 return SuccBB;
440 }
Craig Topperc0196b12014-04-14 00:51:57 +0000441 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000442}
443
Evan Cheng3a51c852007-06-16 09:34:52 +0000444/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000445/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000446bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000447 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000448 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
449 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000450 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000451 std::swap(BBI.TrueBB, BBI.FalseBB);
452 return true;
453 }
454 return false;
455}
456
Evan Cheng2117d1f2007-06-09 01:03:43 +0000457/// getNextBlock - Returns the next block in the function blocks ordering. If
458/// it is the end, returns NULL.
459static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000460 MachineFunction::iterator I = BB->getIterator();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000461 MachineFunction::iterator E = BB->getParent()->end();
462 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000463 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000464 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000465}
466
Evan Cheng7783f822007-06-08 09:36:04 +0000467/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000468/// predecessor) forms a valid simple shape for ifcvt. It also returns the
469/// number of instructions that the ifcvt would need to duplicate if performed
470/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000471bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000472 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000473 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000474 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000475 return false;
476
Evan Chenga955c022007-06-19 21:45:13 +0000477 if (TrueBBI.IsBrAnalyzable)
478 return false;
479
Evan Cheng23402fc2007-06-15 21:18:05 +0000480 if (TrueBBI.BB->pred_size() > 1) {
481 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000482 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000483 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000484 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000485 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000486 }
487
Evan Chenga955c022007-06-19 21:45:13 +0000488 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000489}
490
Evan Cheng7783f822007-06-08 09:36:04 +0000491/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000492/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000493/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000494/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000495/// returns the number of instructions that the ifcvt would need to duplicate
496/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000497bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000498 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000499 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000500 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000502 return false;
503
Evan Cheng23402fc2007-06-15 21:18:05 +0000504 if (TrueBBI.BB->pred_size() > 1) {
505 if (TrueBBI.CannotBeCopied)
506 return false;
507
Evan Cheng92fb5452007-06-15 07:36:12 +0000508 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000509 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000510 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000511 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000512 --Size;
513 else {
514 MachineBasicBlock *FExit = FalseBranch
515 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
516 if (FExit)
517 // Require a conditional branch
518 ++Size;
519 }
520 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000521 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000522 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000523 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000524 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000525
Evan Cheng7783f822007-06-08 09:36:04 +0000526 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
527 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000528 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000529 if (++I == TrueBBI.BB->getParent()->end())
530 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000531 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000532 }
Evan Cheng7783f822007-06-08 09:36:04 +0000533 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000534}
535
Evan Cheng7783f822007-06-08 09:36:04 +0000536/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000537/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000538bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
539 unsigned &Dups1, unsigned &Dups2) const {
540 Dups1 = Dups2 = 0;
541 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
542 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000543 return false;
544
Evan Cheng2117d1f2007-06-09 01:03:43 +0000545 MachineBasicBlock *TT = TrueBBI.TrueBB;
546 MachineBasicBlock *FT = FalseBBI.TrueBB;
547
548 if (!TT && blockAlwaysFallThrough(TrueBBI))
549 TT = getNextBlock(TrueBBI.BB);
550 if (!FT && blockAlwaysFallThrough(FalseBBI))
551 FT = getNextBlock(FalseBBI.BB);
552 if (TT != FT)
553 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000554 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000555 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000556 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
557 return false;
558
559 // FIXME: Allow true block to have an early exit?
560 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
561 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000562 return false;
563
Bob Wilsone1961fe2010-10-26 00:02:24 +0000564 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000565 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
566 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000567 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
568 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
569 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000570 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000571 if (TIB->isDebugValue()) {
572 while (TIB != TIE && TIB->isDebugValue())
573 ++TIB;
574 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000575 break;
576 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000577 if (FIB->isDebugValue()) {
578 while (FIB != FIE && FIB->isDebugValue())
579 ++FIB;
580 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000581 break;
582 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000583 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000584 break;
585 ++Dups1;
586 ++TIB;
587 ++FIB;
588 }
589
590 // Now, in preparation for counting duplicate instructions at the ends of the
591 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000592 // If both blocks are returning don't skip the branches, since they will
593 // likely be both identical return instructions. In such cases the return
594 // can be left unpredicated.
595 // Check for already containing all of the block.
596 if (TIB == TIE || FIB == FIE)
597 return true;
598 --TIE;
599 --FIE;
600 if (!TrueBBI.BB->succ_empty() || !FalseBBI.BB->succ_empty()) {
601 while (TIE != TIB && TIE->isBranch())
602 --TIE;
603 while (FIE != FIB && FIE->isBranch())
604 --FIE;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000605 }
606
607 // If Dups1 includes all of a block, then don't count duplicate
608 // instructions at the end of the blocks.
609 if (TIB == TIE || FIB == FIE)
610 return true;
611
612 // Count duplicate instructions at the ends of the blocks.
613 while (TIE != TIB && FIE != FIB) {
614 // Skip dbg_value instructions. These do not count.
615 if (TIE->isDebugValue()) {
616 while (TIE != TIB && TIE->isDebugValue())
617 --TIE;
618 if (TIE == TIB)
619 break;
620 }
621 if (FIE->isDebugValue()) {
622 while (FIE != FIB && FIE->isDebugValue())
623 --FIE;
624 if (FIE == FIB)
625 break;
626 }
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000627 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000628 break;
629 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000630 --TIE;
631 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000632 }
633
634 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000635}
636
Evan Cheng4dd31a72007-06-11 22:26:22 +0000637/// ScanInstructions - Scan all the instructions in the block to determine if
638/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000639/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000640/// instruction which can clobber a predicate (e.g. condition code register).
641/// If so, the block is not predicable unless it's the last instruction.
642void IfConverter::ScanInstructions(BBInfo &BBI) {
643 if (BBI.IsDone)
644 return;
645
Evan Chengc5adcca2012-06-08 21:53:50 +0000646 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000647 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000648 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000649 BBI.BrCond.clear();
650 BBI.IsBrAnalyzable =
651 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000652 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000653
654 if (BBI.BrCond.size()) {
655 // No false branch. This BB must end with a conditional branch and a
656 // fallthrough.
657 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000658 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000659 if (!BBI.FalseBB) {
660 // Malformed bcc? True and false blocks are the same?
661 BBI.IsUnpredicable = true;
662 return;
663 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000664 }
665
666 // Then scan all the instructions.
667 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000668 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000669 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000670 BBI.ClobbersPred = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000671 for (auto &MI : *BBI.BB) {
672 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000673 continue;
674
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000675 if (MI.isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000676 BBI.CannotBeCopied = true;
677
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000678 bool isPredicated = TII->isPredicated(MI);
679 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000680
Joey Goulya5153cb2013-09-09 14:21:49 +0000681 // A conditional branch is not predicable, but it may be eliminated.
682 if (isCondBr)
683 continue;
684
685 if (!isPredicated) {
686 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000687 unsigned ExtraPredCost = TII->getPredicationCost(MI);
688 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000689 if (NumCycles > 1)
690 BBI.ExtraCost += NumCycles-1;
691 BBI.ExtraCost2 += ExtraPredCost;
692 } else if (!AlreadyPredicated) {
693 // FIXME: This instruction is already predicated before the
694 // if-conversion pass. It's probably something like a conditional move.
695 // Mark this block unpredicable for now.
696 BBI.IsUnpredicable = true;
697 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000698 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000699
700 if (BBI.ClobbersPred && !isPredicated) {
701 // Predicate modification instruction should end the block (except for
702 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000703 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000704 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000705 BBI.IsUnpredicable = true;
706 return;
707 }
708
Evan Chengfbc73092007-07-10 17:50:43 +0000709 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
710 // still potentially predicable.
711 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000712 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000713 BBI.ClobbersPred = true;
714
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000715 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000716 BBI.IsUnpredicable = true;
717 return;
718 }
719 }
720}
721
722/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
723/// predicated by the specified predicate.
724bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000725 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000726 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000727 // If the block is dead or unpredicable, then it cannot be predicated.
728 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000729 return false;
730
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000731 // If it is already predicated but we couldn't analyze its terminator, the
732 // latter might fallthrough, but we can't determine where to.
733 // Conservatively avoid if-converting again.
734 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
735 return false;
736
Quentin Colombetbdab2272013-07-24 20:20:37 +0000737 // If it is already predicated, check if the new predicate subsumes
738 // its predicate.
739 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000740 return false;
741
742 if (BBI.BrCond.size()) {
743 if (!isTriangle)
744 return false;
745
Bob Wilson2371f4f2009-05-13 23:25:24 +0000746 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000747 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
748 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000749 if (RevBranch) {
750 if (TII->ReverseBranchCondition(Cond))
751 return false;
752 }
753 if (TII->ReverseBranchCondition(RevPred) ||
754 !TII->SubsumesPredicate(Cond, RevPred))
755 return false;
756 }
757
758 return true;
759}
760
Evan Cheng7783f822007-06-08 09:36:04 +0000761/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000762/// the specified block. Record its successors and whether it looks like an
763/// if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000764void IfConverter::AnalyzeBlock(
765 MachineBasicBlock *MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000766 struct BBState {
767 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
768 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000769
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000770 /// This flag is true if MBB's successors have been analyzed.
771 bool SuccsAnalyzed;
772 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000773
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000774 // Push MBB to the stack.
775 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000776
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000777 while (!BBStack.empty()) {
778 BBState &State = BBStack.back();
779 MachineBasicBlock *BB = State.MBB;
780 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000781
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000782 if (!State.SuccsAnalyzed) {
783 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
784 BBStack.pop_back();
785 continue;
786 }
Evan Cheng9030b982007-06-06 10:16:17 +0000787
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000788 BBI.BB = BB;
789 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000790
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000791 ScanInstructions(BBI);
Evan Chengb9bff582009-06-15 21:24:34 +0000792
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000793 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
794 // not considered for ifcvt anymore.
795 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
796 BBI.IsBeingAnalyzed = false;
797 BBI.IsAnalyzed = true;
798 BBStack.pop_back();
799 continue;
800 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000801
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000802 // Do not ifcvt if either path is a back edge to the entry block.
803 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
804 BBI.IsBeingAnalyzed = false;
805 BBI.IsAnalyzed = true;
806 BBStack.pop_back();
807 continue;
808 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000809
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000810 // Do not ifcvt if true and false fallthrough blocks are the same.
811 if (!BBI.FalseBB) {
812 BBI.IsBeingAnalyzed = false;
813 BBI.IsAnalyzed = true;
814 BBStack.pop_back();
815 continue;
816 }
Evan Cheng7783f822007-06-08 09:36:04 +0000817
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000818 // Push the False and True blocks to the stack.
819 State.SuccsAnalyzed = true;
820 BBStack.push_back(BBI.FalseBB);
821 BBStack.push_back(BBI.TrueBB);
822 continue;
823 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000824
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000825 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
826 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000827
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000828 if (TrueBBI.IsDone && FalseBBI.IsDone) {
829 BBI.IsBeingAnalyzed = false;
830 BBI.IsAnalyzed = true;
831 BBStack.pop_back();
832 continue;
833 }
834
835 SmallVector<MachineOperand, 4>
836 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
837 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
838
839 unsigned Dups = 0;
840 unsigned Dups2 = 0;
841 bool TNeedSub = !TrueBBI.Predicate.empty();
842 bool FNeedSub = !FalseBBI.Predicate.empty();
843 bool Enqueued = false;
844
845 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
846
847 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
848 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
849 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
850 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000851 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000852 Prediction) &&
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000853 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
854 FeasibilityAnalysis(FalseBBI, RevCond)) {
855 // Diamond:
856 // EBB
857 // / \_
858 // | |
859 // TBB FBB
860 // \ /
861 // TailBB
862 // Note TailBB can be empty.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000863 Tokens.push_back(llvm::make_unique<IfcvtToken>(
864 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000865 Enqueued = true;
866 }
867
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000868 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
869 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
870 TrueBBI.ExtraCost2, Prediction) &&
871 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
872 // Triangle:
873 // EBB
874 // | \_
875 // | |
876 // | TBB
877 // | /
878 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000879 Tokens.push_back(
880 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000881 Enqueued = true;
882 }
883
884 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
885 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
886 TrueBBI.ExtraCost2, Prediction) &&
887 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000888 Tokens.push_back(
889 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000890 Enqueued = true;
891 }
892
893 if (ValidSimple(TrueBBI, Dups, Prediction) &&
894 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
895 TrueBBI.ExtraCost2, Prediction) &&
896 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
897 // Simple (split, no rejoin):
898 // EBB
899 // | \_
900 // | |
901 // | TBB---> exit
902 // |
903 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +0000904 Tokens.push_back(
905 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000906 Enqueued = true;
907 }
908
909 if (CanRevCond) {
910 // Try the other path...
911 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
912 Prediction.getCompl()) &&
913 MeetIfcvtSizeLimit(*FalseBBI.BB,
914 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
915 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
916 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000917 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
918 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000919 Enqueued = true;
920 }
921
922 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
923 Prediction.getCompl()) &&
924 MeetIfcvtSizeLimit(*FalseBBI.BB,
925 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000926 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000927 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000928 Tokens.push_back(
929 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000930 Enqueued = true;
931 }
932
933 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
934 MeetIfcvtSizeLimit(*FalseBBI.BB,
935 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
936 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
937 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000938 Tokens.push_back(
939 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000940 Enqueued = true;
941 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000942 }
943
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000944 BBI.IsEnqueued = Enqueued;
945 BBI.IsBeingAnalyzed = false;
946 BBI.IsAnalyzed = true;
947 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +0000948 }
Evan Cheng2e82cef2007-05-18 18:14:37 +0000949}
950
Evan Cheng905a8f42007-05-30 19:49:19 +0000951/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000952/// candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000953void IfConverter::AnalyzeBlocks(
954 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000955 for (auto &BB : MF)
956 AnalyzeBlock(&BB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +0000957
Evan Cheng20e05992007-06-01 00:12:12 +0000958 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000959 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000960}
961
Evan Cheng288f1542007-06-08 22:01:07 +0000962/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
963/// that all the intervening blocks are empty (given BB can fall through to its
964/// next block).
965static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000966 MachineFunction::iterator PI = BB->getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000967 MachineFunction::iterator I = std::next(PI);
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000968 MachineFunction::iterator TI = ToBB->getIterator();
Evan Cheng2c1acd62007-06-05 07:05:25 +0000969 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000970 while (I != TI) {
971 // Check isSuccessor to avoid case where the next block is empty, but
972 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000973 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +0000974 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000975 PI = I++;
976 }
Evan Cheng312b7232007-06-04 06:47:22 +0000977 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000978}
979
Evan Cheng51eb2c32007-06-18 08:37:25 +0000980/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
981/// to determine if it can be if-converted. If predecessor is already enqueued,
982/// dequeue it!
983void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000984 for (const auto &Predecessor : BB->predecessors()) {
985 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000986 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000987 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000988 PBBI.IsAnalyzed = false;
989 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000990 }
991}
992
Evan Chengc2237ce2007-05-29 22:31:16 +0000993/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
994///
995static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
996 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000997 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000998 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000999 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001000}
1001
Evan Cheng288f1542007-06-08 22:01:07 +00001002/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1003/// successors.
1004void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001005 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001006 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001007 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1008 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001009}
1010
Matthias Braund616ccc2013-10-11 19:04:37 +00001011/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1012/// values defined in MI which are not live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001013static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +00001014 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001015 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001016
Pete Cooper7605e372015-05-05 20:14:22 +00001017 // Now add the implicit uses for each of the clobbered values.
1018 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001019 // FIXME: Const cast here is nasty, but better than making StepForward
1020 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +00001021 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1022 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001023 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001024 if (Op.isRegMask()) {
1025 // First handle regmasks. They clobber any entries in the mask which
1026 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +00001027 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +00001028
1029 // We also need to add an implicit def of this register for the later
1030 // use to read from.
1031 // For the register allocator to have allocated a register clobbered
1032 // by the call which is used later, it must be the case that
1033 // the call doesn't return.
1034 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1035 continue;
1036 }
1037 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001038 if (Op.isDead()) {
1039 // If we found a dead def, but it needs to be live, then remove the dead
1040 // flag.
1041 if (Redefs.contains(Op.getReg()))
1042 Op.setIsDead(false);
1043 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001044 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001045 }
1046}
1047
1048/**
1049 * Remove kill flags from operands with a registers in the @p DontKill set.
1050 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001051static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001052 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001053 if (!O->isReg() || !O->isKill())
1054 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001055 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001056 O->setIsKill(false);
1057 }
1058}
1059
1060/**
1061 * Walks a range of machine instructions and removes kill flags for registers
1062 * in the @p DontKill set.
1063 */
1064static void RemoveKills(MachineBasicBlock::iterator I,
1065 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001066 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001067 const MCRegisterInfo &MCRI) {
1068 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001069 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001070}
1071
Evan Cheng312b7232007-06-04 06:47:22 +00001072/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001073///
Evan Cheng3a51c852007-06-16 09:34:52 +00001074bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001075 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1076 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1077 BBInfo *CvtBBI = &TrueBBI;
1078 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001079
Owen Anderson4f6bf042008-08-14 22:49:33 +00001080 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001081 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001082 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001083
Evan Cheng51eb2c32007-06-18 08:37:25 +00001084 if (CvtBBI->IsDone ||
1085 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001086 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001087 BBI.IsAnalyzed = false;
1088 CvtBBI->IsAnalyzed = false;
1089 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001090 }
Evan Chengd0e66912007-05-23 07:23:16 +00001091
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001092 if (CvtBBI->BB->hasAddressTaken())
1093 // Conservatively abort if-conversion if BB's address is taken.
1094 return false;
1095
Evan Cheng3a51c852007-06-16 09:34:52 +00001096 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001097 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001098 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001099
Bob Wilson45814342010-06-19 05:33:57 +00001100 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001101 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001102 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001103 Redefs.addLiveIns(CvtBBI->BB);
1104 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001105
1106 // Compute a set of registers which must not be killed by instructions in
1107 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001108 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001109 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001110
Evan Cheng92fb5452007-06-15 07:36:12 +00001111 if (CvtBBI->BB->pred_size() > 1) {
1112 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001113 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001114 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001115 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001116
1117 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1118 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001119 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001120 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001121 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001122 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001123
Evan Cheng92fb5452007-06-15 07:36:12 +00001124 // Merge converted block into entry block.
1125 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1126 MergeBlocks(BBI, *CvtBBI);
1127 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001128
Evan Chenge4ec9182007-06-06 02:08:52 +00001129 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001130 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001131 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001132 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001133 // Now ifcvt'd block will look like this:
1134 // BB:
1135 // ...
1136 // t, f = cmp
1137 // if t op
1138 // b BBf
1139 //
1140 // We cannot further ifcvt this block because the unconditional branch
1141 // will have to be predicated on the new condition, that will not be
1142 // available if cmp executes.
1143 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001144 }
Evan Chenge26c0912007-05-21 22:22:58 +00001145
Evan Cheng288f1542007-06-08 22:01:07 +00001146 RemoveExtraEdges(BBI);
1147
Evan Chengd0e66912007-05-23 07:23:16 +00001148 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001149 if (!IterIfcvt)
1150 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001151 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001152 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001153
1154 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001155 return true;
1156}
1157
Evan Chengaf716102007-05-16 21:54:37 +00001158/// IfConvertTriangle - If convert a triangle sub-CFG.
1159///
Evan Cheng3a51c852007-06-16 09:34:52 +00001160bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001161 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001162 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1163 BBInfo *CvtBBI = &TrueBBI;
1164 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001165 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001166
Owen Anderson4f6bf042008-08-14 22:49:33 +00001167 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001168 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001169 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001170
Evan Cheng51eb2c32007-06-18 08:37:25 +00001171 if (CvtBBI->IsDone ||
1172 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001173 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001174 BBI.IsAnalyzed = false;
1175 CvtBBI->IsAnalyzed = false;
1176 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001177 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001178
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001179 if (CvtBBI->BB->hasAddressTaken())
1180 // Conservatively abort if-conversion if BB's address is taken.
1181 return false;
1182
Evan Cheng3a51c852007-06-16 09:34:52 +00001183 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001184 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001185 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001186
Evan Cheng3a51c852007-06-16 09:34:52 +00001187 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001188 if (ReverseBranchCondition(*CvtBBI)) {
1189 // BB has been changed, modify its predecessors (except for this
1190 // one) so they don't get ifcvt'ed based on bad intel.
1191 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1192 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1193 MachineBasicBlock *PBB = *PI;
1194 if (PBB == BBI.BB)
1195 continue;
1196 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1197 if (PBBI.IsEnqueued) {
1198 PBBI.IsAnalyzed = false;
1199 PBBI.IsEnqueued = false;
1200 }
Evan Chengadd97762007-06-14 23:34:09 +00001201 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001202 }
1203 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001204
Bob Wilson45814342010-06-19 05:33:57 +00001205 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001206 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001207 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001208 Redefs.addLiveIns(CvtBBI->BB);
1209 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001210
Andrew Trick276dd452013-10-14 20:45:17 +00001211 DontKill.clear();
1212
Craig Topperc0196b12014-04-14 00:51:57 +00001213 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001214 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001215
Manman Renb6819182014-01-29 23:18:47 +00001216 if (HasEarlyExit) {
Cong Houd97c1002015-12-01 05:29:22 +00001217 // Get probabilities before modifying CvtBBI->BB and BBI.BB.
1218 CvtNext = MBPI->getEdgeProbability(CvtBBI->BB, NextBBI->BB);
1219 CvtFalse = MBPI->getEdgeProbability(CvtBBI->BB, CvtBBI->FalseBB);
1220 BBNext = MBPI->getEdgeProbability(BBI.BB, NextBBI->BB);
1221 BBCvt = MBPI->getEdgeProbability(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001222 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001223
Bob Wilson1e5da552010-06-29 00:55:23 +00001224 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001225 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001226 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001227 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001228 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001229
1230 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1231 // explicitly remove CvtBBI as a successor.
Cong Houc1069892015-12-13 09:26:17 +00001232 BBI.BB->removeSuccessor(CvtBBI->BB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001233 } else {
1234 // Predicate the 'true' block after removing its branch.
1235 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001236 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001237
Evan Cheng0598b2d2007-06-18 22:44:57 +00001238 // Now merge the entry of the triangle with the true block.
1239 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001240 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001241 }
1242
Evan Cheng312b7232007-06-04 06:47:22 +00001243 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001244 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001245 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1246 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001247 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001248 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001249
Cong Houd97c1002015-12-01 05:29:22 +00001250 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
1251 // NewNext = New_Prob(BBI.BB, NextBBI->BB) =
1252 // Prob(BBI.BB, NextBBI->BB) +
1253 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, NextBBI->BB)
1254 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
1255 // Prob(BBI.BB, CvtBBI->BB) * Prob(CvtBBI->BB, CvtBBI->FalseBB)
1256 auto NewTrueBB = getNextBlock(BBI.BB);
1257 auto NewNext = BBNext + BBCvt * CvtNext;
1258 auto NewTrueBBIter =
1259 std::find(BBI.BB->succ_begin(), BBI.BB->succ_end(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001260 if (NewTrueBBIter != BBI.BB->succ_end())
1261 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001262
1263 auto NewFalse = BBCvt * CvtFalse;
1264 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1265 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001266 }
Evan Cheng7783f822007-06-08 09:36:04 +00001267
1268 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001269 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001270 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001271 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001272 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001273 if (!isFallThrough) {
1274 // Only merge them if the true block does not fallthrough to the false
1275 // block. By not merging them, we make it possible to iteratively
1276 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001277 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001278 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1279 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001280 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001281 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001282 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001283 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1284 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001285 }
Evan Cheng7783f822007-06-08 09:36:04 +00001286 // Mixed predicated and unpredicated code. This cannot be iteratively
1287 // predicated.
1288 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001289 }
Evan Chenge26c0912007-05-21 22:22:58 +00001290
Evan Cheng288f1542007-06-08 22:01:07 +00001291 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001292
Evan Chengd0e66912007-05-23 07:23:16 +00001293 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001294 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001295 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001296 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001297 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001298 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001299 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001300
1301 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001302 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001303}
1304
Evan Chengaf716102007-05-16 21:54:37 +00001305/// IfConvertDiamond - If convert a diamond sub-CFG.
1306///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001307bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1308 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001309 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001310 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001311 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001312 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001313 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001314 if (blockAlwaysFallThrough(TrueBBI))
1315 TailBB = FalseBBI.TrueBB;
1316 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001317 }
Evan Chenge26c0912007-05-21 22:22:58 +00001318
Evan Cheng51eb2c32007-06-18 08:37:25 +00001319 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1320 TrueBBI.BB->pred_size() > 1 ||
1321 FalseBBI.BB->pred_size() > 1) {
1322 // Something has changed. It's no longer safe to predicate these blocks.
1323 BBI.IsAnalyzed = false;
1324 TrueBBI.IsAnalyzed = false;
1325 FalseBBI.IsAnalyzed = false;
1326 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001327 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001328
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001329 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1330 // Conservatively abort if-conversion if either BB has its address taken.
1331 return false;
1332
Bob Wilson1e5da552010-06-29 00:55:23 +00001333 // Put the predicated instructions from the 'true' block before the
1334 // instructions from the 'false' block, unless the true block would clobber
1335 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001336 BBInfo *BBI1 = &TrueBBI;
1337 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001338 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001339 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001340 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001341 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1342 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001343
Evan Cheng3a51c852007-06-16 09:34:52 +00001344 // Figure out the more profitable ordering.
1345 bool DoSwap = false;
1346 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1347 DoSwap = true;
1348 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001349 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001350 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001351 }
1352 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001353 std::swap(BBI1, BBI2);
1354 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001355 }
Evan Cheng79484222007-06-05 23:46:14 +00001356
Evan Cheng51eb2c32007-06-18 08:37:25 +00001357 // Remove the conditional branch from entry to the blocks.
1358 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1359
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001360 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001361 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001362 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001363 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001364
Evan Cheng51eb2c32007-06-18 08:37:25 +00001365 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001366 // Skip dbg_value instructions
Benjamin Kramer6b568962015-06-23 14:47:29 +00001367 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1368 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001369 BBI1->NonPredSize -= NumDups1;
1370 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001371
1372 // Skip past the dups on each side separately since there may be
1373 // differing dbg_value entries.
1374 for (unsigned i = 0; i < NumDups1; ++DI1) {
1375 if (!DI1->isDebugValue())
1376 ++i;
1377 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001378 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001379 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001380 if (!DI2->isDebugValue())
1381 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001382 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001383
Matthias Braund616ccc2013-10-11 19:04:37 +00001384 // Compute a set of registers which must not be killed by instructions in BB1:
1385 // This is everything used+live in BB2 after the duplicated instructions. We
1386 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001387 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001388 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1389 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001390 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001391 }
1392
1393 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1394 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001395 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1396 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001397 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001398 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1399 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1400
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001401 // Remove branch from the 'true' block, unless it was not analyzable.
1402 // Non-analyzable branches need to be preserved, since in such cases,
1403 // the CFG structure is not an actual diamond (the join block may not
1404 // be present).
1405 if (BBI1->IsBrAnalyzable)
1406 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1407 // Remove duplicated instructions.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001408 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001409 for (unsigned i = 0; i != NumDups2; ) {
1410 // NumDups2 only counted non-dbg_value instructions, so this won't
1411 // run off the head of the list.
1412 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001413 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001414 // skip dbg_value instructions
1415 if (!DI1->isDebugValue())
1416 ++i;
1417 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001418 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001419
Matthias Braund616ccc2013-10-11 19:04:37 +00001420 // Kill flags in the true block for registers living into the false block
1421 // must be removed.
1422 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1423
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001424 // Remove 'false' block branch (unless it was not analyzable), and find
1425 // the last instruction to predicate.
1426 if (BBI2->IsBrAnalyzable)
1427 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001428 DI2 = BBI2->BB->end();
1429 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001430 // NumDups2 only counted non-dbg_value instructions, so this won't
1431 // run off the head of the list.
1432 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001433 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001434 // skip dbg_value instructions
1435 if (!DI2->isDebugValue())
1436 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001437 }
Evan Cheng4266a792011-12-19 22:01:30 +00001438
1439 // Remember which registers would later be defined by the false block.
1440 // This allows us not to predicate instructions in the true block that would
1441 // later be re-defined. That is, rather than
1442 // subeq r0, r1, #1
1443 // addne r0, r1, #1
1444 // generate:
1445 // sub r0, r1, #1
1446 // addne r0, r1, #1
1447 SmallSet<unsigned, 4> RedefsByFalse;
1448 SmallSet<unsigned, 4> ExtUses;
1449 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1450 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1451 if (FI->isDebugValue())
1452 continue;
1453 SmallVector<unsigned, 4> Defs;
1454 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1455 const MachineOperand &MO = FI->getOperand(i);
1456 if (!MO.isReg())
1457 continue;
1458 unsigned Reg = MO.getReg();
1459 if (!Reg)
1460 continue;
1461 if (MO.isDef()) {
1462 Defs.push_back(Reg);
1463 } else if (!RedefsByFalse.count(Reg)) {
1464 // These are defined before ctrl flow reach the 'false' instructions.
1465 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001466 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1467 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001468 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001469 }
1470 }
1471
1472 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1473 unsigned Reg = Defs[i];
1474 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001475 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1476 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001477 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001478 }
1479 }
1480 }
1481 }
1482
1483 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001484 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001485
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001486 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1487 // a non-predicated in BBI2, then we don't want to predicate the one from
1488 // BBI2. The reason is that if we merged these blocks, we would end up with
1489 // two predicated terminators in the same block.
1490 if (!BBI2->BB->empty() && (DI2 == BBI2->BB->end())) {
1491 MachineBasicBlock::iterator BBI1T = BBI1->BB->getFirstTerminator();
1492 MachineBasicBlock::iterator BBI2T = BBI2->BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001493 if (BBI1T != BBI1->BB->end() && TII->isPredicated(*BBI1T) &&
1494 BBI2T != BBI2->BB->end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001495 --DI2;
1496 }
1497
Evan Cheng4266a792011-12-19 22:01:30 +00001498 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001499 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001500
Evan Cheng0598b2d2007-06-18 22:44:57 +00001501 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001502 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1503 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001504
Bob Wilson2371f4f2009-05-13 23:25:24 +00001505 // If the if-converted block falls through or unconditionally branches into
1506 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001507 // fold the tail block in as well. Otherwise, unless it falls through to the
1508 // tail, add a unconditional branch to it.
1509 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001510 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001511 bool CanMergeTail = !TailBBI.HasFallThrough &&
1512 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001513 // The if-converted block can still have a predicated terminator
1514 // (e.g. a predicated return). If that is the case, we cannot merge
1515 // it with the tail block.
1516 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001517 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001518 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001519 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1520 // check if there are any other predecessors besides those.
1521 unsigned NumPreds = TailBB->pred_size();
1522 if (NumPreds > 1)
1523 CanMergeTail = false;
1524 else if (NumPreds == 1 && CanMergeTail) {
1525 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1526 if (*PI != BBI1->BB && *PI != BBI2->BB)
1527 CanMergeTail = false;
1528 }
1529 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001530 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001531 TailBBI.IsDone = true;
1532 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001533 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Evan Cheng0598b2d2007-06-18 22:44:57 +00001534 InsertUncondBranch(BBI.BB, TailBB, TII);
1535 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001536 }
Evan Chenge26c0912007-05-21 22:22:58 +00001537 }
1538
Bob Wilson1e5da552010-06-29 00:55:23 +00001539 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1540 // which can happen here if TailBB is unanalyzable and is merged, so
1541 // explicitly remove BBI1 and BBI2 as successors.
1542 BBI.BB->removeSuccessor(BBI1->BB);
Cong Houc1069892015-12-13 09:26:17 +00001543 BBI.BB->removeSuccessor(BBI2->BB, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001544 RemoveExtraEdges(BBI);
1545
Evan Cheng79484222007-06-05 23:46:14 +00001546 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001547 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001548 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001549
1550 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001551 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001552}
1553
Evan Cheng4266a792011-12-19 22:01:30 +00001554static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001555 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001556 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001557 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001558 return false;
1559
1560 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1561 const MachineOperand &MO = MI->getOperand(i);
1562 if (!MO.isReg())
1563 continue;
1564 unsigned Reg = MO.getReg();
1565 if (!Reg)
1566 continue;
1567 if (MO.isDef() && !LaterRedefs.count(Reg))
1568 return false;
1569 }
1570
1571 return true;
1572}
1573
Evan Cheng51eb2c32007-06-18 08:37:25 +00001574/// PredicateBlock - Predicate instructions from the start of the block to the
1575/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001576void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001577 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001578 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001579 SmallSet<unsigned, 4> *LaterRedefs) {
1580 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001581 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001582 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001583 if (I->isDebugValue() || TII->isPredicated(*I))
Evan Chengd0e66912007-05-23 07:23:16 +00001584 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001585 // It may be possible not to predicate an instruction if it's the 'true'
1586 // side of a diamond and the 'false' side may re-define the instruction's
1587 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001588 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001589 AnyUnpred = true;
1590 continue;
1591 }
1592 // If any instruction is predicated, then every instruction after it must
1593 // be predicated.
1594 MaySpec = false;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001595 if (!TII->PredicateInstruction(*I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001596#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001597 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001598#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001599 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001600 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001601
Bob Wilson45814342010-06-19 05:33:57 +00001602 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001603 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001604 UpdatePredRedefs(*I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001605 }
Evan Chengd0e66912007-05-23 07:23:16 +00001606
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001607 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001608
Evan Cheng92fb5452007-06-15 07:36:12 +00001609 BBI.IsAnalyzed = false;
1610 BBI.NonPredSize = 0;
1611
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001612 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001613 if (AnyUnpred)
1614 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001615}
1616
Evan Cheng92fb5452007-06-15 07:36:12 +00001617/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1618/// the destination block. Skip end of block branches if IgnoreBr is true.
1619void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001620 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001621 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001622 MachineFunction &MF = *ToBBI.BB->getParent();
1623
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001624 for (auto &I : *FromBBI.BB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001625 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001626 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001627 break;
1628
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001629 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001630 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001631 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001632 unsigned ExtraPredCost = TII->getPredicationCost(I);
1633 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001634 if (NumCycles > 1)
1635 ToBBI.ExtraCost += NumCycles-1;
1636 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001637
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001638 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001639 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001640#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001641 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001642#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001643 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001644 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001645 }
1646
Bob Wilson45814342010-06-19 05:33:57 +00001647 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001648 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001649 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001650
1651 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001652 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001653 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001654 }
1655
Bob Wilson1e5da552010-06-29 00:55:23 +00001656 if (!IgnoreBr) {
1657 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1658 FromBBI.BB->succ_end());
1659 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001660 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001661
Bob Wilson1e5da552010-06-29 00:55:23 +00001662 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1663 MachineBasicBlock *Succ = Succs[i];
1664 // Fallthrough edge can't be transferred.
1665 if (Succ == FallThrough)
1666 continue;
1667 ToBBI.BB->addSuccessor(Succ);
1668 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001669 }
1670
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001671 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1672 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001673
1674 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1675 ToBBI.IsAnalyzed = false;
1676
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001677 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001678}
1679
Evan Cheng0f745da2007-05-18 00:20:58 +00001680/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001681/// This will leave FromBB as an empty block, so remove all of its
1682/// successor edges except for the fall-through edge. If AddEdges is true,
1683/// i.e., when FromBBI's branch is being moved, add those successor edges to
1684/// ToBBI.
1685void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001686 assert(!FromBBI.BB->hasAddressTaken() &&
1687 "Removing a BB whose address is taken!");
1688
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001689 // In case FromBBI.BB contains terminators (e.g. return instruction),
1690 // first move the non-terminator instructions, then the terminators.
1691 MachineBasicBlock::iterator FromTI = FromBBI.BB->getFirstTerminator();
1692 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
1693 ToBBI.BB->splice(ToTI, FromBBI.BB, FromBBI.BB->begin(), FromTI);
1694
1695 // If FromBB has non-predicated terminator we should copy it at the end.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001696 if (FromTI != FromBBI.BB->end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001697 ToTI = ToBBI.BB->end();
1698 ToBBI.BB->splice(ToTI, FromBBI.BB, FromTI, FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001699
Cong Houb9e8d482015-12-17 01:29:08 +00001700 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1701 // unknown probabilities into known ones.
1702 // FIXME: This usage is too tricky and in the future we would like to
1703 // eliminate all unknown probabilities in MBB.
1704 ToBBI.BB->normalizeSuccProbs();
1705
Cong Houd40105d2015-09-18 20:22:41 +00001706 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromBBI.BB->succ_begin(),
1707 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001708 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001709 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001710 // The edge probability from ToBBI.BB to FromBBI.BB, which is only needed when
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001711 // AddEdges is true and FromBBI.BB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001712 auto To2FromProb = BranchProbability::getZero();
Cong Houfa1917c2015-12-01 00:02:51 +00001713 if (AddEdges && ToBBI.BB->isSuccessor(FromBBI.BB)) {
Cong Houd97c1002015-12-01 05:29:22 +00001714 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, FromBBI.BB);
1715 // Set the edge probability from ToBBI.BB to FromBBI.BB to zero to avoid the
1716 // edge probability being merged to other edges when this edge is removed
1717 // later.
1718 ToBBI.BB->setSuccProbability(
1719 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), FromBBI.BB),
1720 BranchProbability::getZero());
1721 }
1722
Cong Houd40105d2015-09-18 20:22:41 +00001723 for (unsigned i = 0, e = FromSuccs.size(); i != e; ++i) {
1724 MachineBasicBlock *Succ = FromSuccs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001725 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001726 if (Succ == FallThrough)
1727 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001728
Cong Houd97c1002015-12-01 05:29:22 +00001729 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001730 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001731 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
1732 // which is a portion of the edge probability from FromBBI.BB to Succ. The
1733 // portion ratio is the edge probability from ToBBI.BB to FromBBI.BB (if
1734 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
1735 NewProb = MBPI->getEdgeProbability(FromBBI.BB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001736
Cong Houd97c1002015-12-01 05:29:22 +00001737 // To2FromProb is 0 when FromBBI.BB is not a successor of ToBBI.BB. This
Cong Houd40105d2015-09-18 20:22:41 +00001738 // only happens when if-converting a diamond CFG and FromBBI.BB is the
1739 // tail BB. In this case FromBBI.BB post-dominates ToBBI.BB and hence we
Cong Houd97c1002015-12-01 05:29:22 +00001740 // could just use the probabilities on FromBBI.BB's out-edges when adding
1741 // new successors.
1742 if (!To2FromProb.isZero())
1743 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001744 }
1745
Evan Chengbe9859e2007-06-07 02:12:15 +00001746 FromBBI.BB->removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001747
1748 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001749 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001750 // probability of this edge by adding NewProb to it. An example is shown
Cong Houd97c1002015-12-01 05:29:22 +00001751 // below, in which A is ToBBI.BB and B is FromBBI.BB. In this case we
1752 // don't have to set C as A's successor as it already is. We only need to
1753 // update the edge probability on A->C. Note that B will not be
1754 // immediately removed from A's successors. It is possible that B->D is
1755 // not removed either if D is a fallthrough of B. Later the edge A->D
1756 // (generated here) and B->D will be combined into one edge. To maintain
1757 // correct edge probability of this combined edge, we need to set the edge
1758 // probability of A->B to zero, which is already done above. The edge
1759 // probability on A->D is calculated by scaling the original probability
1760 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001761 //
1762 // Before ifcvt: After ifcvt (assume B->D is kept):
1763 //
1764 // A A
1765 // /| /|\
1766 // / B / B|
1767 // | /| | ||
1768 // |/ | | |/
1769 // C D C D
1770 //
1771 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001772 ToBBI.BB->setSuccProbability(
Cong Houd40105d2015-09-18 20:22:41 +00001773 std::find(ToBBI.BB->succ_begin(), ToBBI.BB->succ_end(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001774 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001775 else
Cong Houd97c1002015-12-01 05:29:22 +00001776 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001777 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001778 }
1779
Bob Wilson2371f4f2009-05-13 23:25:24 +00001780 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001781 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001782 FromBBI.BB->addSuccessor(NBB);
1783
Cong Houc1069892015-12-13 09:26:17 +00001784 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1785 // we've done above.
1786 ToBBI.BB->normalizeSuccProbs();
1787
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001788 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001789 FromBBI.Predicate.clear();
1790
Evan Chengd0e66912007-05-23 07:23:16 +00001791 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001792 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001793 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001794 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001795 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001796 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001797
Evan Cheng4dd31a72007-06-11 22:26:22 +00001798 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001799 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001800 ToBBI.IsAnalyzed = false;
1801 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001802}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001803
1804FunctionPass *
1805llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1806 return new IfConverter(Ftor);
1807}