blob: 0f7bc65269810f9f62cc66e1fdf861ace2a70177 [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;
Kyle Butt5b104832016-08-19 18:17:06 +0000152 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000153 unsigned NumDups;
154 unsigned NumDups2;
Kyle Butt5b104832016-08-19 18:17:06 +0000155 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
156 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000157 };
158
Matthias Braun2c931792016-08-17 02:51:57 +0000159 /// Results of if-conversion feasibility analysis indexed by basic block
160 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000161 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000162 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000163
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000164 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000165 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000166 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000167 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000168 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000169
Juergen Ributzka310034e2013-12-14 06:52:56 +0000170 LivePhysRegs Redefs;
171 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000172
Evan Chengc5adcca2012-06-08 21:53:50 +0000173 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000174 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000175 int FnNum;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000176 std::function<bool(const Function &)> PredicateFtor;
177
Evan Chengf5e53a52007-05-16 02:00:57 +0000178 public:
179 static char ID;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000180 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000181 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000182 initializeIfConverterPass(*PassRegistry::getPassRegistry());
183 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000184
Craig Topper4584cd52014-03-07 09:26:03 +0000185 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000186 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000187 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000188 MachineFunctionPass::getAnalysisUsage(AU);
189 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000190
Craig Topper4584cd52014-03-07 09:26:03 +0000191 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000192
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000193 MachineFunctionProperties getRequiredProperties() const override {
194 return MachineFunctionProperties().set(
195 MachineFunctionProperties::Property::AllVRegsAllocated);
196 }
197
Evan Chengf5e53a52007-05-16 02:00:57 +0000198 private:
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000199 bool ReverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000200 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000201 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000202 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000203 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000204 BranchProbability Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000205 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt5b104832016-08-19 18:17:06 +0000206 unsigned &Dups1, unsigned &Dups2) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000207 void AnalyzeBranches(BBInfo &BBI);
208 void ScanInstructions(BBInfo &BBI,
209 MachineBasicBlock::iterator &Begin,
Kyle Buttce0196d2016-08-19 18:17:04 +0000210 MachineBasicBlock::iterator &End) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000211 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000212 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000213 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt5b104832016-08-19 18:17:06 +0000214 bool isTriangle = false, bool RevBranch = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000215 void AnalyzeBlocks(MachineFunction &MF,
216 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000217 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng288f1542007-06-08 22:01:07 +0000218 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000219 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
220 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000221 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt5b104832016-08-19 18:17:06 +0000222 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000223 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000224 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000225 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000226 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000227 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000228 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000229 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000230 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000231
Evan Chengdebf9c52010-11-03 00:45:17 +0000232 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
233 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000234 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000235 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000236 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000237 }
238
Evan Chengdebf9c52010-11-03 00:45:17 +0000239 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
240 unsigned TCycle, unsigned TExtra,
241 MachineBasicBlock &FBB,
242 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000243 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000244 return TCycle > 0 && FCycle > 0 &&
245 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000246 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000247 }
248
Matthias Braun2c931792016-08-17 02:51:57 +0000249 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000250 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000251 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000252 }
253
Matthias Braun2c931792016-08-17 02:51:57 +0000254 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000255 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
256 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000257 int Incr1 = (C1->Kind == ICDiamond)
258 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
259 int Incr2 = (C2->Kind == ICDiamond)
260 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
261 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000262 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000263 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000264 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000265 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000266 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000267 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000268 // Favors diamond over triangle, etc.
269 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
270 return true;
271 else if (C1->Kind == C2->Kind)
272 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
273 }
274 }
275 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000276 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000277 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000278
Evan Chengf5e53a52007-05-16 02:00:57 +0000279 char IfConverter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000280}
Evan Chengf5e53a52007-05-16 02:00:57 +0000281
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000282char &llvm::IfConverterID = IfConverter::ID;
283
Owen Anderson8ac477f2010-10-12 19:48:12 +0000284INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000285INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000286INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000287
Evan Chengf5e53a52007-05-16 02:00:57 +0000288bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000289 if (skipFunction(*MF.getFunction()) ||
290 (PredicateFtor && !PredicateFtor(*MF.getFunction())))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000291 return false;
292
Eric Christopher3d4276f2015-01-27 07:31:29 +0000293 const TargetSubtargetInfo &ST = MF.getSubtarget();
294 TLI = ST.getTargetLowering();
295 TII = ST.getInstrInfo();
296 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000297 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000298 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000299 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000300 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000301
Evan Chengf5e53a52007-05-16 02:00:57 +0000302 if (!TII) return false;
303
Evan Chengc5adcca2012-06-08 21:53:50 +0000304 PreRegAlloc = MRI->isSSA();
305
306 bool BFChange = false;
307 if (!PreRegAlloc) {
308 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000309 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000310 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000311 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000312 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000313
David Greene72e47cd2010-01-04 22:02:01 +0000314 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000315 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000316
317 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000318 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000319 return false;
320 }
David Greene72e47cd2010-01-04 22:02:01 +0000321 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000322
Evan Chengf5e53a52007-05-16 02:00:57 +0000323 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000324 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000325
Justin Lebar3a7bc572016-02-22 17:51:28 +0000326 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000327 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000328 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
329 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
330 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000331 // Do an initial analysis for each basic block and find all the potential
332 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000333 bool Change = false;
334 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000335 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000336 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000337 Tokens.pop_back();
338 BBInfo &BBI = Token->BBI;
339 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000340 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000341 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000342
Evan Cheng4dd31a72007-06-11 22:26:22 +0000343 // If the block has been evicted out of the queue or it has already been
344 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000345 if (BBI.IsDone)
346 BBI.IsEnqueued = false;
347 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000348 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000349
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000350 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000351
Evan Cheng312b7232007-06-04 06:47:22 +0000352 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000353 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000354 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000355 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000356 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000357 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000358 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000359 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
360 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000361 << "): BB#" << BBI.BB->getNumber() << " ("
362 << ((Kind == ICSimpleFalse)
363 ? BBI.FalseBB->getNumber()
364 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000365 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000366 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000367 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000368 if (isFalse) ++NumSimpleFalse;
369 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000370 }
Evan Cheng312b7232007-06-04 06:47:22 +0000371 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000372 }
Evan Chengd0e66912007-05-23 07:23:16 +0000373 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000374 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000375 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000376 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000377 bool isFalse = Kind == ICTriangleFalse;
378 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000379 if (DisableTriangle && !isFalse && !isRev) break;
380 if (DisableTriangleR && !isFalse && isRev) break;
381 if (DisableTriangleF && isFalse && !isRev) break;
382 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000383 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000384 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000385 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000386 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000387 DEBUG(dbgs() << " rev");
388 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000389 << BBI.TrueBB->getNumber() << ",F:"
390 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000391 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000392 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000393 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000394 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000395 if (isRev) ++NumTriangleFRev;
396 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000397 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000398 if (isRev) ++NumTriangleRev;
399 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000400 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000401 }
Evan Chengd0e66912007-05-23 07:23:16 +0000402 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000403 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000404 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000405 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000406 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000407 << BBI.TrueBB->getNumber() << ",F:"
408 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt5b104832016-08-19 18:17:06 +0000409 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000410 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000411 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000412 break;
413 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000414 }
415
Evan Cheng312b7232007-06-04 06:47:22 +0000416 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000417
Evan Cheng92fb5452007-06-15 07:36:12 +0000418 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
419 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
420 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000421 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000422 }
Evan Chengd0e66912007-05-23 07:23:16 +0000423
Evan Chengd0e66912007-05-23 07:23:16 +0000424 if (!Change)
425 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000426 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000427 }
Evan Cheng478b8052007-05-18 01:55:58 +0000428
Evan Cheng3a51c852007-06-16 09:34:52 +0000429 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000430 BBAnalysis.clear();
431
Evan Chengcf9e8a92010-06-18 22:17:13 +0000432 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000433 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000434 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000435 getAnalysisIfAvailable<MachineModuleInfo>());
436 }
437
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000438 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000439 return MadeChange;
440}
441
Matthias Braun2c931792016-08-17 02:51:57 +0000442/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000443static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000444 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000445 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000446 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000447 return SuccBB;
448 }
Craig Topperc0196b12014-04-14 00:51:57 +0000449 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000450}
451
Matthias Braun2c931792016-08-17 02:51:57 +0000452/// Reverse the condition of the end of the block branch. Swap block's 'true'
453/// and 'false' successors.
Kyle Butt59f2a2a2016-07-27 20:19:31 +0000454bool IfConverter::ReverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000455 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000456 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
457 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000458 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000459 std::swap(BBI.TrueBB, BBI.FalseBB);
460 return true;
461 }
462 return false;
463}
464
Matthias Braun2c931792016-08-17 02:51:57 +0000465/// Returns the next block in the function blocks ordering. If it is the end,
466/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000467static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
468 MachineFunction::iterator I = MBB.getIterator();
469 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000470 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000471 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000472 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000473}
474
Matthias Braun2c931792016-08-17 02:51:57 +0000475/// Returns true if the 'true' block (along with its predecessor) forms a valid
476/// simple shape for ifcvt. It also returns the number of instructions that the
477/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000478bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000479 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000480 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000481 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000482 return false;
483
Evan Chenga955c022007-06-19 21:45:13 +0000484 if (TrueBBI.IsBrAnalyzable)
485 return false;
486
Evan Cheng23402fc2007-06-15 21:18:05 +0000487 if (TrueBBI.BB->pred_size() > 1) {
488 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000489 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000490 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000491 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000492 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000493 }
494
Evan Chenga955c022007-06-19 21:45:13 +0000495 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000496}
497
Matthias Braun2c931792016-08-17 02:51:57 +0000498/// Returns true if the 'true' and 'false' blocks (along with their common
499/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
500/// true, it checks if 'true' block's false branch branches to the 'false' block
501/// rather than the other way around. It also returns the number of instructions
502/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000503bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000504 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000505 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000506 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000507 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000508 return false;
509
Evan Cheng23402fc2007-06-15 21:18:05 +0000510 if (TrueBBI.BB->pred_size() > 1) {
511 if (TrueBBI.CannotBeCopied)
512 return false;
513
Evan Cheng92fb5452007-06-15 07:36:12 +0000514 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000515 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000516 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000517 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000518 --Size;
519 else {
520 MachineBasicBlock *FExit = FalseBranch
521 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
522 if (FExit)
523 // Require a conditional branch
524 ++Size;
525 }
526 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000527 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000528 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000529 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000530 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000531
Evan Cheng7783f822007-06-08 09:36:04 +0000532 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
533 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000534 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000535 if (++I == TrueBBI.BB->getParent()->end())
536 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000537 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000538 }
Evan Cheng7783f822007-06-08 09:36:04 +0000539 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000540}
541
Matthias Braun2c931792016-08-17 02:51:57 +0000542/// Increment \p It until it points to a non-debug instruction or to \p End.
Kyle Buttfe916822016-08-06 01:52:31 +0000543/// @param It Iterator to increment
544/// @param End Iterator that points to end. Will be compared to It
545/// @returns true if It == End, false otherwise.
546static inline bool skipDebugInstructionsForward(
547 MachineBasicBlock::iterator &It,
548 MachineBasicBlock::iterator &End) {
549 while (It != End && It->isDebugValue())
550 It++;
551 return It == End;
552}
553
Kyle Buttd76755e2016-08-18 22:09:23 +0000554/// Shrink the provided inclusive range by one instruction.
555/// If the range was one instruction (\p It == \p Begin), It is not modified,
556/// but \p Empty is set to true.
557static inline void shrinkInclusiveRange(
558 MachineBasicBlock::iterator &Begin,
559 MachineBasicBlock::iterator &It,
560 bool &Empty) {
561 if (It == Begin)
562 Empty = true;
563 else
564 It--;
565}
566
567/// Decrement \p It until it points to a non-debug instruction or the range is
568/// empty.
Kyle Buttfe916822016-08-06 01:52:31 +0000569/// @param It Iterator to decrement.
David Majnemer70c93fa2016-08-06 08:37:12 +0000570/// @param Begin Iterator that points to beginning. Will be compared to It
Kyle Buttd76755e2016-08-18 22:09:23 +0000571/// @param Empty Set to true if the resulting range is Empty
572/// @returns the value of Empty as a convenience.
Kyle Buttfe916822016-08-06 01:52:31 +0000573static inline bool skipDebugInstructionsBackward(
Kyle Buttd76755e2016-08-18 22:09:23 +0000574 MachineBasicBlock::iterator &Begin,
Kyle Buttfe916822016-08-06 01:52:31 +0000575 MachineBasicBlock::iterator &It,
Kyle Buttd76755e2016-08-18 22:09:23 +0000576 bool &Empty) {
577 while (!Empty && It->isDebugValue())
578 shrinkInclusiveRange(Begin, It, Empty);
579 return Empty;
Kyle Buttfe916822016-08-06 01:52:31 +0000580}
581
Kyle Butt4f0e2872016-08-06 01:52:33 +0000582/// Count duplicated instructions and move the iterators to show where they
583/// are.
584/// @param TIB True Iterator Begin
585/// @param FIB False Iterator Begin
586/// These two iterators initially point to the first instruction of the two
587/// blocks, and finally point to the first non-shared instruction.
588/// @param TIE True Iterator End
589/// @param FIE False Iterator End
590/// These two iterators initially point to End() for the two blocks() and
591/// finally point to the first shared instruction in the tail.
592/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
593/// two blocks.
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000594static void countDuplicatedInstructions(
595 MachineBasicBlock::iterator &TIB,
596 MachineBasicBlock::iterator &FIB,
597 MachineBasicBlock::iterator &TIE,
598 MachineBasicBlock::iterator &FIE,
599 unsigned &Dups1, unsigned &Dups2,
600 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
601 bool SkipConditionalBranches) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000602
Bob Wilsone1961fe2010-10-26 00:02:24 +0000603 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000604 // Skip dbg_value instructions. These do not count.
Kyle Buttfe916822016-08-06 01:52:31 +0000605 if(skipDebugInstructionsForward(TIB, TIE))
606 break;
607 if(skipDebugInstructionsForward(FIB, FIE))
608 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000609 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000610 break;
611 ++Dups1;
612 ++TIB;
613 ++FIB;
614 }
615
Kyle Buttce0196d2016-08-19 18:17:04 +0000616 // If both blocks are returning don't skip the branches, since they will
617 // likely be both identical return instructions. In such cases the return
618 // can be left unpredicated.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000619 // Check for already containing all of the block.
620 if (TIB == TIE || FIB == FIE)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000621 return;
Kyle Buttd76755e2016-08-18 22:09:23 +0000622 // Now, in preparation for counting duplicate instructions at the ends of the
623 // blocks, move the end iterators up past any branch instructions.
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000624 --TIE;
625 --FIE;
Kyle Buttd76755e2016-08-18 22:09:23 +0000626
627 // After this point TIB and TIE define an inclusive range, which means that
628 // TIB == TIE is true when there is one more instruction to consider, not at
629 // the end. Because we may not be able to go before TIB, we need a flag to
630 // indicate a completely empty range.
631 bool TEmpty = false, FEmpty = false;
632
633 // Upon exit TIE and FIE will both point at the last non-shared instruction.
634 // They need to be moved forward to point past the last non-shared
635 // instruction if the range they delimit is non-empty.
636 auto IncrementEndIteratorsOnExit = make_scope_exit([&]() {
637 if (!TEmpty)
638 ++TIE;
639 if (!FEmpty)
640 ++FIE;
641 });
642
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000643 if (!TBB.succ_empty() || !FBB.succ_empty()) {
644 if (SkipConditionalBranches) {
Kyle Buttd76755e2016-08-18 22:09:23 +0000645 while (!TEmpty && TIE->isBranch())
646 shrinkInclusiveRange(TIB, TIE, TEmpty);
647 while (!FEmpty && FIE->isBranch())
648 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000649 } else {
Kyle Buttd76755e2016-08-18 22:09:23 +0000650 while (!TEmpty && TIE->isUnconditionalBranch())
651 shrinkInclusiveRange(TIB, TIE, TEmpty);
652 while (!FEmpty && FIE->isUnconditionalBranch())
653 shrinkInclusiveRange(FIB, FIE, FEmpty);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000654 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000655 }
656
657 // If Dups1 includes all of a block, then don't count duplicate
658 // instructions at the end of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000659 if (TEmpty || FEmpty)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000660 return;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000661
662 // Count duplicate instructions at the ends of the blocks.
Kyle Buttd76755e2016-08-18 22:09:23 +0000663 while (!TEmpty && !FEmpty) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000664 // Skip dbg_value instructions. These do not count.
Kyle Buttd76755e2016-08-18 22:09:23 +0000665 if (skipDebugInstructionsBackward(TIB, TIE, TEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000666 break;
Kyle Buttd76755e2016-08-18 22:09:23 +0000667 if (skipDebugInstructionsBackward(FIB, FIE, FEmpty))
Kyle Buttfe916822016-08-06 01:52:31 +0000668 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000669 if (!TIE->isIdenticalTo(*FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000670 break;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000671 // If we are trying to make sure the conditional branches are the same, we
672 // still don't want to count them.
673 if (SkipConditionalBranches || !TIE->isBranch())
674 ++Dups2;
Kyle Buttd76755e2016-08-18 22:09:23 +0000675 shrinkInclusiveRange(TIB, TIE, TEmpty);
676 shrinkInclusiveRange(FIB, FIE, FEmpty);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000677 }
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000678}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000679
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000680/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
681/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt5b104832016-08-19 18:17:06 +0000682bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
683 unsigned &Dups1, unsigned &Dups2) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000684 Dups1 = Dups2 = 0;
685 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
686 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
687 return false;
688
689 MachineBasicBlock *TT = TrueBBI.TrueBB;
690 MachineBasicBlock *FT = FalseBBI.TrueBB;
691
692 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000693 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000694 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000695 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000696 if (TT != FT)
697 return false;
698 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
699 return false;
700 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
701 return false;
702
703 // FIXME: Allow true block to have an early exit?
Kyle Butt5b104832016-08-19 18:17:06 +0000704 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
705 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000706 return false;
707
708 // Count duplicate instructions at the beginning and end of the true and
709 // false blocks.
710 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
711 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
712 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
713 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
714 countDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
715 *TrueBBI.BB, *FalseBBI.BB,
716 /* SkipConditionalBranches */ true);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000717 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000718}
719
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000720/// AnalyzeBranches - Look at the branches at the end of a block to determine if
721/// the block is predicable.
722void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000723 if (BBI.IsDone)
724 return;
725
Craig Topperc0196b12014-04-14 00:51:57 +0000726 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000727 BBI.BrCond.clear();
728 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000729 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000730 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000731
732 if (BBI.BrCond.size()) {
733 // No false branch. This BB must end with a conditional branch and a
734 // fallthrough.
735 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000736 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000737 if (!BBI.FalseBB) {
738 // Malformed bcc? True and false blocks are the same?
739 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000740 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000741 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000742}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000743
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000744/// ScanInstructions - Scan all the instructions in the block to determine if
745/// the block is predicable. In most cases, that means all the instructions
746/// in the block are isPredicable(). Also checks if the block contains any
747/// instruction which can clobber a predicate (e.g. condition code register).
748/// If so, the block is not predicable unless it's the last instruction.
749void IfConverter::ScanInstructions(BBInfo &BBI,
750 MachineBasicBlock::iterator &Begin,
Kyle Buttce0196d2016-08-19 18:17:04 +0000751 MachineBasicBlock::iterator &End) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000752 if (BBI.IsDone || BBI.IsUnpredicable)
753 return;
754
755 bool AlreadyPredicated = !BBI.Predicate.empty();
756
Evan Cheng4dd31a72007-06-11 22:26:22 +0000757 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000758 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000759 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000760 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000761 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000762 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000763 continue;
764
Justin Lebar7dba2e02016-04-15 01:38:41 +0000765 // It's unsafe to duplicate convergent instructions in this context, so set
766 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
767 // following CFG, which is subject to our "simple" transformation.
768 //
769 // BB0 // if (c1) goto BB1; else goto BB2;
770 // / \
771 // BB1 |
772 // | BB2 // if (c2) goto TBB; else goto FBB;
773 // | / |
774 // | / |
775 // TBB |
776 // | |
777 // | FBB
778 // |
779 // exit
780 //
781 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
782 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
783 // TBB contains a convergent instruction. This is safe iff doing so does
784 // not add a control-flow dependency to the convergent instruction -- i.e.,
785 // it's safe iff the set of control flows that leads us to the convergent
786 // instruction does not get smaller after the transformation.
787 //
788 // Originally we executed TBB if c1 || c2. After the transformation, there
789 // are two copies of TBB's instructions. We get to the first if c1, and we
790 // get to the second if !c1 && c2.
791 //
792 // There are clearly fewer ways to satisfy the condition "c1" than
793 // "c1 || c2". Since we've shrunk the set of control flows which lead to
794 // our convergent instruction, the transformation is unsafe.
795 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000796 BBI.CannotBeCopied = true;
797
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000798 bool isPredicated = TII->isPredicated(MI);
799 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000800
Joey Goulya5153cb2013-09-09 14:21:49 +0000801 // A conditional branch is not predicable, but it may be eliminated.
802 if (isCondBr)
803 continue;
804
805 if (!isPredicated) {
806 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000807 unsigned ExtraPredCost = TII->getPredicationCost(MI);
808 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000809 if (NumCycles > 1)
810 BBI.ExtraCost += NumCycles-1;
811 BBI.ExtraCost2 += ExtraPredCost;
812 } else if (!AlreadyPredicated) {
813 // FIXME: This instruction is already predicated before the
814 // if-conversion pass. It's probably something like a conditional move.
815 // Mark this block unpredicable for now.
816 BBI.IsUnpredicable = true;
817 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000818 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000819
820 if (BBI.ClobbersPred && !isPredicated) {
821 // Predicate modification instruction should end the block (except for
822 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000823 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000824 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000825 BBI.IsUnpredicable = true;
826 return;
827 }
828
Evan Chengfbc73092007-07-10 17:50:43 +0000829 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
830 // still potentially predicable.
831 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000832 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000833 BBI.ClobbersPred = true;
834
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000835 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000836 BBI.IsUnpredicable = true;
837 return;
838 }
839 }
840}
841
Matthias Braun2c931792016-08-17 02:51:57 +0000842/// Determine if the block is a suitable candidate to be predicated by the
843/// specified predicate.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000844bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000845 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt5b104832016-08-19 18:17:06 +0000846 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000847 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt5b104832016-08-19 18:17:06 +0000848 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000849 return false;
850
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000851 // If it is already predicated but we couldn't analyze its terminator, the
852 // latter might fallthrough, but we can't determine where to.
853 // Conservatively avoid if-converting again.
854 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
855 return false;
856
Quentin Colombetbdab2272013-07-24 20:20:37 +0000857 // If it is already predicated, check if the new predicate subsumes
858 // its predicate.
859 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000860 return false;
861
Kyle Butt5b104832016-08-19 18:17:06 +0000862 if (BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000863 if (!isTriangle)
864 return false;
865
Bob Wilson2371f4f2009-05-13 23:25:24 +0000866 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000867 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
868 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000869 if (RevBranch) {
870 if (TII->ReverseBranchCondition(Cond))
871 return false;
872 }
873 if (TII->ReverseBranchCondition(RevPred) ||
874 !TII->SubsumesPredicate(Cond, RevPred))
875 return false;
876 }
877
878 return true;
879}
880
Matthias Braun2c931792016-08-17 02:51:57 +0000881/// Analyze the structure of the sub-CFG starting from the specified block.
882/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000883void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +0000884 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000885 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +0000886 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000887 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +0000888
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000889 /// This flag is true if MBB's successors have been analyzed.
890 bool SuccsAnalyzed;
891 };
Evan Cheng0f745da2007-05-18 00:20:58 +0000892
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000893 // Push MBB to the stack.
894 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000895
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000896 while (!BBStack.empty()) {
897 BBState &State = BBStack.back();
898 MachineBasicBlock *BB = State.MBB;
899 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +0000900
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000901 if (!State.SuccsAnalyzed) {
902 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
903 BBStack.pop_back();
904 continue;
905 }
Evan Cheng9030b982007-06-06 10:16:17 +0000906
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000907 BBI.BB = BB;
908 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000909
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000910 AnalyzeBranches(BBI);
911 MachineBasicBlock::iterator Begin = BBI.BB->begin();
912 MachineBasicBlock::iterator End = BBI.BB->end();
913 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +0000914
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000915 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
916 // not considered for ifcvt anymore.
917 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
918 BBI.IsBeingAnalyzed = false;
919 BBI.IsAnalyzed = true;
920 BBStack.pop_back();
921 continue;
922 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000923
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000924 // Do not ifcvt if either path is a back edge to the entry block.
925 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
926 BBI.IsBeingAnalyzed = false;
927 BBI.IsAnalyzed = true;
928 BBStack.pop_back();
929 continue;
930 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000931
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000932 // Do not ifcvt if true and false fallthrough blocks are the same.
933 if (!BBI.FalseBB) {
934 BBI.IsBeingAnalyzed = false;
935 BBI.IsAnalyzed = true;
936 BBStack.pop_back();
937 continue;
938 }
Evan Cheng7783f822007-06-08 09:36:04 +0000939
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000940 // Push the False and True blocks to the stack.
941 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +0000942 BBStack.push_back(*BBI.FalseBB);
943 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000944 continue;
945 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000946
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000947 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
948 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +0000949
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000950 if (TrueBBI.IsDone && FalseBBI.IsDone) {
951 BBI.IsBeingAnalyzed = false;
952 BBI.IsAnalyzed = true;
953 BBStack.pop_back();
954 continue;
955 }
956
957 SmallVector<MachineOperand, 4>
958 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
959 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
960
961 unsigned Dups = 0;
962 unsigned Dups2 = 0;
963 bool TNeedSub = !TrueBBI.Predicate.empty();
964 bool FNeedSub = !FalseBBI.Predicate.empty();
965 bool Enqueued = false;
966
967 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
968
Kyle Butt5b104832016-08-19 18:17:06 +0000969 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Kyle Buttce0196d2016-08-19 18:17:04 +0000970 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Kyle Butt5b104832016-08-19 18:17:06 +0000971 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Kyle Buttce0196d2016-08-19 18:17:04 +0000972 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Kyle Butt5b104832016-08-19 18:17:06 +0000973 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
974 Prediction) &&
975 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
976 FeasibilityAnalysis(FalseBBI, RevCond)) {
977 // Diamond:
978 // EBB
979 // / \_
980 // | |
981 // TBB FBB
982 // \ /
983 // TailBB
984 // Note TailBB can be empty.
985 Tokens.push_back(llvm::make_unique<IfcvtToken>(
986 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2));
987 Enqueued = true;
Evan Cheng3a51c852007-06-16 09:34:52 +0000988 }
989
Akira Hatanaka14348aa2015-06-24 20:34:35 +0000990 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
991 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
992 TrueBBI.ExtraCost2, Prediction) &&
993 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
994 // Triangle:
995 // EBB
996 // | \_
997 // | |
998 // | TBB
999 // | /
1000 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001001 Tokens.push_back(
1002 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001003 Enqueued = true;
1004 }
1005
1006 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1007 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1008 TrueBBI.ExtraCost2, Prediction) &&
1009 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001010 Tokens.push_back(
1011 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001012 Enqueued = true;
1013 }
1014
1015 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1016 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1017 TrueBBI.ExtraCost2, Prediction) &&
1018 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1019 // Simple (split, no rejoin):
1020 // EBB
1021 // | \_
1022 // | |
1023 // | TBB---> exit
1024 // |
1025 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001026 Tokens.push_back(
1027 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001028 Enqueued = true;
1029 }
1030
1031 if (CanRevCond) {
1032 // Try the other path...
1033 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1034 Prediction.getCompl()) &&
1035 MeetIfcvtSizeLimit(*FalseBBI.BB,
1036 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1037 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1038 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001039 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1040 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001041 Enqueued = true;
1042 }
1043
1044 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1045 Prediction.getCompl()) &&
1046 MeetIfcvtSizeLimit(*FalseBBI.BB,
1047 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001048 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001049 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001050 Tokens.push_back(
1051 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001052 Enqueued = true;
1053 }
1054
1055 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1056 MeetIfcvtSizeLimit(*FalseBBI.BB,
1057 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1058 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1059 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001060 Tokens.push_back(
1061 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001062 Enqueued = true;
1063 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001064 }
1065
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001066 BBI.IsEnqueued = Enqueued;
1067 BBI.IsBeingAnalyzed = false;
1068 BBI.IsAnalyzed = true;
1069 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001070 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001071}
1072
Matthias Braun2c931792016-08-17 02:51:57 +00001073/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001074void IfConverter::AnalyzeBlocks(
1075 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001076 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001077 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001078
Evan Cheng20e05992007-06-01 00:12:12 +00001079 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001080 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001081}
1082
Matthias Braun2c931792016-08-17 02:51:57 +00001083/// Returns true either if ToMBB is the next block after MBB or that all the
1084/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001085static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1086 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001087 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001088 MachineFunction::iterator TI = ToMBB.getIterator();
1089 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001090 while (I != TI) {
1091 // Check isSuccessor to avoid case where the next block is empty, but
1092 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001093 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001094 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001095 PI = I++;
1096 }
Evan Cheng312b7232007-06-04 06:47:22 +00001097 return true;
Evan Chenge26c0912007-05-21 22:22:58 +00001098}
1099
Matthias Braun2c931792016-08-17 02:51:57 +00001100/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1101/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001102void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1103 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001104 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001105 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001106 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001107 PBBI.IsAnalyzed = false;
1108 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001109 }
1110}
1111
Matthias Braun2c931792016-08-17 02:51:57 +00001112/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001113static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001114 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001115 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001116 SmallVector<MachineOperand, 0> NoCond;
Matthias Braun08f47042016-08-17 02:52:01 +00001117 TII->InsertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001118}
1119
Matthias Braun2c931792016-08-17 02:51:57 +00001120/// Remove true / false edges if either / both are no longer successors.
Evan Cheng288f1542007-06-08 22:01:07 +00001121void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +00001122 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001123 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001124 if (!TII->analyzeBranch(*BBI.BB, TBB, FBB, Cond))
Evan Cheng0598b2d2007-06-18 22:44:57 +00001125 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +00001126}
1127
Matthias Braund616ccc2013-10-11 19:04:37 +00001128/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001129/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001130static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Jonas Paulsson196986c2016-08-03 05:46:35 +00001131 const TargetRegisterInfo *TRI = MI.getParent()->getParent()
1132 ->getSubtarget().getRegisterInfo();
1133
1134 // Before stepping forward past MI, remember which regs were live
1135 // before MI. This is needed to set the Undef flag only when reg is
1136 // dead.
1137 SparseSet<unsigned> LiveBeforeMI;
1138 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001139 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001140 LiveBeforeMI.insert(Reg);
1141
Pete Cooper7605e372015-05-05 20:14:22 +00001142 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001143 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001144
Pete Cooper7605e372015-05-05 20:14:22 +00001145 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001146 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001147 // FIXME: Const cast here is nasty, but better than making StepForward
1148 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001149 unsigned Reg = Clobber.first;
1150 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001151 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +00001152 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001153 if (Op.isRegMask()) {
1154 // First handle regmasks. They clobber any entries in the mask which
1155 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001156 if (LiveBeforeMI.count(Reg))
1157 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001158
1159 // We also need to add an implicit def of this register for the later
1160 // use to read from.
1161 // For the register allocator to have allocated a register clobbered
1162 // by the call which is used later, it must be the case that
1163 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001164 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001165 continue;
1166 }
1167 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001168 if (Op.isDead()) {
1169 // If we found a dead def, but it needs to be live, then remove the dead
1170 // flag.
1171 if (Redefs.contains(Op.getReg()))
1172 Op.setIsDead(false);
1173 }
Matthias Braun08f47042016-08-17 02:52:01 +00001174 if (LiveBeforeMI.count(Reg))
1175 MIB.addReg(Reg, RegState::Implicit);
Matthias Braund616ccc2013-10-11 19:04:37 +00001176 }
1177}
1178
Matthias Braun2c931792016-08-17 02:51:57 +00001179/// Remove kill flags from operands with a registers in the \p DontKill set.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001180static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001181 for (MIBundleOperands O(MI); O.isValid(); ++O) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001182 if (!O->isReg() || !O->isKill())
1183 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001184 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001185 O->setIsKill(false);
1186 }
1187}
1188
Matthias Braun2c931792016-08-17 02:51:57 +00001189/// Walks a range of machine instructions and removes kill flags for registers
1190/// in the \p DontKill set.
Matthias Braund616ccc2013-10-11 19:04:37 +00001191static void RemoveKills(MachineBasicBlock::iterator I,
1192 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001193 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001194 const MCRegisterInfo &MCRI) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001195 for (MachineInstr &MI : make_range(I, E))
1196 RemoveKills(MI, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001197}
1198
Matthias Braun2c931792016-08-17 02:51:57 +00001199/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001200bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001201 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1202 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1203 BBInfo *CvtBBI = &TrueBBI;
1204 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001205
Owen Anderson4f6bf042008-08-14 22:49:33 +00001206 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001207 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001208 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001209
Matthias Braun08f47042016-08-17 02:52:01 +00001210 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1211 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001212 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001213 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001214 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001215 BBI.IsAnalyzed = false;
1216 CvtBBI->IsAnalyzed = false;
1217 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001218 }
Evan Chengd0e66912007-05-23 07:23:16 +00001219
Matthias Braun08f47042016-08-17 02:52:01 +00001220 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001221 // Conservatively abort if-conversion if BB's address is taken.
1222 return false;
1223
Evan Cheng3a51c852007-06-16 09:34:52 +00001224 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001225 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001226 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001227
Bob Wilson45814342010-06-19 05:33:57 +00001228 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001229 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001230 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001231 Redefs.addLiveIns(CvtMBB);
1232 Redefs.addLiveIns(NextMBB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001233
1234 // Compute a set of registers which must not be killed by instructions in
1235 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001236 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001237 DontKill.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001238
Matthias Braun08f47042016-08-17 02:52:01 +00001239 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001240 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001241 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001242 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001243 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001244
1245 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1246 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001247 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001248 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001249 RemoveKills(CvtMBB.begin(), CvtMBB.end(), DontKill, *TRI);
1250 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001251
Evan Cheng92fb5452007-06-15 07:36:12 +00001252 // Merge converted block into entry block.
1253 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1254 MergeBlocks(BBI, *CvtBBI);
1255 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001256
Evan Chenge4ec9182007-06-06 02:08:52 +00001257 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001258 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1259 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001260 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001261 // Now ifcvt'd block will look like this:
1262 // BB:
1263 // ...
1264 // t, f = cmp
1265 // if t op
1266 // b BBf
1267 //
1268 // We cannot further ifcvt this block because the unconditional branch
1269 // will have to be predicated on the new condition, that will not be
1270 // available if cmp executes.
1271 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001272 }
Evan Chenge26c0912007-05-21 22:22:58 +00001273
Evan Cheng288f1542007-06-08 22:01:07 +00001274 RemoveExtraEdges(BBI);
1275
Evan Chengd0e66912007-05-23 07:23:16 +00001276 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001277 if (!IterIfcvt)
1278 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001279 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001280 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001281
1282 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001283 return true;
1284}
1285
Matthias Braun2c931792016-08-17 02:51:57 +00001286/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001287bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001288 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001289 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1290 BBInfo *CvtBBI = &TrueBBI;
1291 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001292 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001293
Owen Anderson4f6bf042008-08-14 22:49:33 +00001294 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001295 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001296 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001297
Matthias Braun08f47042016-08-17 02:52:01 +00001298 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1299 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001300 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001301 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001302 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001303 BBI.IsAnalyzed = false;
1304 CvtBBI->IsAnalyzed = false;
1305 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001306 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001307
Matthias Braun08f47042016-08-17 02:52:01 +00001308 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001309 // Conservatively abort if-conversion if BB's address is taken.
1310 return false;
1311
Evan Cheng3a51c852007-06-16 09:34:52 +00001312 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001313 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001314 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001315
Evan Cheng3a51c852007-06-16 09:34:52 +00001316 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001317 if (ReverseBranchCondition(*CvtBBI)) {
1318 // BB has been changed, modify its predecessors (except for this
1319 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001320 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001321 if (PBB == BBI.BB)
1322 continue;
1323 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1324 if (PBBI.IsEnqueued) {
1325 PBBI.IsAnalyzed = false;
1326 PBBI.IsEnqueued = false;
1327 }
Evan Chengadd97762007-06-14 23:34:09 +00001328 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001329 }
1330 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001331
Bob Wilson45814342010-06-19 05:33:57 +00001332 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001333 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001334 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001335 Redefs.addLiveIns(CvtMBB);
1336 Redefs.addLiveIns(NextMBB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001337
Andrew Trick276dd452013-10-14 20:45:17 +00001338 DontKill.clear();
1339
Craig Topperc0196b12014-04-14 00:51:57 +00001340 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001341 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001342
Manman Renb6819182014-01-29 23:18:47 +00001343 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001344 // Get probabilities before modifying CvtMBB and BBI.BB.
1345 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1346 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1347 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1348 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001349 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001350
Matthias Braun08f47042016-08-17 02:52:01 +00001351 if (CvtMBB.pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001352 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001353 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001354 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001355 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001356
1357 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1358 // explicitly remove CvtBBI as a successor.
Matthias Braun08f47042016-08-17 02:52:01 +00001359 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001360 } else {
1361 // Predicate the 'true' block after removing its branch.
Matthias Braun08f47042016-08-17 02:52:01 +00001362 CvtBBI->NonPredSize -= TII->RemoveBranch(CvtMBB);
1363 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001364
Evan Cheng0598b2d2007-06-18 22:44:57 +00001365 // Now merge the entry of the triangle with the true block.
1366 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001367 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001368 }
1369
Evan Cheng312b7232007-06-04 06:47:22 +00001370 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001371 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001372 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1373 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001374 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001375 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001376
Cong Houd97c1002015-12-01 05:29:22 +00001377 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001378 // NewNext = New_Prob(BBI.BB, NextMBB) =
1379 // Prob(BBI.BB, NextMBB) +
1380 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001381 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001382 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1383 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001384 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001385 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001386 if (NewTrueBBIter != BBI.BB->succ_end())
1387 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001388
1389 auto NewFalse = BBCvt * CvtFalse;
1390 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1391 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001392 }
Evan Cheng7783f822007-06-08 09:36:04 +00001393
1394 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001395 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001396 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001397 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001398 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001399 if (!isFallThrough) {
1400 // Only merge them if the true block does not fallthrough to the false
1401 // block. By not merging them, we make it possible to iteratively
1402 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001403 if (!HasEarlyExit &&
Matthias Braun08f47042016-08-17 02:52:01 +00001404 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
1405 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001406 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001407 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001408 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001409 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001410 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001411 }
Evan Cheng7783f822007-06-08 09:36:04 +00001412 // Mixed predicated and unpredicated code. This cannot be iteratively
1413 // predicated.
1414 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001415 }
Evan Chenge26c0912007-05-21 22:22:58 +00001416
Evan Cheng288f1542007-06-08 22:01:07 +00001417 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001418
Evan Chengd0e66912007-05-23 07:23:16 +00001419 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001420 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001421 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001422 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001423 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001424 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001425 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001426
1427 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001428 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001429}
1430
Kyle Buttce0196d2016-08-19 18:17:04 +00001431/// If convert a diamond sub-CFG.
Kyle Buttce0196d2016-08-19 18:17:04 +00001432bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt5b104832016-08-19 18:17:06 +00001433 unsigned NumDups1, unsigned NumDups2) {
Kyle Buttce0196d2016-08-19 18:17:04 +00001434 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1435 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1436 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1437 // True block must fall through or end with an unanalyzable terminator.
1438 if (!TailBB) {
1439 if (blockAlwaysFallThrough(TrueBBI))
1440 TailBB = FalseBBI.TrueBB;
1441 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1442 }
Evan Chenge26c0912007-05-21 22:22:58 +00001443
Evan Cheng51eb2c32007-06-18 08:37:25 +00001444 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Buttce0196d2016-08-19 18:17:04 +00001445 TrueBBI.BB->pred_size() > 1 ||
1446 FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001447 // Something has changed. It's no longer safe to predicate these blocks.
1448 BBI.IsAnalyzed = false;
1449 TrueBBI.IsAnalyzed = false;
1450 FalseBBI.IsAnalyzed = false;
1451 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001452 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001453
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001454 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1455 // Conservatively abort if-conversion if either BB has its address taken.
1456 return false;
1457
Bob Wilson1e5da552010-06-29 00:55:23 +00001458 // Put the predicated instructions from the 'true' block before the
1459 // instructions from the 'false' block, unless the true block would clobber
1460 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001461 BBInfo *BBI1 = &TrueBBI;
1462 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001463 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001464 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001465 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001466 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1467 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001468
Evan Cheng3a51c852007-06-16 09:34:52 +00001469 // Figure out the more profitable ordering.
1470 bool DoSwap = false;
Kyle Butt5b104832016-08-19 18:17:06 +00001471 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001472 DoSwap = true;
Kyle Butt5b104832016-08-19 18:17:06 +00001473 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001474 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001475 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001476 }
1477 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001478 std::swap(BBI1, BBI2);
1479 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001480 }
Evan Cheng79484222007-06-05 23:46:14 +00001481
Evan Cheng51eb2c32007-06-18 08:37:25 +00001482 // Remove the conditional branch from entry to the blocks.
1483 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1484
Matthias Braun08f47042016-08-17 02:52:01 +00001485 MachineBasicBlock &MBB1 = *BBI1->BB;
1486 MachineBasicBlock &MBB2 = *BBI2->BB;
1487
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001488 // Initialize the Redefs:
1489 // - BB2 live-in regs need implicit uses before being redefined by BB1
1490 // instructions.
1491 // - BB1 live-out regs need implicit uses before being redefined by BB2
1492 // instructions. We start with BB1 live-ins so we have the live-out regs
1493 // after tracking the BB1 instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001494 Redefs.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001495 Redefs.addLiveIns(MBB1);
1496 Redefs.addLiveIns(MBB2);
Evan Chengf128bdc2010-06-16 07:35:02 +00001497
Evan Cheng51eb2c32007-06-18 08:37:25 +00001498 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001499 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001500 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1501 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001502 BBI1->NonPredSize -= NumDups1;
1503 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001504
1505 // Skip past the dups on each side separately since there may be
1506 // differing dbg_value entries.
1507 for (unsigned i = 0; i < NumDups1; ++DI1) {
1508 if (!DI1->isDebugValue())
1509 ++i;
1510 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001511 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001512 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001513 if (!DI2->isDebugValue())
1514 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001515 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001516
Matthias Braund616ccc2013-10-11 19:04:37 +00001517 // Compute a set of registers which must not be killed by instructions in BB1:
1518 // This is everything used+live in BB2 after the duplicated instructions. We
1519 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001520 DontKill.init(TRI);
Matthias Braun08f47042016-08-17 02:52:01 +00001521 for (const MachineInstr &MI :
1522 make_range(MBB2.rbegin(), MachineBasicBlock::reverse_iterator(DI2)))
Matthias Braunb1e05582016-08-17 02:51:59 +00001523 DontKill.stepBackward(MI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001524
Matthias Braun08f47042016-08-17 02:52:01 +00001525 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
Pete Cooper7605e372015-05-05 20:14:22 +00001526 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
Matthias Braunb1e05582016-08-17 02:51:59 +00001527 Redefs.stepForward(MI, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001528 }
Matthias Braun08f47042016-08-17 02:52:01 +00001529 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1530 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001531
Kyle Buttce0196d2016-08-19 18:17:04 +00001532 // Remove branch from the 'true' block, unless it was not analyzable.
1533 // Non-analyzable branches need to be preserved, since in such cases,
1534 // the CFG structure is not an actual diamond (the join block may not
1535 // be present).
1536 if (BBI1->IsBrAnalyzable)
1537 BBI1->NonPredSize -= TII->RemoveBranch(MBB1);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001538 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001539 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001540 for (unsigned i = 0; i != NumDups2; ) {
1541 // NumDups2 only counted non-dbg_value instructions, so this won't
1542 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001543 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001544 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001545 // skip dbg_value instructions
1546 if (!DI1->isDebugValue())
1547 ++i;
1548 }
Matthias Braun08f47042016-08-17 02:52:01 +00001549 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001550
Matthias Braund616ccc2013-10-11 19:04:37 +00001551 // Kill flags in the true block for registers living into the false block
1552 // must be removed.
Matthias Braun08f47042016-08-17 02:52:01 +00001553 RemoveKills(MBB1.begin(), MBB1.end(), DontKill, *TRI);
Matthias Braund616ccc2013-10-11 19:04:37 +00001554
Kyle Buttce0196d2016-08-19 18:17:04 +00001555 // Remove 'false' block branch (unless it was not analyzable), and find
1556 // the last instruction to predicate.
1557 if (BBI2->IsBrAnalyzable)
1558 BBI2->NonPredSize -= TII->RemoveBranch(MBB2);
1559 DI2 = MBB2.end();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001560 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001561 // NumDups2 only counted non-dbg_value instructions, so this won't
1562 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001563 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001564 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001565 // skip dbg_value instructions
1566 if (!DI2->isDebugValue())
1567 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001568 }
Evan Cheng4266a792011-12-19 22:01:30 +00001569
1570 // Remember which registers would later be defined by the false block.
1571 // This allows us not to predicate instructions in the true block that would
1572 // later be re-defined. That is, rather than
1573 // subeq r0, r1, #1
1574 // addne r0, r1, #1
1575 // generate:
1576 // sub r0, r1, #1
1577 // addne r0, r1, #1
1578 SmallSet<unsigned, 4> RedefsByFalse;
1579 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001580 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1581 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001582 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001583 continue;
1584 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001585 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001586 if (!MO.isReg())
1587 continue;
1588 unsigned Reg = MO.getReg();
1589 if (!Reg)
1590 continue;
1591 if (MO.isDef()) {
1592 Defs.push_back(Reg);
1593 } else if (!RedefsByFalse.count(Reg)) {
1594 // These are defined before ctrl flow reach the 'false' instructions.
1595 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001596 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1597 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001598 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001599 }
1600 }
1601
Matthias Braunb1e05582016-08-17 02:51:59 +00001602 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001603 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001604 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1605 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001606 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001607 }
1608 }
1609 }
1610 }
1611
1612 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001613 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001614
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001615 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1616 // a non-predicated in BBI2, then we don't want to predicate the one from
1617 // BBI2. The reason is that if we merged these blocks, we would end up with
1618 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001619 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1620 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1621 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1622 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1623 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001624 --DI2;
1625 }
1626
Evan Cheng4266a792011-12-19 22:01:30 +00001627 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001628 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001629
Evan Cheng0598b2d2007-06-18 22:44:57 +00001630 // Merge the true block into the entry of the diamond.
Kyle Buttce0196d2016-08-19 18:17:04 +00001631 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1632 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001633
Bob Wilson2371f4f2009-05-13 23:25:24 +00001634 // If the if-converted block falls through or unconditionally branches into
1635 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001636 // fold the tail block in as well. Otherwise, unless it falls through to the
1637 // tail, add a unconditional branch to it.
1638 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001639 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001640 bool CanMergeTail = !TailBBI.HasFallThrough &&
1641 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001642 // The if-converted block can still have a predicated terminator
1643 // (e.g. a predicated return). If that is the case, we cannot merge
1644 // it with the tail block.
1645 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001646 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001647 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001648 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1649 // check if there are any other predecessors besides those.
1650 unsigned NumPreds = TailBB->pred_size();
1651 if (NumPreds > 1)
1652 CanMergeTail = false;
1653 else if (NumPreds == 1 && CanMergeTail) {
1654 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Buttce0196d2016-08-19 18:17:04 +00001655 if (*PI != &MBB1 && *PI != &MBB2)
Bob Wilson1e5da552010-06-29 00:55:23 +00001656 CanMergeTail = false;
1657 }
1658 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001659 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001660 TailBBI.IsDone = true;
1661 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001662 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001663 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001664 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001665 }
Evan Chenge26c0912007-05-21 22:22:58 +00001666 }
1667
Bob Wilson1e5da552010-06-29 00:55:23 +00001668 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1669 // which can happen here if TailBB is unanalyzable and is merged, so
1670 // explicitly remove BBI1 and BBI2 as successors.
Kyle Buttce0196d2016-08-19 18:17:04 +00001671 BBI.BB->removeSuccessor(&MBB1);
1672 BBI.BB->removeSuccessor(&MBB2, true);
Evan Cheng288f1542007-06-08 22:01:07 +00001673 RemoveExtraEdges(BBI);
1674
Evan Cheng79484222007-06-05 23:46:14 +00001675 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001676 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001677 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001678
1679 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001680 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001681}
1682
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001683static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001684 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001685 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001686 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001687 return false;
1688
Matthias Braunb1e05582016-08-17 02:51:59 +00001689 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001690 if (!MO.isReg())
1691 continue;
1692 unsigned Reg = MO.getReg();
1693 if (!Reg)
1694 continue;
1695 if (MO.isDef() && !LaterRedefs.count(Reg))
1696 return false;
1697 }
1698
1699 return true;
1700}
1701
Matthias Braun2c931792016-08-17 02:51:57 +00001702/// Predicate instructions from the start of the block to the specified end with
1703/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001704void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001705 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001706 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001707 SmallSet<unsigned, 4> *LaterRedefs) {
1708 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001709 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001710 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001711 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001712 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001713 // It may be possible not to predicate an instruction if it's the 'true'
1714 // side of a diamond and the 'false' side may re-define the instruction's
1715 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001716 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001717 AnyUnpred = true;
1718 continue;
1719 }
1720 // If any instruction is predicated, then every instruction after it must
1721 // be predicated.
1722 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001723 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001724#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001725 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001726#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001727 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001728 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001729
Bob Wilson45814342010-06-19 05:33:57 +00001730 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001731 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001732 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001733 }
Evan Chengd0e66912007-05-23 07:23:16 +00001734
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001735 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001736
Evan Cheng92fb5452007-06-15 07:36:12 +00001737 BBI.IsAnalyzed = false;
1738 BBI.NonPredSize = 0;
1739
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001740 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001741 if (AnyUnpred)
1742 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001743}
1744
Matthias Braun2c931792016-08-17 02:51:57 +00001745/// Copy and predicate instructions from source BB to the destination block.
1746/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00001747void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001748 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001749 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001750 MachineFunction &MF = *ToBBI.BB->getParent();
1751
Matthias Braun08f47042016-08-17 02:52:01 +00001752 MachineBasicBlock &FromMBB = *FromBBI.BB;
1753 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001754 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001755 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001756 break;
1757
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001758 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001759 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001760 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001761 unsigned ExtraPredCost = TII->getPredicationCost(I);
1762 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001763 if (NumCycles > 1)
1764 ToBBI.ExtraCost += NumCycles-1;
1765 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001766
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001767 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001768 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001769#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001770 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001771#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001772 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001773 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001774 }
1775
Bob Wilson45814342010-06-19 05:33:57 +00001776 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001777 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001778 UpdatePredRedefs(*MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001779
1780 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001781 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001782 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001783 }
1784
Bob Wilson1e5da552010-06-29 00:55:23 +00001785 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00001786 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
1787 FromMBB.succ_end());
1788 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001789 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001790
Matthias Braunb1e05582016-08-17 02:51:59 +00001791 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00001792 // Fallthrough edge can't be transferred.
1793 if (Succ == FallThrough)
1794 continue;
1795 ToBBI.BB->addSuccessor(Succ);
1796 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001797 }
1798
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001799 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1800 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001801
1802 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1803 ToBBI.IsAnalyzed = false;
1804
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001805 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001806}
1807
Matthias Braun2c931792016-08-17 02:51:57 +00001808/// Move all instructions from FromBB to the end of ToBB. This will leave
1809/// FromBB as an empty block, so remove all of its successor edges except for
1810/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
1811/// being moved, add those successor edges to ToBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00001812void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00001813 MachineBasicBlock &FromMBB = *FromBBI.BB;
1814 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001815 "Removing a BB whose address is taken!");
1816
Matthias Braun08f47042016-08-17 02:52:01 +00001817 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001818 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00001819 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001820 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00001821 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001822
1823 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00001824 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001825 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00001826 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00001827
Cong Houb9e8d482015-12-17 01:29:08 +00001828 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
1829 // unknown probabilities into known ones.
1830 // FIXME: This usage is too tricky and in the future we would like to
1831 // eliminate all unknown probabilities in MBB.
1832 ToBBI.BB->normalizeSuccProbs();
1833
Matthias Braun08f47042016-08-17 02:52:01 +00001834 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
1835 FromMBB.succ_end());
1836 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00001837 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00001838 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
1839 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00001840 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00001841 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
1842 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
1843 // Set the edge probability from ToBBI.BB to FromMBB to zero to avoid the
Cong Houd97c1002015-12-01 05:29:22 +00001844 // edge probability being merged to other edges when this edge is removed
1845 // later.
Matthias Braun08f47042016-08-17 02:52:01 +00001846 ToBBI.BB->setSuccProbability(find(ToBBI.BB->successors(), &FromMBB),
David Majnemer42531262016-08-12 03:55:06 +00001847 BranchProbability::getZero());
Cong Houd97c1002015-12-01 05:29:22 +00001848 }
1849
Matthias Braunb1e05582016-08-17 02:51:59 +00001850 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00001851 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001852 if (Succ == FallThrough)
1853 continue;
Cong Houd40105d2015-09-18 20:22:41 +00001854
Cong Houd97c1002015-12-01 05:29:22 +00001855 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00001856 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001857 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00001858 // which is a portion of the edge probability from FromMBB to Succ. The
1859 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00001860 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00001861 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001862
Matthias Braun08f47042016-08-17 02:52:01 +00001863 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
1864 // only happens when if-converting a diamond CFG and FromMBB is the
1865 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
1866 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00001867 // new successors.
1868 if (!To2FromProb.isZero())
1869 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00001870 }
1871
Matthias Braun08f47042016-08-17 02:52:01 +00001872 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00001873
1874 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00001875 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00001876 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00001877 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00001878 // don't have to set C as A's successor as it already is. We only need to
1879 // update the edge probability on A->C. Note that B will not be
1880 // immediately removed from A's successors. It is possible that B->D is
1881 // not removed either if D is a fallthrough of B. Later the edge A->D
1882 // (generated here) and B->D will be combined into one edge. To maintain
1883 // correct edge probability of this combined edge, we need to set the edge
1884 // probability of A->B to zero, which is already done above. The edge
1885 // probability on A->D is calculated by scaling the original probability
1886 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00001887 //
1888 // Before ifcvt: After ifcvt (assume B->D is kept):
1889 //
1890 // A A
1891 // /| /|\
1892 // / B / B|
1893 // | /| | ||
1894 // |/ | | |/
1895 // C D C D
1896 //
1897 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00001898 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00001899 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00001900 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001901 else
Cong Houd97c1002015-12-01 05:29:22 +00001902 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00001903 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001904 }
1905
Bob Wilson2371f4f2009-05-13 23:25:24 +00001906 // Now FromBBI always falls through to the next block!
Matthias Braun08f47042016-08-17 02:52:01 +00001907 if (NBB && !FromMBB.isSuccessor(NBB))
1908 FromMBB.addSuccessor(NBB);
Evan Cheng288f1542007-06-08 22:01:07 +00001909
Cong Houc1069892015-12-13 09:26:17 +00001910 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
1911 // we've done above.
1912 ToBBI.BB->normalizeSuccProbs();
1913
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001914 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001915 FromBBI.Predicate.clear();
1916
Evan Chengd0e66912007-05-23 07:23:16 +00001917 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001918 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001919 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001920 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001921 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001922 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001923
Evan Cheng4dd31a72007-06-11 22:26:22 +00001924 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001925 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001926 ToBBI.IsAnalyzed = false;
1927 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001928}
Akira Hatanaka4a616192015-06-08 18:50:43 +00001929
1930FunctionPass *
1931llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00001932 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00001933}