blob: 6a7fd67ca145638570dab7ab4997263a60d08fa3 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Chengf5e53a52007-05-16 02:00:57 +000015#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "BranchFolding.h"
17#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000018#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000022#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000028#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000029#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000036#include "llvm/Target/TargetSubtargetInfo.h"
Cong Houd97c1002015-12-01 05:29:22 +000037#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000039
Evan Chengf5e53a52007-05-16 02:00:57 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "ifcvt"
43
Chris Lattner769c86b2008-01-07 05:40:58 +000044// Hidden options for help debugging.
45static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
46static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
47static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000055 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000056static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000058static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000059 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000060static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000061 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000062static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
63 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000064
Evan Cheng2117d1f2007-06-09 01:03:43 +000065STATISTIC(NumSimple, "Number of simple if-conversions performed");
66STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
67STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000068STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000069STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
70STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
71STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
72STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000073STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000074STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000075
76namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000077 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000078 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000079 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000080 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000081 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
82 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000083 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000084 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000085 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Buttce0196d2016-08-19 18:17:04 +000086 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000087 };
88
Matthias Braun2c931792016-08-17 02:51:57 +000089 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +000090 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +000091 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000092 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000093 /// diamond shape), its size, whether it's predicable, and whether any
94 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000095 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000096 /// IsDone - True if BB is not to be considered for ifcvt.
97 /// IsBeingAnalyzed - True if BB is currently being analyzed.
98 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
99 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000100 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// HasFallThrough - True if BB may fallthrough to the following BB.
102 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000103 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000104 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000105 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000106 /// ExtraCost - Extra cost for multi-cycle instructions.
107 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000108 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000109 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000110 /// BrCond - Conditions for end of block conditional branches.
111 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000112 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000113 bool IsDone : 1;
114 bool IsBeingAnalyzed : 1;
115 bool IsAnalyzed : 1;
116 bool IsEnqueued : 1;
117 bool IsBrAnalyzable : 1;
118 bool HasFallThrough : 1;
119 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000120 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000121 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000122 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000123 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000124 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000125 MachineBasicBlock *BB;
126 MachineBasicBlock *TrueBB;
127 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000128 SmallVector<MachineOperand, 4> BrCond;
129 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000130 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000131 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Buttce0196d2016-08-19 18:17:04 +0000132 HasFallThrough(false), IsUnpredicable(false),
133 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
134 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
Craig Topperc0196b12014-04-14 00:51:57 +0000135 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000136 };
137
Matthias Braun2c931792016-08-17 02:51:57 +0000138 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000139 /// BBI - Corresponding BBInfo.
140 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000141 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000142 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000143 /// NumDups - Number of instructions that would be duplicated due
144 /// to this if-conversion. (For diamonds, the number of
145 /// identical instructions at the beginnings of both
146 /// paths).
147 /// NumDups2 - For diamonds, the number of identical instructions
148 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000149 struct IfcvtToken {
150 BBInfo &BBI;
151 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000152 unsigned NumDups;
153 unsigned NumDups2;
Kyle Butt6262ca32016-08-24 21:34:24 +0000154 bool NeedSubsumption : 1;
155 bool TClobbersPred : 1;
156 bool FClobbersPred : 1;
157 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
158 bool tc = false, bool fc = false)
159 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
160 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000161 };
162
Matthias Braun2c931792016-08-17 02:51:57 +0000163 /// Results of if-conversion feasibility analysis indexed by basic block
164 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000165 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000166 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000167
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000168 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000169 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000170 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000171 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000172 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000173
Juergen Ributzka310034e2013-12-14 06:52:56 +0000174 LivePhysRegs Redefs;
175 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000176
Evan Chengc5adcca2012-06-08 21:53:50 +0000177 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000178 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000179 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000180 std::function<bool(const Function &)> PredicateFtor;
181
Evan Chengf5e53a52007-05-16 02:00:57 +0000182 public:
183 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000184 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000185 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000186 initializeIfConverterPass(*PassRegistry::getPassRegistry());
187 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000188
Craig Topper4584cd52014-03-07 09:26:03 +0000189 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000190 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000191 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000192 MachineFunctionPass::getAnalysisUsage(AU);
193 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000194
Craig Topper4584cd52014-03-07 09:26:03 +0000195 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000196
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000197 MachineFunctionProperties getRequiredProperties() const override {
198 return MachineFunctionProperties().set(
199 MachineFunctionProperties::Property::AllVRegsAllocated);
200 }
201
Evan Chengf5e53a52007-05-16 02:00:57 +0000202 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000203 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000204 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000205 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000206 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000207 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000208 BranchProbability Prediction) const;
Kyle Butt6262ca32016-08-24 21:34:24 +0000209 bool CountDuplicatedInstructions(
210 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
211 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
212 unsigned &Dups1, unsigned &Dups2,
213 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
214 bool SkipUnconditionalBranches) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000215 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt6262ca32016-08-24 21:34:24 +0000216 unsigned &Dups1, unsigned &Dups2,
217 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000218 void AnalyzeBranches(BBInfo &BBI);
219 void ScanInstructions(BBInfo &BBI,
220 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000221 MachineBasicBlock::iterator &End,
222 bool BranchUnpredicable = false) const;
223 bool RescanInstructions(
224 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
225 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
226 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000227 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000228 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000229 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt6262ca32016-08-24 21:34:24 +0000230 bool isTriangle = false, bool RevBranch = false,
231 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000232 void AnalyzeBlocks(MachineFunction &MF,
233 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000234 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng288f1542007-06-08 22:01:07 +0000235 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000236 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
237 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000238 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +0000239 unsigned NumDups1, unsigned NumDups2,
240 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000241 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000242 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000243 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000244 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000245 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000246 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000247 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000248 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000249
Evan Chengdebf9c52010-11-03 00:45:17 +0000250 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
251 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000252 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000253 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000254 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000255 }
256
Evan Chengdebf9c52010-11-03 00:45:17 +0000257 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
258 unsigned TCycle, unsigned TExtra,
259 MachineBasicBlock &FBB,
260 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000261 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000262 return TCycle > 0 && FCycle > 0 &&
263 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000264 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000265 }
266
Matthias Braun2c931792016-08-17 02:51:57 +0000267 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000268 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000269 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000270 }
271
Matthias Braun2c931792016-08-17 02:51:57 +0000272 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000273 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
274 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000275 int Incr1 = (C1->Kind == ICDiamond)
276 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
277 int Incr2 = (C2->Kind == ICDiamond)
278 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
279 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000280 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000281 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000282 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000283 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000284 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000285 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000286 // Favors diamond over triangle, etc.
287 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
288 return true;
289 else if (C1->Kind == C2->Kind)
290 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
291 }
292 }
293 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000294 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000295 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000296
Evan Chengf5e53a52007-05-16 02:00:57 +0000297 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000298}
Evan Chengf5e53a52007-05-16 02:00:57 +0000299
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000300char &llvm::IfConverterID = IfConverter::ID;
301
Owen Anderson8ac477f2010-10-12 19:48:12 +0000302INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000303INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000304INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000305
Evan Chengf5e53a52007-05-16 02:00:57 +0000306bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000307 if (skipFunction(*MF.getFunction()) ||
308 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000309 return false;
310
Eric Christopher3d4276f2015-01-27 07:31:29 +0000311 const TargetSubtargetInfo &ST = MF.getSubtarget();
312 TLI = ST.getTargetLowering();
313 TII = ST.getInstrInfo();
314 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000315 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000316 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000317 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000318 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000319
Evan Chengf5e53a52007-05-16 02:00:57 +0000320 if (!TII) return false;
321
Evan Chengc5adcca2012-06-08 21:53:50 +0000322 PreRegAlloc = MRI->isSSA();
323
324 bool BFChange = false;
325 if (!PreRegAlloc) {
326 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000327 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000328 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000329 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000330 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000331
David Greene72e47cd2010-01-04 22:02:01 +0000332 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000333 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000334
335 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000336 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000337 return false;
338 }
David Greene72e47cd2010-01-04 22:02:01 +0000339 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000340
Evan Chengf5e53a52007-05-16 02:00:57 +0000341 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000342 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000343
Justin Lebar3a7bc572016-02-22 17:51:28 +0000344 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000345 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000346 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
347 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
348 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000349 // Do an initial analysis for each basic block and find all the potential
350 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000351 bool Change = false;
352 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000353 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000354 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000355 Tokens.pop_back();
356 BBInfo &BBI = Token->BBI;
357 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000358 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000359 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000360
Evan Cheng4dd31a72007-06-11 22:26:22 +0000361 // If the block has been evicted out of the queue or it has already been
362 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000363 if (BBI.IsDone)
364 BBI.IsEnqueued = false;
365 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000366 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000367
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000368 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000369
Evan Cheng312b7232007-06-04 06:47:22 +0000370 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000371 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000372 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000373 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000374 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000375 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000376 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000377 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
378 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000379 << "): BB#" << BBI.BB->getNumber() << " ("
380 << ((Kind == ICSimpleFalse)
381 ? BBI.FalseBB->getNumber()
382 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000383 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000384 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000385 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000386 if (isFalse) ++NumSimpleFalse;
387 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000388 }
Evan Cheng312b7232007-06-04 06:47:22 +0000389 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000390 }
Evan Chengd0e66912007-05-23 07:23:16 +0000391 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000392 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000393 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000394 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000395 bool isFalse = Kind == ICTriangleFalse;
396 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000397 if (DisableTriangle && !isFalse && !isRev) break;
398 if (DisableTriangleR && !isFalse && isRev) break;
399 if (DisableTriangleF && isFalse && !isRev) break;
400 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000401 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000402 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000403 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000404 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000405 DEBUG(dbgs() << " rev");
406 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000407 << BBI.TrueBB->getNumber() << ",F:"
408 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000409 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000410 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000411 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000412 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000413 if (isRev) ++NumTriangleFRev;
414 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000415 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000416 if (isRev) ++NumTriangleRev;
417 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000418 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000419 }
Evan Chengd0e66912007-05-23 07:23:16 +0000420 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000421 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000422 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000423 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000424 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000425 << BBI.TrueBB->getNumber() << ",F:"
426 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000427 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
428 Token->TClobbersPred,
429 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000430 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000431 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000432 break;
433 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000434 }
435
Evan Cheng312b7232007-06-04 06:47:22 +0000436 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000437
Evan Cheng92fb5452007-06-15 07:36:12 +0000438 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
439 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
440 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000441 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000442 }
Evan Chengd0e66912007-05-23 07:23:16 +0000443
Evan Chengd0e66912007-05-23 07:23:16 +0000444 if (!Change)
445 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000446 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000447 }
Evan Cheng478b8052007-05-18 01:55:58 +0000448
Evan Cheng3a51c852007-06-16 09:34:52 +0000449 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000450 BBAnalysis.clear();
451
Evan Chengcf9e8a92010-06-18 22:17:13 +0000452 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000453 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000454 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000455 getAnalysisIfAvailable<MachineModuleInfo>());
456 }
457
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000458 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000459 return MadeChange;
460}
461
Matthias Braun2c931792016-08-17 02:51:57 +0000462/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000463static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000464 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000465 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000466 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000467 return SuccBB;
468 }
Craig Topperc0196b12014-04-14 00:51:57 +0000469 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000470}
471
Matthias Braun2c931792016-08-17 02:51:57 +0000472/// Reverse the condition of the end of the block branch. Swap block's 'true'
473/// and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000474bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000475 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000476 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
477 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000478 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000479 std::swap(BBI.TrueBB, BBI.FalseBB);
480 return true;
481 }
482 return false;
483}
484
Matthias Braun2c931792016-08-17 02:51:57 +0000485/// Returns the next block in the function blocks ordering. If it is the end,
486/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000487static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
488 MachineFunction::iterator I = MBB.getIterator();
489 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000490 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000491 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000492 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000493}
494
Matthias Braun2c931792016-08-17 02:51:57 +0000495/// Returns true if the 'true' block (along with its predecessor) forms a valid
496/// simple shape for ifcvt. It also returns the number of instructions that the
497/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000498bool IfConverter::ValidSimple(BBInfo &TrueBBI, 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 Chenga955c022007-06-19 21:45:13 +0000504 if (TrueBBI.IsBrAnalyzable)
505 return false;
506
Evan Cheng23402fc2007-06-15 21:18:05 +0000507 if (TrueBBI.BB->pred_size() > 1) {
508 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000509 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000510 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000511 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000512 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000513 }
514
Evan Chenga955c022007-06-19 21:45:13 +0000515 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000516}
517
Matthias Braun2c931792016-08-17 02:51:57 +0000518/// Returns true if the 'true' and 'false' blocks (along with their common
519/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
520/// true, it checks if 'true' block's false branch branches to the 'false' block
521/// rather than the other way around. It also returns the number of instructions
522/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000523bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000524 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000525 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000526 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000527 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000528 return false;
529
Evan Cheng23402fc2007-06-15 21:18:05 +0000530 if (TrueBBI.BB->pred_size() > 1) {
531 if (TrueBBI.CannotBeCopied)
532 return false;
533
Evan Cheng92fb5452007-06-15 07:36:12 +0000534 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000535 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000536 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000537 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000538 --Size;
539 else {
540 MachineBasicBlock *FExit = FalseBranch
541 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
542 if (FExit)
543 // Require a conditional branch
544 ++Size;
545 }
546 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000547 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000548 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000549 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000550 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000551
Evan Cheng7783f822007-06-08 09:36:04 +0000552 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
553 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000554 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000555 if (++I == TrueBBI.BB->getParent()->end())
556 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000557 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000558 }
Evan Cheng7783f822007-06-08 09:36:04 +0000559 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000560}
561
Matthias Braun2c931792016-08-17 02:51:57 +0000562/// Increment \p It until it points to a non-debug instruction or to \p End.
Kyle Buttfe916822016-08-06 01:52:31 +0000563/// @param It Iterator to increment
564/// @param End Iterator that points to end. Will be compared to It
565/// @returns true if It == End, false otherwise.
566static inline bool skipDebugInstructionsForward(
567 MachineBasicBlock::iterator &It,
568 MachineBasicBlock::iterator &End) {
569 while (It != End && It->isDebugValue())
570 It++;
571 return It == End;
572}
573
Kyle Buttd76755e2016-08-18 22:09:23 +0000574/// Shrink the provided inclusive range by one instruction.
575/// If the range was one instruction (\p It == \p Begin), It is not modified,
576/// but \p Empty is set to true.
577static inline void shrinkInclusiveRange(
578 MachineBasicBlock::iterator &Begin,
579 MachineBasicBlock::iterator &It,
580 bool &Empty) {
581 if (It == Begin)
582 Empty = true;
583 else
584 It--;
585}
586
587/// Decrement \p It until it points to a non-debug instruction or the range is
588/// empty.
Kyle Buttfe916822016-08-06 01:52:31 +0000589/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000590/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttd76755e2016-08-18 22:09:23 +0000591/// @param Empty Set to true if the resulting range is Empty
592/// @returns the value of Empty as a convenience.
Kyle Buttfe916822016-08-06 01:52:31 +0000593static inline bool skipDebugInstructionsBackward(
Kyle Buttd76755e2016-08-18 22:09:23 +0000594 MachineBasicBlock::iterator &Begin,
Kyle Buttfe916822016-08-06 01:52:31 +0000595 MachineBasicBlock::iterator &It,
Kyle Buttd76755e2016-08-18 22:09:23 +0000596 bool &Empty) {
597 while (!Empty && It->isDebugValue())
598 shrinkInclusiveRange(Begin, It, Empty);
599 return Empty;
Kyle Buttfe916822016-08-06 01:52:31 +0000600}
601
Kyle Butt4f0e2872016-08-06 01:52:33 +0000602/// Count duplicated instructions and move the iterators to show where they
603/// are.
604/// @param TIB True Iterator Begin
605/// @param FIB False Iterator Begin
606/// These two iterators initially point to the first instruction of the two
607/// blocks, and finally point to the first non-shared instruction.
608/// @param TIE True Iterator End
609/// @param FIE False Iterator End
610/// These two iterators initially point to End() for the two blocks() and
611/// finally point to the first shared instruction in the tail.
612/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
613/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000614/// @param Dups1 count of duplicated instructions at the beginning of the 2
615/// blocks.
616/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
617/// @param SkipUnconditionalBranches if true, Don't make sure that
618/// unconditional branches at the end of the blocks are the same. True is
619/// passed when the blocks are analyzable to allow for fallthrough to be
620/// handled.
621/// @return false if the shared portion prevents if conversion.
622bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000623 MachineBasicBlock::iterator &TIB,
624 MachineBasicBlock::iterator &FIB,
625 MachineBasicBlock::iterator &TIE,
626 MachineBasicBlock::iterator &FIE,
627 unsigned &Dups1, unsigned &Dups2,
628 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000629 bool SkipUnconditionalBranches) const {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000630
Bob Wilsone1961fe2010-10-26 00:02:24 +0000631 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000632 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000633 if(skipDebugInstructionsForward(TIB, TIE))
634 break;
635 if(skipDebugInstructionsForward(FIB, FIE))
636 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000637 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000638 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000639 // A pred-clobbering instruction in the shared portion prevents
640 // if-conversion.
641 std::vector<MachineOperand> PredDefs;
642 if (TII->DefinesPredicate(*TIB, PredDefs))
643 return false;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000644 ++Dups1;
645 ++TIB;
646 ++FIB;
647 }
648
Kyle Buttce0196d2016-08-19 18:17:04 +0000649 // If both blocks are returning don't skip the branches, since they will
650 // likely be both identical return instructions. In such cases the return
651 // can be left unpredicated.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000652 // Check for already containing all of the block.
653 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000654 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000655 // Now, in preparation for counting duplicate instructions at the ends of the
656 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000657 --TIE;
658 --FIE;
Kyle Buttd76755e2016-08-18 22:09:23 +0000659
660 // After this point TIB and TIE define an inclusive range, which means that
661 // TIB == TIE is true when there is one more instruction to consider, not at
662 // the end. Because we may not be able to go before TIB, we need a flag to
663 // indicate a completely empty range.
664 bool TEmpty = false, FEmpty = false;
665
666 // Upon exit TIE and FIE will both point at the last non-shared instruction.
667 // They need to be moved forward to point past the last non-shared
668 // instruction if the range they delimit is non-empty.
669 auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
670 if (!TEmpty)
671 ++TIE;
672 if (!FEmpty)
673 ++FIE;
674 });
675
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000676 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000677 if (SkipUnconditionalBranches) {
Kyle Buttd76755e2016-08-18 22:09:23 +0000678 while (!TEmpty && TIE->isUnconditionalBranch())
679 shrinkInclusiveRange(TIB, TIE, TEmpty);
680 while (!FEmpty && FIE->isUnconditionalBranch())
681 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000682 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000683 }
684
685 // If Dups1 includes all of a block, then don't count duplicate
686 // instructions at the end of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000687 if (TEmpty || FEmpty)
Kyle Butt6262ca32016-08-24 21:34:24 +0000688 return true;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000689
690 // Count duplicate instructions at the ends of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000691 while (!TEmpty && !FEmpty) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000692 // Skip dbg_value instructions. These do not count.
Kyle Buttd76755e2016-08-18 22:09:23 +0000693 if (skipDebugInstructionsBackward(TIB, TIE, TEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000694 break;
Kyle Buttd76755e2016-08-18 22:09:23 +0000695 if (skipDebugInstructionsBackward(FIB, FIE, FEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000696 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000697 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000698 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000699 // We have to verify that any branch instructions are the same, and then we
700 // don't count them toward the # of duplicate instructions.
701 if (!TIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000702 ++Dups2;
Kyle Buttd76755e2016-08-18 22:09:23 +0000703 shrinkInclusiveRange(TIB, TIE, TEmpty);
704 shrinkInclusiveRange(FIB, FIE, FEmpty);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000705 }
Kyle Butt6262ca32016-08-24 21:34:24 +0000706 return true;
707}
708
709/// RescanInstructions - Run ScanInstructions on a pair of blocks.
710/// @param TIB - True Iterator Begin, points to first non-shared instruction
711/// @param FIB - False Iterator Begin, points to first non-shared instruction
712/// @param TIE - True Iterator End, points past last non-shared instruction
713/// @param FIE - False Iterator End, points past last non-shared instruction
714/// @param TrueBBI - BBInfo to update for the true block.
715/// @param FalseBBI - BBInfo to update for the false block.
716/// @returns - false if either block cannot be predicated or if both blocks end
717/// with a predicate-clobbering instruction.
718bool IfConverter::RescanInstructions(
719 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
720 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
721 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
722 bool BranchUnpredicable = true;
723 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
724 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
725 if (TrueBBI.IsUnpredicable)
726 return false;
727 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
728 if (FalseBBI.IsUnpredicable)
729 return false;
730 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
731 return false;
732 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000733}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000734
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000735/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
736/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000737bool IfConverter::ValidDiamond(
738 BBInfo &TrueBBI, BBInfo &FalseBBI,
739 unsigned &Dups1, unsigned &Dups2,
740 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000741 Dups1 = Dups2 = 0;
742 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
743 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
744 return false;
745
746 MachineBasicBlock *TT = TrueBBI.TrueBB;
747 MachineBasicBlock *FT = FalseBBI.TrueBB;
748
749 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000750 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000751 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000752 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000753 if (TT != FT)
754 return false;
755 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
756 return false;
757 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
758 return false;
759
760 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000761 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000762 return false;
763
764 // Count duplicate instructions at the beginning and end of the true and
765 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000766 // Skip unconditional branches only if we are considering an analyzable
767 // diamond. Otherwise the branches must be the same.
768 bool SkipUnconditionalBranches =
769 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000770 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
771 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
772 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
773 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000774 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
775 *TrueBBI.BB, *FalseBBI.BB,
776 SkipUnconditionalBranches))
777 return false;
778
779 TrueBBICalc.BB = TrueBBI.BB;
780 FalseBBICalc.BB = FalseBBI.BB;
781 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
782 return false;
783 // The size is used to decide whether to if-convert, and the shared portions
784 // are subtracted off. Because of the subtraction, we just use the size that
785 // was calculated by the original ScanInstructions, as it is correct.
786 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
787 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000788 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000789}
790
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000791/// AnalyzeBranches - Look at the branches at the end of a block to determine if
792/// the block is predicable.
793void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000794 if (BBI.IsDone)
795 return;
796
Craig Topperc0196b12014-04-14 00:51:57 +0000797 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000798 BBI.BrCond.clear();
799 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000800 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000801 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000802
803 if (BBI.BrCond.size()) {
804 // No false branch. This BB must end with a conditional branch and a
805 // fallthrough.
806 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000807 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000808 if (!BBI.FalseBB) {
809 // Malformed bcc? True and false blocks are the same?
810 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000811 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000812 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000813}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000814
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000815/// ScanInstructions - Scan all the instructions in the block to determine if
816/// the block is predicable. In most cases, that means all the instructions
817/// in the block are isPredicable(). Also checks if the block contains any
818/// instruction which can clobber a predicate (e.g. condition code register).
819/// If so, the block is not predicable unless it's the last instruction.
820void IfConverter::ScanInstructions(BBInfo &BBI,
821 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000822 MachineBasicBlock::iterator &End,
823 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000824 if (BBI.IsDone || BBI.IsUnpredicable)
825 return;
826
827 bool AlreadyPredicated = !BBI.Predicate.empty();
828
Evan Cheng4dd31a72007-06-11 22:26:22 +0000829 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000830 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000831 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000832 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000833 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000834 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000835 continue;
836
Justin Lebar7dba2e02016-04-15 01:38:41 +0000837 // It's unsafe to duplicate convergent instructions in this context, so set
838 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
839 // following CFG, which is subject to our "simple" transformation.
840 //
841 // BB0 // if (c1) goto BB1; else goto BB2;
842 // / \
843 // BB1 |
844 // | BB2 // if (c2) goto TBB; else goto FBB;
845 // | / |
846 // | / |
847 // TBB |
848 // | |
849 // | FBB
850 // |
851 // exit
852 //
853 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
854 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
855 // TBB contains a convergent instruction. This is safe iff doing so does
856 // not add a control-flow dependency to the convergent instruction -- i.e.,
857 // it's safe iff the set of control flows that leads us to the convergent
858 // instruction does not get smaller after the transformation.
859 //
860 // Originally we executed TBB if c1 || c2. After the transformation, there
861 // are two copies of TBB's instructions. We get to the first if c1, and we
862 // get to the second if !c1 && c2.
863 //
864 // There are clearly fewer ways to satisfy the condition "c1" than
865 // "c1 || c2". Since we've shrunk the set of control flows which lead to
866 // our convergent instruction, the transformation is unsafe.
867 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000868 BBI.CannotBeCopied = true;
869
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000870 bool isPredicated = TII->isPredicated(MI);
871 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000872
Kyle Butt6262ca32016-08-24 21:34:24 +0000873 if (BranchUnpredicable && MI.isBranch()) {
874 BBI.IsUnpredicable = true;
875 return;
876 }
877
Joey Goulya5153cb2013-09-09 14:21:49 +0000878 // A conditional branch is not predicable, but it may be eliminated.
879 if (isCondBr)
880 continue;
881
882 if (!isPredicated) {
883 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000884 unsigned ExtraPredCost = TII->getPredicationCost(MI);
885 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000886 if (NumCycles > 1)
887 BBI.ExtraCost += NumCycles-1;
888 BBI.ExtraCost2 += ExtraPredCost;
889 } else if (!AlreadyPredicated) {
890 // FIXME: This instruction is already predicated before the
891 // if-conversion pass. It's probably something like a conditional move.
892 // Mark this block unpredicable for now.
893 BBI.IsUnpredicable = true;
894 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000895 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000896
897 if (BBI.ClobbersPred && !isPredicated) {
898 // Predicate modification instruction should end the block (except for
899 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000900 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000901 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000902 BBI.IsUnpredicable = true;
903 return;
904 }
905
Evan Chengfbc73092007-07-10 17:50:43 +0000906 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
907 // still potentially predicable.
908 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000909 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000910 BBI.ClobbersPred = true;
911
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000912 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000913 BBI.IsUnpredicable = true;
914 return;
915 }
916 }
917}
918
Matthias Braun2c931792016-08-17 02:51:57 +0000919/// Determine if the block is a suitable candidate to be predicated by the
920/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +0000921/// @param BBI BBInfo for the block to check
922/// @param Pred Predicate array for the branch that leads to BBI
923/// @param isTriangle true if the Analysis is for a triangle
924/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
925/// case
926/// @param hasCommonTail true if BBI shares a tail with a sibling block that
927/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000928bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000929 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +0000930 bool isTriangle, bool RevBranch,
931 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000932 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +0000933 // Two blocks may share a common unpredicable tail, but this doesn't prevent
934 // them from being if-converted. The non-shared portion is assumed to have
935 // been checked
936 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000937 return false;
938
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000939 // If it is already predicated but we couldn't analyze its terminator, the
940 // latter might fallthrough, but we can't determine where to.
941 // Conservatively avoid if-converting again.
942 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
943 return false;
944
Quentin Colombetbdab2272013-07-24 20:20:37 +0000945 // If it is already predicated, check if the new predicate subsumes
946 // its predicate.
947 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000948 return false;
949
Kyle Butt6262ca32016-08-24 21:34:24 +0000950 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000951 if (!isTriangle)
952 return false;
953
Bob Wilson2371f4f2009-05-13 23:25:24 +0000954 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000955 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
956 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000957 if (RevBranch) {
958 if (TII->ReverseBranchCondition(Cond))
959 return false;
960 }
961 if (TII->ReverseBranchCondition(RevPred) ||
962 !TII->SubsumesPredicate(Cond, RevPred))
963 return false;
964 }
965
966 return true;
967}
968
Matthias Braun2c931792016-08-17 02:51:57 +0000969/// Analyze the structure of the sub-CFG starting from the specified block.
970/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000971void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +0000972 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000973 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +0000974 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000975 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000976
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000977 /// This flag is true if MBB's successors have been analyzed.
978 bool SuccsAnalyzed;
979 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000980
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000981 // Push MBB to the stack.
982 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000983
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000984 while (!BBStack.empty()) {
985 BBState &State = BBStack.back();
986 MachineBasicBlock *BB = State.MBB;
987 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000988
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000989 if (!State.SuccsAnalyzed) {
990 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
991 BBStack.pop_back();
992 continue;
993 }
Evan Cheng9030b982007-06-06 10:16:17 +0000994
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000995 BBI.BB = BB;
996 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000997
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000998 AnalyzeBranches(BBI);
999 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1000 MachineBasicBlock::iterator End = BBI.BB->end();
1001 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001002
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001003 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1004 // not considered for ifcvt anymore.
1005 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1006 BBI.IsBeingAnalyzed = false;
1007 BBI.IsAnalyzed = true;
1008 BBStack.pop_back();
1009 continue;
1010 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001011
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001012 // Do not ifcvt if either path is a back edge to the entry block.
1013 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1014 BBI.IsBeingAnalyzed = false;
1015 BBI.IsAnalyzed = true;
1016 BBStack.pop_back();
1017 continue;
1018 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001019
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001020 // Do not ifcvt if true and false fallthrough blocks are the same.
1021 if (!BBI.FalseBB) {
1022 BBI.IsBeingAnalyzed = false;
1023 BBI.IsAnalyzed = true;
1024 BBStack.pop_back();
1025 continue;
1026 }
Evan Cheng7783f822007-06-08 09:36:04 +00001027
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001028 // Push the False and True blocks to the stack.
1029 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001030 BBStack.push_back(*BBI.FalseBB);
1031 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001032 continue;
1033 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001034
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001035 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1036 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001037
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001038 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1039 BBI.IsBeingAnalyzed = false;
1040 BBI.IsAnalyzed = true;
1041 BBStack.pop_back();
1042 continue;
1043 }
1044
1045 SmallVector<MachineOperand, 4>
1046 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1047 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
1048
1049 unsigned Dups = 0;
1050 unsigned Dups2 = 0;
1051 bool TNeedSub = !TrueBBI.Predicate.empty();
1052 bool FNeedSub = !FalseBBI.Predicate.empty();
1053 bool Enqueued = false;
1054
1055 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1056
Kyle Butt6262ca32016-08-24 21:34:24 +00001057 if (CanRevCond) {
1058 BBInfo TrueBBICalc, FalseBBICalc;
1059 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1060 TrueBBICalc, FalseBBICalc) &&
Kyle Buttce0196d2016-08-19 18:17:04 +00001061 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Kyle Butt6262ca32016-08-24 21:34:24 +00001062 TrueBBICalc.ExtraCost),
1063 TrueBBICalc.ExtraCost2,
Kyle Buttce0196d2016-08-19 18:17:04 +00001064 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Kyle Butt6262ca32016-08-24 21:34:24 +00001065 FalseBBICalc.ExtraCost),
1066 FalseBBICalc.ExtraCost2,
1067 Prediction) &&
1068 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1069 /* IsTriangle */ false, /* RevCond */ false,
1070 /* hasCommonTail */ true) &&
1071 FeasibilityAnalysis(FalseBBI, RevCond,
1072 /* IsTriangle */ false, /* RevCond */ false,
1073 /* hasCommonTail */ true)) {
1074 // Diamond:
1075 // EBB
1076 // / \_
1077 // | |
1078 // TBB FBB
1079 // \ /
1080 // TailBB
1081 // Note TailBB can be empty.
1082 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1083 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1084 (bool) TrueBBICalc.ClobbersPred,
1085 (bool) FalseBBICalc.ClobbersPred));
1086 Enqueued = true;
1087 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001088 }
1089
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001090 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1091 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1092 TrueBBI.ExtraCost2, Prediction) &&
1093 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1094 // Triangle:
1095 // EBB
1096 // | \_
1097 // | |
1098 // | TBB
1099 // | /
1100 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001101 Tokens.push_back(
1102 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001103 Enqueued = true;
1104 }
1105
1106 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1107 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1108 TrueBBI.ExtraCost2, Prediction) &&
1109 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001110 Tokens.push_back(
1111 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001112 Enqueued = true;
1113 }
1114
1115 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1116 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1117 TrueBBI.ExtraCost2, Prediction) &&
1118 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1119 // Simple (split, no rejoin):
1120 // EBB
1121 // | \_
1122 // | |
1123 // | TBB---> exit
1124 // |
1125 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001126 Tokens.push_back(
1127 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001128 Enqueued = true;
1129 }
1130
1131 if (CanRevCond) {
1132 // Try the other path...
1133 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1134 Prediction.getCompl()) &&
1135 MeetIfcvtSizeLimit(*FalseBBI.BB,
1136 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1137 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1138 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001139 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1140 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001141 Enqueued = true;
1142 }
1143
1144 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1145 Prediction.getCompl()) &&
1146 MeetIfcvtSizeLimit(*FalseBBI.BB,
1147 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001148 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001149 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001150 Tokens.push_back(
1151 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001152 Enqueued = true;
1153 }
1154
1155 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1156 MeetIfcvtSizeLimit(*FalseBBI.BB,
1157 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1158 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1159 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001160 Tokens.push_back(
1161 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001162 Enqueued = true;
1163 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001164 }
1165
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001166 BBI.IsEnqueued = Enqueued;
1167 BBI.IsBeingAnalyzed = false;
1168 BBI.IsAnalyzed = true;
1169 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001170 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001171}
1172
Matthias Braun2c931792016-08-17 02:51:57 +00001173/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001174void IfConverter::AnalyzeBlocks(
1175 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001176 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001177 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001178
Evan Cheng20e05992007-06-01 00:12:12 +00001179 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001180 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001181}
1182
Matthias Braun2c931792016-08-17 02:51:57 +00001183/// Returns true either if ToMBB is the next block after MBB or that all the
1184/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001185static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1186 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001187 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001188 MachineFunction::iterator TI = ToMBB.getIterator();
1189 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001190 while (I != TI) {
1191 // Check isSuccessor to avoid case where the next block is empty, but
1192 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001193 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001194 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001195 PI = I++;
1196 }
Evan Cheng312b7232007-06-04 06:47:22 +00001197 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001198}
1199
Matthias Braun2c931792016-08-17 02:51:57 +00001200/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1201/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001202void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1203 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001204 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001205 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001206 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001207 PBBI.IsAnalyzed = false;
1208 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001209 }
1210}
1211
Matthias Braun2c931792016-08-17 02:51:57 +00001212/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001213static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001214 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001215 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001216 SmallVector<MachineOperand, 0> NoCond;
Matthias Braun08f47042016-08-17 02:52:01 +00001217 TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001218}
1219
Matthias Braun2c931792016-08-17 02:51:57 +00001220/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001221void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001222 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001223 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001224 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001225 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001226}
1227
Matthias Braund616ccc2013-10-11 19:04:37 +00001228/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001229/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001230static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001231 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1232 ->getSubtarget().getRegisterInfo();
1233
1234 // Before stepping forward past MI, remember which regs were live
1235 // before MI. This is needed to set the Undef flag only when reg is
1236 // dead.
1237 SparseSet<unsigned> LiveBeforeMI;
1238 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001239 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001240 LiveBeforeMI.insert(Reg);
1241
Pete Cooper7605e372015-05-05 20:14:22 +00001242 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001243 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001244
Pete Cooper7605e372015-05-05 20:14:22 +00001245 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001246 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001247 // FIXME: Const cast here is nasty, but better than making StepForward
1248 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001249 unsigned Reg = Clobber.first;
1250 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001251 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001252 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001253 if (Op.isRegMask()) {
1254 // First handle regmasks. They clobber any entries in the mask which
1255 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001256 if (LiveBeforeMI.count(Reg))
1257 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001258
1259 // We also need to add an implicit def of this register for the later
1260 // use to read from.
1261 // For the register allocator to have allocated a register clobbered
1262 // by the call which is used later, it must be the case that
1263 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001264 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001265 continue;
1266 }
1267 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001268 if (Op.isDead()) {
1269 // If we found a dead def, but it needs to be live, then remove the dead
1270 // flag.
1271 if (Redefs.contains(Op.getReg()))
1272 Op.setIsDead(false);
1273 }
Matthias Braun08f47042016-08-17 02:52:01 +00001274 if (LiveBeforeMI.count(Reg))
1275 MIB.addReg(Reg, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001276 }
1277}
1278
Matthias Braun2c931792016-08-17 02:51:57 +00001279/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001280static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001281 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001282 if (!O->isReg() || !O->isKill())
1283 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001284 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001285 O->setIsKill(false);
1286 }
1287}
1288
Matthias Braun2c931792016-08-17 02:51:57 +00001289/// Walks a range of machine instructions and removes kill flags for registers
1290/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001291static void RemoveKills(MachineBasicBlock::iterator I,
1292 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001293 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001294 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001295 for (MachineInstr &MI : make_range(I, E))
1296 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001297}
1298
Matthias Braun2c931792016-08-17 02:51:57 +00001299/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001300bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001301 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1302 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1303 BBInfo *CvtBBI = &TrueBBI;
1304 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001305
Owen Anderson4f6bf042008-08-14 22:49:33 +00001306 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001307 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001308 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001309
Matthias Braun08f47042016-08-17 02:52:01 +00001310 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1311 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001312 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001313 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001314 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001315 BBI.IsAnalyzed = false;
1316 CvtBBI->IsAnalyzed = false;
1317 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001318 }
Evan Chengd0e66912007-05-23 07:23:16 +00001319
Matthias Braun08f47042016-08-17 02:52:01 +00001320 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001321 // Conservatively abort if-conversion if BB's address is taken.
1322 return false;
1323
Evan Cheng3a51c852007-06-16 09:34:52 +00001324 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001325 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001326 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001327
Bob Wilson45814342010-06-19 05:33:57 +00001328 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001329 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001330 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001331 Redefs.addLiveIns(CvtMBB);
1332 Redefs.addLiveIns(NextMBB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001333
1334 // Compute a set of registers which must not be killed by instructions in
1335 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001336 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001337 DontKill.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001338
Matthias Braun08f47042016-08-17 02:52:01 +00001339 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001340 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001341 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001342 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001343 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001344
1345 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1346 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001347 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001348 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001349 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1350 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001351
Evan Cheng92fb5452007-06-15 07:36:12 +00001352 // Merge converted block into entry block.
1353 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1354 MergeBlocks(BBI, *CvtBBI);
1355 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001356
Evan Chenge4ec9182007-06-06 02:08:52 +00001357 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001358 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1359 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001360 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001361 // Now ifcvt'd block will look like this:
1362 // BB:
1363 // ...
1364 // t, f = cmp
1365 // if t op
1366 // b BBf
1367 //
1368 // We cannot further ifcvt this block because the unconditional branch
1369 // will have to be predicated on the new condition, that will not be
1370 // available if cmp executes.
1371 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001372 }
Evan Chenge26c0912007-05-21 22:22:58 +00001373
Evan Cheng288f1542007-06-08 22:01:07 +00001374 RemoveExtraEdges(BBI);
1375
Evan Chengd0e66912007-05-23 07:23:16 +00001376 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001377 if (!IterIfcvt)
1378 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001379 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001380 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001381
1382 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001383 return true;
1384}
1385
Matthias Braun2c931792016-08-17 02:51:57 +00001386/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001387bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001388 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001389 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1390 BBInfo *CvtBBI = &TrueBBI;
1391 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001392 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001393
Owen Anderson4f6bf042008-08-14 22:49:33 +00001394 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001395 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001396 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001397
Matthias Braun08f47042016-08-17 02:52:01 +00001398 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1399 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001400 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001401 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001402 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001403 BBI.IsAnalyzed = false;
1404 CvtBBI->IsAnalyzed = false;
1405 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001406 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001407
Matthias Braun08f47042016-08-17 02:52:01 +00001408 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001409 // Conservatively abort if-conversion if BB's address is taken.
1410 return false;
1411
Evan Cheng3a51c852007-06-16 09:34:52 +00001412 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001413 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001414 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001415
Evan Cheng3a51c852007-06-16 09:34:52 +00001416 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001417 if (ReverseBranchCondition(*CvtBBI)) {
1418 // BB has been changed, modify its predecessors (except for this
1419 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001420 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001421 if (PBB == BBI.BB)
1422 continue;
1423 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1424 if (PBBI.IsEnqueued) {
1425 PBBI.IsAnalyzed = false;
1426 PBBI.IsEnqueued = false;
1427 }
Evan Chengadd97762007-06-14 23:34:09 +00001428 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001429 }
1430 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001431
Bob Wilson45814342010-06-19 05:33:57 +00001432 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001433 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001434 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001435 Redefs.addLiveIns(CvtMBB);
1436 Redefs.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001437
Andrew Trick276dd452013-10-14 20:45:17 +00001438 DontKill.clear();
1439
Craig Topperc0196b12014-04-14 00:51:57 +00001440 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001441 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001442
Manman Renb6819182014-01-29 23:18:47 +00001443 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001444 // Get probabilities before modifying CvtMBB and BBI.BB.
1445 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1446 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1447 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1448 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001449 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001450
Matthias Braun08f47042016-08-17 02:52:01 +00001451 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001452 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001453 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001454 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001455 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001456
1457 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1458 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001459 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001460 } else {
1461 // Predicate the 'true' block after removing its branch.
Matthias Braun08f47042016-08-17 02:52:01 +00001462 CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1463 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001464
Evan Cheng0598b2d2007-06-18 22:44:57 +00001465 // Now merge the entry of the triangle with the true block.
1466 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001467 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001468 }
1469
Evan Cheng312b7232007-06-04 06:47:22 +00001470 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001471 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001472 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1473 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001474 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001475 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001476
Cong Houd97c1002015-12-01 05:29:22 +00001477 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001478 // NewNext = New_Prob(BBI.BB, NextMBB) =
1479 // Prob(BBI.BB, NextMBB) +
1480 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001481 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001482 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1483 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001484 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001485 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001486 if (NewTrueBBIter != BBI.BB->succ_end())
1487 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001488
1489 auto NewFalse = BBCvt * CvtFalse;
1490 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1491 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001492 }
Evan Cheng7783f822007-06-08 09:36:04 +00001493
1494 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001495 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001496 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001497 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001498 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001499 if (!isFallThrough) {
1500 // Only merge them if the true block does not fallthrough to the false
1501 // block. By not merging them, we make it possible to iteratively
1502 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001503 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001504 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1505 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001506 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001507 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001508 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001509 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001510 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001511 }
Evan Cheng7783f822007-06-08 09:36:04 +00001512 // Mixed predicated and unpredicated code. This cannot be iteratively
1513 // predicated.
1514 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001515 }
Evan Chenge26c0912007-05-21 22:22:58 +00001516
Evan Cheng288f1542007-06-08 22:01:07 +00001517 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001518
Evan Chengd0e66912007-05-23 07:23:16 +00001519 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001520 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001521 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001522 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001523 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001524 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001525 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001526
1527 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001528 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001529}
1530
Kyle Buttce0196d2016-08-19 18:17:04 +00001531/// If convert a diamond sub-CFG.
Kyle Butt6262ca32016-08-24 21:34:24 +00001532/// \p BBI is the head of the diamond
1533/// \p NumDups1 - number of shared instructions at the beginning of TrueBBI and
1534/// FalseBBI
1535/// \p NumDups2 - number of shared instructions at the end of TrueBBI and
1536/// FalseBBI
1537/// \p TClobbersPred - True if the true block clobbers the predicate in the
1538/// non-shared portion.
1539/// \p TClobbersPred - True if the false block clobbers the predicate in the
1540/// non-shared portion.
Kyle Buttce0196d2016-08-19 18:17:04 +00001541bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +00001542 unsigned NumDups1, unsigned NumDups2,
1543 bool TClobbersPred, bool FClobbersPred) {
Kyle Buttce0196d2016-08-19 18:17:04 +00001544 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1545 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1546 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1547 // True block must fall through or end with an unanalyzable terminator.
1548 if (!TailBB) {
1549 if (blockAlwaysFallThrough(TrueBBI))
1550 TailBB = FalseBBI.TrueBB;
1551 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1552 }
Evan Chenge26c0912007-05-21 22:22:58 +00001553
Evan Cheng51eb2c32007-06-18 08:37:25 +00001554 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Buttce0196d2016-08-19 18:17:04 +00001555 TrueBBI.BB->pred_size() > 1 ||
1556 FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001557 // Something has changed. It's no longer safe to predicate these blocks.
1558 BBI.IsAnalyzed = false;
1559 TrueBBI.IsAnalyzed = false;
1560 FalseBBI.IsAnalyzed = false;
1561 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001562 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001563
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001564 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1565 // Conservatively abort if-conversion if either BB has its address taken.
1566 return false;
1567
Bob Wilson1e5da552010-06-29 00:55:23 +00001568 // Put the predicated instructions from the 'true' block before the
1569 // instructions from the 'false' block, unless the true block would clobber
1570 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001571 BBInfo *BBI1 = &TrueBBI;
1572 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001573 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001574 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001575 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001576 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1577 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001578
Evan Cheng3a51c852007-06-16 09:34:52 +00001579 // Figure out the more profitable ordering.
1580 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001581 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001582 DoSwap = true;
Kyle Butt6262ca32016-08-24 21:34:24 +00001583 else if (TClobbersPred == FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001584 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001585 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001586 }
1587 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001588 std::swap(BBI1, BBI2);
1589 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001590 }
Evan Cheng79484222007-06-05 23:46:14 +00001591
Evan Cheng51eb2c32007-06-18 08:37:25 +00001592 // Remove the conditional branch from entry to the blocks.
1593 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1594
Matthias Braun08f47042016-08-17 02:52:01 +00001595 MachineBasicBlock &MBB1 = *BBI1->BB;
1596 MachineBasicBlock &MBB2 = *BBI2->BB;
1597
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001598 // Initialize the Redefs:
1599 // - BB2 live-in regs need implicit uses before being redefined by BB1
1600 // instructions.
1601 // - BB1 live-out regs need implicit uses before being redefined by BB2
1602 // instructions. We start with BB1 live-ins so we have the live-out regs
1603 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001604 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001605 Redefs.addLiveIns(MBB1);
1606 Redefs.addLiveIns(MBB2);
Evan Chengf128bdc2010-06-16 07:35:02 +00001607
Evan Cheng51eb2c32007-06-18 08:37:25 +00001608 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001609 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001610 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1611 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001612 BBI1->NonPredSize -= NumDups1;
1613 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001614
1615 // Skip past the dups on each side separately since there may be
1616 // differing dbg_value entries.
1617 for (unsigned i = 0; i < NumDups1; ++DI1) {
1618 if (!DI1->isDebugValue())
1619 ++i;
1620 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001621 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001622 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001623 if (!DI2->isDebugValue())
1624 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001625 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001626
Matthias Braund616ccc2013-10-11 19:04:37 +00001627 // Compute a set of registers which must not be killed by instructions in BB1:
1628 // This is everything used+live in BB2 after the duplicated instructions. We
1629 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001630 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001631 for (const MachineInstr &MI :
1632 make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
Matthias Braunb1e05582016-08-17 02:51:59 +00001633 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001634
Matthias Braun08f47042016-08-17 02:52:01 +00001635 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Pete Cooper7605e372015-05-05 20:14:22 +00001636 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
Matthias Braunb1e05582016-08-17 02:51:59 +00001637 Redefs.stepForward(MI, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001638 }
Matthias Braun08f47042016-08-17 02:52:01 +00001639 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1640 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001641
Kyle Buttce0196d2016-08-19 18:17:04 +00001642 // Remove branch from the 'true' block, unless it was not analyzable.
1643 // Non-analyzable branches need to be preserved, since in such cases,
1644 // the CFG structure is not an actual diamond (the join block may not
1645 // be present).
1646 if (BBI1->IsBrAnalyzable)
1647 BBI1->NonPredSize -= TII->RemoveBranch(MBB1);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001648 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001649 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001650 for (unsigned i = 0; i != NumDups2; ) {
1651 // NumDups2 only counted non-dbg_value instructions, so this won't
1652 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001653 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001654 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001655 // skip dbg_value instructions
1656 if (!DI1->isDebugValue())
1657 ++i;
1658 }
Matthias Braun08f47042016-08-17 02:52:01 +00001659 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001660
Matthias Braund616ccc2013-10-11 19:04:37 +00001661 // Kill flags in the true block for registers living into the false block
1662 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001663 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001664
Kyle Buttce0196d2016-08-19 18:17:04 +00001665 // Remove 'false' block branch (unless it was not analyzable), and find
1666 // the last instruction to predicate.
1667 if (BBI2->IsBrAnalyzable)
1668 BBI2->NonPredSize -= TII->RemoveBranch(MBB2);
1669 DI2 = MBB2.end();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001670 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001671 // NumDups2 only counted non-dbg_value instructions, so this won't
1672 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001673 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001674 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001675 // skip dbg_value instructions
1676 if (!DI2->isDebugValue())
1677 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001678 }
Evan Cheng4266a792011-12-19 22:01:30 +00001679
1680 // Remember which registers would later be defined by the false block.
1681 // This allows us not to predicate instructions in the true block that would
1682 // later be re-defined. That is, rather than
1683 // subeq r0, r1, #1
1684 // addne r0, r1, #1
1685 // generate:
1686 // sub r0, r1, #1
1687 // addne r0, r1, #1
1688 SmallSet<unsigned, 4> RedefsByFalse;
1689 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001690 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1691 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001692 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001693 continue;
1694 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001695 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001696 if (!MO.isReg())
1697 continue;
1698 unsigned Reg = MO.getReg();
1699 if (!Reg)
1700 continue;
1701 if (MO.isDef()) {
1702 Defs.push_back(Reg);
1703 } else if (!RedefsByFalse.count(Reg)) {
1704 // These are defined before ctrl flow reach the 'false' instructions.
1705 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001706 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1707 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001708 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001709 }
1710 }
1711
Matthias Braunb1e05582016-08-17 02:51:59 +00001712 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001713 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001714 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1715 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001716 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001717 }
1718 }
1719 }
1720 }
1721
1722 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001723 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001724
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001725 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1726 // a non-predicated in BBI2, then we don't want to predicate the one from
1727 // BBI2. The reason is that if we merged these blocks, we would end up with
1728 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001729 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1730 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1731 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1732 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1733 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001734 --DI2;
1735 }
1736
Evan Cheng4266a792011-12-19 22:01:30 +00001737 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001738 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001739
Evan Cheng0598b2d2007-06-18 22:44:57 +00001740 // Merge the true block into the entry of the diamond.
Kyle Buttce0196d2016-08-19 18:17:04 +00001741 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1742 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001743
Bob Wilson2371f4f2009-05-13 23:25:24 +00001744 // If the if-converted block falls through or unconditionally branches into
1745 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001746 // fold the tail block in as well. Otherwise, unless it falls through to the
1747 // tail, add a unconditional branch to it.
1748 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001749 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001750 bool CanMergeTail = !TailBBI.HasFallThrough &&
1751 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001752 // The if-converted block can still have a predicated terminator
1753 // (e.g. a predicated return). If that is the case, we cannot merge
1754 // it with the tail block.
1755 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001756 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001757 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001758 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1759 // check if there are any other predecessors besides those.
1760 unsigned NumPreds = TailBB->pred_size();
1761 if (NumPreds > 1)
1762 CanMergeTail = false;
1763 else if (NumPreds == 1 && CanMergeTail) {
1764 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Buttce0196d2016-08-19 18:17:04 +00001765 if (*PI != &MBB1 && *PI != &MBB2)
Bob Wilson1e5da552010-06-29 00:55:23 +00001766 CanMergeTail = false;
1767 }
1768 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001769 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001770 TailBBI.IsDone = true;
1771 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001772 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001773 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001774 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001775 }
Evan Chenge26c0912007-05-21 22:22:58 +00001776 }
1777
Bob Wilson1e5da552010-06-29 00:55:23 +00001778 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1779 // which can happen here if TailBB is unanalyzable and is merged, so
1780 // explicitly remove BBI1 and BBI2 as successors.
Kyle Buttce0196d2016-08-19 18:17:04 +00001781 BBI.BB->removeSuccessor(&MBB1);
1782 BBI.BB->removeSuccessor(&MBB2, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001783 RemoveExtraEdges(BBI);
1784
Evan Cheng79484222007-06-05 23:46:14 +00001785 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001786 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001787 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001788
1789 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001790 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001791}
1792
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001793static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001794 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001795 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001796 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001797 return false;
1798
Matthias Braunb1e05582016-08-17 02:51:59 +00001799 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001800 if (!MO.isReg())
1801 continue;
1802 unsigned Reg = MO.getReg();
1803 if (!Reg)
1804 continue;
1805 if (MO.isDef() && !LaterRedefs.count(Reg))
1806 return false;
1807 }
1808
1809 return true;
1810}
1811
Matthias Braun2c931792016-08-17 02:51:57 +00001812/// Predicate instructions from the start of the block to the specified end with
1813/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001814void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001815 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001816 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001817 SmallSet<unsigned, 4> *LaterRedefs) {
1818 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001819 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001820 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001821 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001822 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001823 // It may be possible not to predicate an instruction if it's the 'true'
1824 // side of a diamond and the 'false' side may re-define the instruction's
1825 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001826 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001827 AnyUnpred = true;
1828 continue;
1829 }
1830 // If any instruction is predicated, then every instruction after it must
1831 // be predicated.
1832 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001833 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001834#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001835 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001836#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001837 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001838 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001839
Bob Wilson45814342010-06-19 05:33:57 +00001840 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001841 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001842 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001843 }
Evan Chengd0e66912007-05-23 07:23:16 +00001844
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001845 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001846
Evan Cheng92fb5452007-06-15 07:36:12 +00001847 BBI.IsAnalyzed = false;
1848 BBI.NonPredSize = 0;
1849
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001850 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001851 if (AnyUnpred)
1852 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001853}
1854
Matthias Braun2c931792016-08-17 02:51:57 +00001855/// Copy and predicate instructions from source BB to the destination block.
1856/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00001857void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001858 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001859 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001860 MachineFunction &MF = *ToBBI.BB->getParent();
1861
Matthias Braun08f47042016-08-17 02:52:01 +00001862 MachineBasicBlock &FromMBB = *FromBBI.BB;
1863 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001864 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001865 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001866 break;
1867
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001868 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001869 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001870 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001871 unsigned ExtraPredCost = TII->getPredicationCost(I);
1872 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001873 if (NumCycles > 1)
1874 ToBBI.ExtraCost += NumCycles-1;
1875 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001876
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001877 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001878 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001879#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001880 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001881#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001882 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001883 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001884 }
1885
Bob Wilson45814342010-06-19 05:33:57 +00001886 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001887 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001888 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001889
1890 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001891 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001892 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001893 }
1894
Bob Wilson1e5da552010-06-29 00:55:23 +00001895 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00001896 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
1897 FromMBB.succ_end());
1898 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001899 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001900
Matthias Braunb1e05582016-08-17 02:51:59 +00001901 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00001902 // Fallthrough edge can't be transferred.
1903 if (Succ == FallThrough)
1904 continue;
1905 ToBBI.BB->addSuccessor(Succ);
1906 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001907 }
1908
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001909 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1910 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001911
1912 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1913 ToBBI.IsAnalyzed = false;
1914
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001915 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001916}
1917
Matthias Braun2c931792016-08-17 02:51:57 +00001918/// Move all instructions from FromBB to the end of ToBB. This will leave
1919/// FromBB as an empty block, so remove all of its successor edges except for
1920/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
1921/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00001922void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00001923 MachineBasicBlock &FromMBB = *FromBBI.BB;
1924 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001925 "Removing a BB whose address is taken!");
1926
Matthias Braun08f47042016-08-17 02:52:01 +00001927 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001928 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00001929 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001930 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00001931 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001932
1933 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00001934 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001935 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00001936 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00001937
Cong Houb9e8d482015-12-17 01:29:08 +00001938 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1939 // unknown probabilities into known ones.
1940 // FIXME: This usage is too tricky and in the future we would like to
1941 // eliminate all unknown probabilities in MBB.
1942 ToBBI.BB->normalizeSuccProbs();
1943
Matthias Braun08f47042016-08-17 02:52:01 +00001944 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
1945 FromMBB.succ_end());
1946 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001947 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00001948 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
1949 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001950 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00001951 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
1952 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
1953 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00001954 // edge probability being merged to other edges when this edge is removed
1955 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00001956 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00001957 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00001958 }
1959
Matthias Braunb1e05582016-08-17 02:51:59 +00001960 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00001961 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001962 if (Succ == FallThrough)
1963 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001964
Cong Houd97c1002015-12-01 05:29:22 +00001965 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001966 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001967 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00001968 // which is a portion of the edge probability from FromMBB to Succ. The
1969 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00001970 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00001971 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001972
Matthias Braun08f47042016-08-17 02:52:01 +00001973 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
1974 // only happens when if-converting a diamond CFG and FromMBB is the
1975 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
1976 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00001977 // new successors.
1978 if (!To2FromProb.isZero())
1979 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001980 }
1981
Matthias Braun08f47042016-08-17 02:52:01 +00001982 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001983
1984 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001985 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001986 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00001987 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00001988 // don't have to set C as A's successor as it already is. We only need to
1989 // update the edge probability on A->C. Note that B will not be
1990 // immediately removed from A's successors. It is possible that B->D is
1991 // not removed either if D is a fallthrough of B. Later the edge A->D
1992 // (generated here) and B->D will be combined into one edge. To maintain
1993 // correct edge probability of this combined edge, we need to set the edge
1994 // probability of A->B to zero, which is already done above. The edge
1995 // probability on A->D is calculated by scaling the original probability
1996 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001997 //
1998 // Before ifcvt: After ifcvt (assume B->D is kept):
1999 //
2000 // A A
2001 // /| /|\
2002 // / B / B|
2003 // | /| | ||
2004 // |/ | | |/
2005 // C D C D
2006 //
2007 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002008 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002009 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002010 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002011 else
Cong Houd97c1002015-12-01 05:29:22 +00002012 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002013 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002014 }
2015
Bob Wilson2371f4f2009-05-13 23:25:24 +00002016 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00002017 if (NBB && !FromMBB.isSuccessor(NBB))
2018 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00002019
Cong Houc1069892015-12-13 09:26:17 +00002020 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2021 // we've done above.
2022 ToBBI.BB->normalizeSuccProbs();
2023
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002024 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002025 FromBBI.Predicate.clear();
2026
Evan Chengd0e66912007-05-23 07:23:16 +00002027 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002028 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002029 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002030 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002031 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002032 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002033
Evan Cheng4dd31a72007-06-11 22:26:22 +00002034 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002035 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002036 ToBBI.IsAnalyzed = false;
2037 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002038}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002039
2040FunctionPass *
2041llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002042 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002043}