blob: 0d59c72cb8f77ff38e8af95a1c5d83d85b703fa3 [file] [log] [blame]
Evan Chengf5e53a52007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Chengf5e53a52007-05-16 02:00:57 +000014#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/CodeGen/LivePhysRegs.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000020#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000021#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000025#include "llvm/CodeGen/MachineRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000026#include "llvm/CodeGen/TargetSchedule.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000027#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000028#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000029#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000034#include "llvm/Target/TargetSubtargetInfo.h"
35
Evan Chengf5e53a52007-05-16 02:00:57 +000036using namespace llvm;
37
Chandler Carruth1b9dde02014-04-22 02:02:50 +000038#define DEBUG_TYPE "ifcvt"
39
Chris Lattner769c86b2008-01-07 05:40:58 +000040// Hidden options for help debugging.
41static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
42static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
43static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000044static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000045 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000046static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000047 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000048static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000050static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000051 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000052static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000053 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000054static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-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> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000057 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000058static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
59 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000060
Evan Cheng2117d1f2007-06-09 01:03:43 +000061STATISTIC(NumSimple, "Number of simple if-conversions performed");
62STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
63STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000064STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000065STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
66STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
67STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
68STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000069STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000070STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000071
72namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000073 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000074 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000075 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000076 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000077 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
78 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +000079 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +000080 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +000081 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng4dd31a72007-06-11 22:26:22 +000082 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Chengf5e53a52007-05-16 02:00:57 +000083 };
84
85 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
86 /// if-conversion feasibility analysis. This includes results from
87 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +000088 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +000089 /// diamond shape), its size, whether it's predicable, and whether any
90 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +000091 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +000092 /// IsDone - True if BB is not to be considered for ifcvt.
93 /// IsBeingAnalyzed - True if BB is currently being analyzed.
94 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
95 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
96 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
97 /// HasFallThrough - True if BB may fallthrough to the following BB.
98 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +000099 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000100 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000101 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000102 /// ExtraCost - Extra cost for multi-cycle instructions.
103 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000104 /// BB - Corresponding MachineBasicBlock.
105 /// TrueBB / FalseBB- See AnalyzeBranch().
106 /// BrCond - Conditions for end of block conditional branches.
107 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000108 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000109 bool IsDone : 1;
110 bool IsBeingAnalyzed : 1;
111 bool IsAnalyzed : 1;
112 bool IsEnqueued : 1;
113 bool IsBrAnalyzable : 1;
114 bool HasFallThrough : 1;
115 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000116 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000117 bool ClobbersPred : 1;
Evan Chengd0e66912007-05-23 07:23:16 +0000118 unsigned NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000119 unsigned ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +0000120 unsigned ExtraCost2;
Evan Cheng0f745da2007-05-18 00:20:58 +0000121 MachineBasicBlock *BB;
122 MachineBasicBlock *TrueBB;
123 MachineBasicBlock *FalseBB;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000124 SmallVector<MachineOperand, 4> BrCond;
125 SmallVector<MachineOperand, 4> Predicate;
Evan Cheng3a51c852007-06-16 09:34:52 +0000126 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000127 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
128 HasFallThrough(false), IsUnpredicable(false),
Evan Cheng23402fc2007-06-15 21:18:05 +0000129 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000130 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
131 FalseBB(nullptr) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000132 };
133
Bob Wilson59475732010-06-15 18:19:27 +0000134 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000135 /// BBI - Corresponding BBInfo.
136 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000137 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000138 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000139 /// NumDups - Number of instructions that would be duplicated due
140 /// to this if-conversion. (For diamonds, the number of
141 /// identical instructions at the beginnings of both
142 /// paths).
143 /// NumDups2 - For diamonds, the number of identical instructions
144 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000145 struct IfcvtToken {
146 BBInfo &BBI;
147 IfcvtKind Kind;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000148 bool NeedSubsumption;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000149 unsigned NumDups;
150 unsigned NumDups2;
151 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson2371f4f2009-05-13 23:25:24 +0000152 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000153 };
154
155 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
156 /// basic block number.
157 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000158 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000159
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000160 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000161 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000162 const TargetRegisterInfo *TRI;
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000163 const MachineBlockFrequencyInfo *MBFI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000164 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000165 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000166
Juergen Ributzka310034e2013-12-14 06:52:56 +0000167 LivePhysRegs Redefs;
168 LivePhysRegs DontKill;
Andrew Trick276dd452013-10-14 20:45:17 +0000169
Evan Chengc5adcca2012-06-08 21:53:50 +0000170 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000171 bool MadeChange;
Owen Anderson816e2832009-06-24 23:41:44 +0000172 int FnNum;
Evan Chengf5e53a52007-05-16 02:00:57 +0000173 public:
174 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000175 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
176 initializeIfConverterPass(*PassRegistry::getPassRegistry());
177 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000178
Craig Topper4584cd52014-03-07 09:26:03 +0000179 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000180 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000181 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000182 MachineFunctionPass::getAnalysisUsage(AU);
183 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000184
Craig Topper4584cd52014-03-07 09:26:03 +0000185 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000186
187 private:
Evan Cheng312b7232007-06-04 06:47:22 +0000188 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersonf31f33e2010-10-01 22:45:50 +0000189 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000190 const BranchProbability &Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000191 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000192 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000193 const BranchProbability &Prediction) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000194 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
195 unsigned &Dups1, unsigned &Dups2) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000196 void ScanInstructions(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000197 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
198 std::vector<IfcvtToken*> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000199 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng7783f822007-06-08 09:36:04 +0000200 bool isTriangle = false, bool RevBranch = false);
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000201 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000202 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng288f1542007-06-08 22:01:07 +0000203 void RemoveExtraEdges(BBInfo &BBI);
Evan Cheng3a51c852007-06-16 09:34:52 +0000204 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
205 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000206 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
207 unsigned NumDups1, unsigned NumDups2);
Evan Chengd0e66912007-05-23 07:23:16 +0000208 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000209 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000210 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000211 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000212 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000213 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000214 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000215 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000216
Evan Chengdebf9c52010-11-03 00:45:17 +0000217 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
218 unsigned Cycle, unsigned Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000219 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000220 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000221 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000222 }
223
Evan Chengdebf9c52010-11-03 00:45:17 +0000224 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
225 unsigned TCycle, unsigned TExtra,
226 MachineBasicBlock &FBB,
227 unsigned FCycle, unsigned FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000228 const BranchProbability &Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000229 return TCycle > 0 && FCycle > 0 &&
230 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000231 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000232 }
233
Evan Chengbe9859e2007-06-07 02:12:15 +0000234 // blockAlwaysFallThrough - Block ends without a terminator.
235 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000236 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000237 }
238
Evan Cheng3a51c852007-06-16 09:34:52 +0000239 // IfcvtTokenCmp - Used to sort if-conversion candidates.
240 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000241 int Incr1 = (C1->Kind == ICDiamond)
242 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
243 int Incr2 = (C2->Kind == ICDiamond)
244 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
245 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000246 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000247 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000248 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000249 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000250 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000251 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000252 // Favors diamond over triangle, etc.
253 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
254 return true;
255 else if (C1->Kind == C2->Kind)
256 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
257 }
258 }
259 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000260 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000261 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000262
Evan Chengf5e53a52007-05-16 02:00:57 +0000263 char IfConverter::ID = 0;
264}
265
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000266char &llvm::IfConverterID = IfConverter::ID;
267
Owen Anderson8ac477f2010-10-12 19:48:12 +0000268INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000269INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000270INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000271
Evan Chengf5e53a52007-05-16 02:00:57 +0000272bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher3d4276f2015-01-27 07:31:29 +0000273 const TargetSubtargetInfo &ST = MF.getSubtarget();
274 TLI = ST.getTargetLowering();
275 TII = ST.getInstrInfo();
276 TRI = ST.getRegisterInfo();
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000277 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000278 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000279 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000280 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000281
Evan Chengf5e53a52007-05-16 02:00:57 +0000282 if (!TII) return false;
283
Evan Chengc5adcca2012-06-08 21:53:50 +0000284 PreRegAlloc = MRI->isSSA();
285
286 bool BFChange = false;
287 if (!PreRegAlloc) {
288 // Tail merge tend to expose more if-conversion opportunities.
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000289 BranchFolder BF(true, false, *MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000290 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000291 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000292 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000293
David Greene72e47cd2010-01-04 22:02:01 +0000294 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000295 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000296
297 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000298 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000299 return false;
300 }
David Greene72e47cd2010-01-04 22:02:01 +0000301 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000302
Evan Chengf5e53a52007-05-16 02:00:57 +0000303 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000304 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000305
Evan Cheng3a51c852007-06-16 09:34:52 +0000306 std::vector<IfcvtToken*> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000307 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000308 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
309 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
310 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000311 // Do an initial analysis for each basic block and find all the potential
312 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000313 bool Change = false;
314 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000315 while (!Tokens.empty()) {
316 IfcvtToken *Token = Tokens.back();
317 Tokens.pop_back();
318 BBInfo &BBI = Token->BBI;
319 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000320 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000321 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000322
323 delete Token;
Evan Cheng312b7232007-06-04 06:47:22 +0000324
Evan Cheng4dd31a72007-06-11 22:26:22 +0000325 // If the block has been evicted out of the queue or it has already been
326 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000327 if (BBI.IsDone)
328 BBI.IsEnqueued = false;
329 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000330 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000331
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000332 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000333
Evan Cheng312b7232007-06-04 06:47:22 +0000334 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000335 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000336 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000337 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000338 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000339 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000340 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000341 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
342 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000343 << "): BB#" << BBI.BB->getNumber() << " ("
344 << ((Kind == ICSimpleFalse)
345 ? BBI.FalseBB->getNumber()
346 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000347 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000348 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000349 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000350 if (isFalse) ++NumSimpleFalse;
351 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000352 }
Evan Cheng312b7232007-06-04 06:47:22 +0000353 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000354 }
Evan Chengd0e66912007-05-23 07:23:16 +0000355 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000356 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000357 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000358 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000359 bool isFalse = Kind == ICTriangleFalse;
360 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000361 if (DisableTriangle && !isFalse && !isRev) break;
362 if (DisableTriangleR && !isFalse && isRev) break;
363 if (DisableTriangleF && isFalse && !isRev) break;
364 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000365 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000366 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000367 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000368 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000369 DEBUG(dbgs() << " rev");
370 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000371 << BBI.TrueBB->getNumber() << ",F:"
372 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000373 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000374 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000375 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000376 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000377 if (isRev) ++NumTriangleFRev;
378 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000379 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000380 if (isRev) ++NumTriangleRev;
381 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000382 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000383 }
Evan Chengd0e66912007-05-23 07:23:16 +0000384 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000385 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000386 case ICDiamond: {
Evan Chenge93ccc02007-06-08 19:10:51 +0000387 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000388 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000389 << BBI.TrueBB->getNumber() << ",F:"
390 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes57c65942008-11-04 13:02:59 +0000391 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene72e47cd2010-01-04 22:02:01 +0000392 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000393 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000394 break;
395 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000396 }
397
Evan Cheng312b7232007-06-04 06:47:22 +0000398 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000399
Evan Cheng92fb5452007-06-15 07:36:12 +0000400 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
401 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
402 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000403 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000404 }
Evan Chengd0e66912007-05-23 07:23:16 +0000405
Evan Chengd0e66912007-05-23 07:23:16 +0000406 if (!Change)
407 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000408 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000409 }
Evan Cheng478b8052007-05-18 01:55:58 +0000410
Evan Cheng3a51c852007-06-16 09:34:52 +0000411 // Delete tokens in case of early exit.
412 while (!Tokens.empty()) {
413 IfcvtToken *Token = Tokens.back();
414 Tokens.pop_back();
415 delete Token;
416 }
417
418 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000419 BBAnalysis.clear();
420
Evan Chengcf9e8a92010-06-18 22:17:13 +0000421 if (MadeChange && IfCvtBranchFold) {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000422 BranchFolder BF(false, false, *MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000423 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000424 getAnalysisIfAvailable<MachineModuleInfo>());
425 }
426
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000427 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000428 return MadeChange;
429}
430
Evan Cheng3a51c852007-06-16 09:34:52 +0000431/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
432/// its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000433static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000434 MachineBasicBlock *TrueBB) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000435 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
436 E = BB->succ_end(); SI != E; ++SI) {
437 MachineBasicBlock *SuccBB = *SI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000438 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000439 return SuccBB;
440 }
Craig Topperc0196b12014-04-14 00:51:57 +0000441 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000442}
443
Evan Cheng3a51c852007-06-16 09:34:52 +0000444/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson2371f4f2009-05-13 23:25:24 +0000445/// branch. Swap block's 'true' and 'false' successors.
Evan Cheng312b7232007-06-04 06:47:22 +0000446bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000447 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng312b7232007-06-04 06:47:22 +0000448 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
449 TII->RemoveBranch(*BBI.BB);
Stuart Hastings0125b642010-06-17 22:43:56 +0000450 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000451 std::swap(BBI.TrueBB, BBI.FalseBB);
452 return true;
453 }
454 return false;
455}
456
Evan Cheng2117d1f2007-06-09 01:03:43 +0000457/// getNextBlock - Returns the next block in the function blocks ordering. If
458/// it is the end, returns NULL.
459static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
460 MachineFunction::iterator I = BB;
461 MachineFunction::iterator E = BB->getParent()->end();
462 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000463 return nullptr;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000464 return I;
465}
466
Evan Cheng7783f822007-06-08 09:36:04 +0000467/// ValidSimple - Returns true if the 'true' block (along with its
Evan Cheng3a51c852007-06-16 09:34:52 +0000468/// predecessor) forms a valid simple shape for ifcvt. It also returns the
469/// number of instructions that the ifcvt would need to duplicate if performed
470/// in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000471bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000472 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000473 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000474 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000475 return false;
476
Evan Chenga955c022007-06-19 21:45:13 +0000477 if (TrueBBI.IsBrAnalyzable)
478 return false;
479
Evan Cheng23402fc2007-06-15 21:18:05 +0000480 if (TrueBBI.BB->pred_size() > 1) {
481 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000482 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000483 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000484 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000485 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000486 }
487
Evan Chenga955c022007-06-19 21:45:13 +0000488 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000489}
490
Evan Cheng7783f822007-06-08 09:36:04 +0000491/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000492/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Cheng3a51c852007-06-16 09:34:52 +0000493/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson81051442010-06-15 22:18:54 +0000494/// branches to the 'false' block rather than the other way around. It also
Evan Cheng3a51c852007-06-16 09:34:52 +0000495/// returns the number of instructions that the ifcvt would need to duplicate
496/// if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000497bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000498 bool FalseBranch, unsigned &Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000499 const BranchProbability &Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000500 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000502 return false;
503
Evan Cheng23402fc2007-06-15 21:18:05 +0000504 if (TrueBBI.BB->pred_size() > 1) {
505 if (TrueBBI.CannotBeCopied)
506 return false;
507
Evan Cheng92fb5452007-06-15 07:36:12 +0000508 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000509 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000510 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000511 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000512 --Size;
513 else {
514 MachineBasicBlock *FExit = FalseBranch
515 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
516 if (FExit)
517 // Require a conditional branch
518 ++Size;
519 }
520 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000521 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000522 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000523 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000524 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000525
Evan Cheng7783f822007-06-08 09:36:04 +0000526 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
527 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengbe9859e2007-06-07 02:12:15 +0000528 MachineFunction::iterator I = TrueBBI.BB;
529 if (++I == TrueBBI.BB->getParent()->end())
530 return false;
Evan Cheng7783f822007-06-08 09:36:04 +0000531 TExit = I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000532 }
Evan Cheng7783f822007-06-08 09:36:04 +0000533 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000534}
535
Evan Cheng7783f822007-06-08 09:36:04 +0000536/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengbe9859e2007-06-07 02:12:15 +0000537/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000538bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
539 unsigned &Dups1, unsigned &Dups2) const {
540 Dups1 = Dups2 = 0;
541 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
542 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000543 return false;
544
Evan Cheng2117d1f2007-06-09 01:03:43 +0000545 MachineBasicBlock *TT = TrueBBI.TrueBB;
546 MachineBasicBlock *FT = FalseBBI.TrueBB;
547
548 if (!TT && blockAlwaysFallThrough(TrueBBI))
549 TT = getNextBlock(TrueBBI.BB);
550 if (!FT && blockAlwaysFallThrough(FalseBBI))
551 FT = getNextBlock(FalseBBI.BB);
552 if (TT != FT)
553 return false;
Craig Topperc0196b12014-04-14 00:51:57 +0000554 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng2117d1f2007-06-09 01:03:43 +0000555 return false;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000556 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
557 return false;
558
559 // FIXME: Allow true block to have an early exit?
560 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
561 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000562 return false;
563
Bob Wilsone1961fe2010-10-26 00:02:24 +0000564 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach6201b992010-06-07 21:28:55 +0000565 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
566 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilsone1961fe2010-10-26 00:02:24 +0000567 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
568 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
569 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000570 // Skip dbg_value instructions. These do not count.
Bob Wilsone1961fe2010-10-26 00:02:24 +0000571 if (TIB->isDebugValue()) {
572 while (TIB != TIE && TIB->isDebugValue())
573 ++TIB;
574 if (TIB == TIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000575 break;
576 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000577 if (FIB->isDebugValue()) {
578 while (FIB != FIE && FIB->isDebugValue())
579 ++FIB;
580 if (FIB == FIE)
Evan Chengc0e0d852010-06-18 21:52:57 +0000581 break;
582 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000583 if (!TIB->isIdenticalTo(FIB))
584 break;
585 ++Dups1;
586 ++TIB;
587 ++FIB;
588 }
589
590 // Now, in preparation for counting duplicate instructions at the ends of the
591 // blocks, move the end iterators up past any branch instructions.
592 while (TIE != TIB) {
593 --TIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000594 if (!TIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000595 break;
596 }
597 while (FIE != FIB) {
598 --FIE;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000599 if (!FIE->isBranch())
Bob Wilsone1961fe2010-10-26 00:02:24 +0000600 break;
601 }
602
603 // If Dups1 includes all of a block, then don't count duplicate
604 // instructions at the end of the blocks.
605 if (TIB == TIE || FIB == FIE)
606 return true;
607
608 // Count duplicate instructions at the ends of the blocks.
609 while (TIE != TIB && FIE != FIB) {
610 // Skip dbg_value instructions. These do not count.
611 if (TIE->isDebugValue()) {
612 while (TIE != TIB && TIE->isDebugValue())
613 --TIE;
614 if (TIE == TIB)
615 break;
616 }
617 if (FIE->isDebugValue()) {
618 while (FIE != FIB && FIE->isDebugValue())
619 --FIE;
620 if (FIE == FIB)
621 break;
622 }
623 if (!TIE->isIdenticalTo(FIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000624 break;
625 ++Dups2;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000626 --TIE;
627 --FIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000628 }
629
630 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000631}
632
Evan Cheng4dd31a72007-06-11 22:26:22 +0000633/// ScanInstructions - Scan all the instructions in the block to determine if
634/// the block is predicable. In most cases, that means all the instructions
Chris Lattnera98c6792008-01-07 01:56:04 +0000635/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng4dd31a72007-06-11 22:26:22 +0000636/// instruction which can clobber a predicate (e.g. condition code register).
637/// If so, the block is not predicable unless it's the last instruction.
638void IfConverter::ScanInstructions(BBInfo &BBI) {
639 if (BBI.IsDone)
640 return;
641
Evan Chengc5adcca2012-06-08 21:53:50 +0000642 bool AlreadyPredicated = !BBI.Predicate.empty();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000643 // First analyze the end of BB branches.
Craig Topperc0196b12014-04-14 00:51:57 +0000644 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000645 BBI.BrCond.clear();
646 BBI.IsBrAnalyzable =
647 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000648 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000649
650 if (BBI.BrCond.size()) {
651 // No false branch. This BB must end with a conditional branch and a
652 // fallthrough.
653 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000654 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000655 if (!BBI.FalseBB) {
656 // Malformed bcc? True and false blocks are the same?
657 BBI.IsUnpredicable = true;
658 return;
659 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000660 }
661
662 // Then scan all the instructions.
663 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000664 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000665 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000666 BBI.ClobbersPred = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000667 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
668 I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000669 if (I->isDebugValue())
670 continue;
671
Evan Cheng7f8e5632011-12-07 07:15:52 +0000672 if (I->isNotDuplicable())
Evan Cheng23402fc2007-06-15 21:18:05 +0000673 BBI.CannotBeCopied = true;
674
Evan Cheng4dd31a72007-06-11 22:26:22 +0000675 bool isPredicated = TII->isPredicated(I);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000676 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000677
Joey Goulya5153cb2013-09-09 14:21:49 +0000678 // A conditional branch is not predicable, but it may be eliminated.
679 if (isCondBr)
680 continue;
681
682 if (!isPredicated) {
683 BBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000684 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
685 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Joey Goulya5153cb2013-09-09 14:21:49 +0000686 if (NumCycles > 1)
687 BBI.ExtraCost += NumCycles-1;
688 BBI.ExtraCost2 += ExtraPredCost;
689 } else if (!AlreadyPredicated) {
690 // FIXME: This instruction is already predicated before the
691 // if-conversion pass. It's probably something like a conditional move.
692 // Mark this block unpredicable for now.
693 BBI.IsUnpredicable = true;
694 return;
Evan Cheng96c14572007-07-06 23:24:39 +0000695 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000696
697 if (BBI.ClobbersPred && !isPredicated) {
698 // Predicate modification instruction should end the block (except for
699 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +0000700 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +0000701 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000702 BBI.IsUnpredicable = true;
703 return;
704 }
705
Evan Chengfbc73092007-07-10 17:50:43 +0000706 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
707 // still potentially predicable.
708 std::vector<MachineOperand> PredDefs;
709 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000710 BBI.ClobbersPred = true;
711
Evan Cheng1f4062f2009-11-21 06:20:26 +0000712 if (!TII->isPredicable(I)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000713 BBI.IsUnpredicable = true;
714 return;
715 }
716 }
717}
718
719/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
720/// predicated by the specified predicate.
721bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000722 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng4dd31a72007-06-11 22:26:22 +0000723 bool isTriangle, bool RevBranch) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000724 // If the block is dead or unpredicable, then it cannot be predicated.
725 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000726 return false;
727
Ahmed Bougacha7173b662015-03-21 01:23:15 +0000728 // If it is already predicated but we couldn't analyze its terminator, the
729 // latter might fallthrough, but we can't determine where to.
730 // Conservatively avoid if-converting again.
731 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
732 return false;
733
Quentin Colombetbdab2272013-07-24 20:20:37 +0000734 // If it is already predicated, check if the new predicate subsumes
735 // its predicate.
736 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +0000737 return false;
738
739 if (BBI.BrCond.size()) {
740 if (!isTriangle)
741 return false;
742
Bob Wilson2371f4f2009-05-13 23:25:24 +0000743 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +0000744 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
745 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +0000746 if (RevBranch) {
747 if (TII->ReverseBranchCondition(Cond))
748 return false;
749 }
750 if (TII->ReverseBranchCondition(RevPred) ||
751 !TII->SubsumesPredicate(Cond, RevPred))
752 return false;
753 }
754
755 return true;
756}
757
Evan Cheng7783f822007-06-08 09:36:04 +0000758/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Cheng2e82cef2007-05-18 18:14:37 +0000759/// the specified block. Record its successors and whether it looks like an
760/// if-conversion candidate.
Evan Cheng3a51c852007-06-16 09:34:52 +0000761IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
762 std::vector<IfcvtToken*> &Tokens) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000763 BBInfo &BBI = BBAnalysis[BB->getNumber()];
764
Evan Cheng4dd31a72007-06-11 22:26:22 +0000765 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
766 return BBI;
Evan Cheng0f745da2007-05-18 00:20:58 +0000767
Evan Cheng4dd31a72007-06-11 22:26:22 +0000768 BBI.BB = BB;
769 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000770
771 ScanInstructions(BBI);
772
Jakub Staszaka4a18f02011-07-10 02:00:16 +0000773 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
774 // considered for ifcvt anymore.
775 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000776 BBI.IsBeingAnalyzed = false;
777 BBI.IsAnalyzed = true;
778 return BBI;
Evan Cheng9030b982007-06-06 10:16:17 +0000779 }
780
Evan Cheng4dd31a72007-06-11 22:26:22 +0000781 // Do not ifcvt if either path is a back edge to the entry block.
782 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
783 BBI.IsBeingAnalyzed = false;
784 BBI.IsAnalyzed = true;
785 return BBI;
786 }
787
Evan Chengb9bff582009-06-15 21:24:34 +0000788 // Do not ifcvt if true and false fallthrough blocks are the same.
789 if (!BBI.FalseBB) {
790 BBI.IsBeingAnalyzed = false;
791 BBI.IsAnalyzed = true;
792 return BBI;
793 }
794
Evan Cheng3a51c852007-06-16 09:34:52 +0000795 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
796 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng4dd31a72007-06-11 22:26:22 +0000797
798 if (TrueBBI.IsDone && FalseBBI.IsDone) {
799 BBI.IsBeingAnalyzed = false;
800 BBI.IsAnalyzed = true;
801 return BBI;
802 }
803
Owen Anderson4f6bf042008-08-14 22:49:33 +0000804 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng312b7232007-06-04 06:47:22 +0000805 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Cheng7783f822007-06-08 09:36:04 +0000806
Evan Cheng3a51c852007-06-16 09:34:52 +0000807 unsigned Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000808 unsigned Dups2 = 0;
Evan Chengc5adcca2012-06-08 21:53:50 +0000809 bool TNeedSub = !TrueBBI.Predicate.empty();
810 bool FNeedSub = !FalseBBI.Predicate.empty();
Evan Cheng3a51c852007-06-16 09:34:52 +0000811 bool Enqueued = false;
Benjamin Kramer2016f0e2010-09-29 22:38:50 +0000812
Jakub Staszak15e5b742011-08-03 22:34:43 +0000813 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
814
Evan Cheng51eb2c32007-06-18 08:37:25 +0000815 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000816 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000817 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
Bob Wilsonefd360c2010-10-26 00:02:21 +0000818 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
Evan Chengdebf9c52010-11-03 00:45:17 +0000819 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000820 Prediction) &&
Evan Cheng7783f822007-06-08 09:36:04 +0000821 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
822 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Chengf5e53a52007-05-16 02:00:57 +0000823 // Diamond:
824 // EBB
825 // / \_
826 // | |
827 // TBB FBB
828 // \ /
Evan Cheng0f745da2007-05-18 00:20:58 +0000829 // TailBB
Evan Cheng79484222007-06-05 23:46:14 +0000830 // Note TailBB can be empty.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000831 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
832 Dups2));
Evan Cheng3a51c852007-06-16 09:34:52 +0000833 Enqueued = true;
834 }
835
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000836 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000837 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000838 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000839 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
840 // Triangle:
841 // EBB
842 // | \_
843 // | |
844 // | TBB
845 // | /
846 // FBB
847 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
848 Enqueued = true;
849 }
Bob Wilson81051442010-06-15 22:18:54 +0000850
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000851 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000852 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000853 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000854 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
855 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
856 Enqueued = true;
857 }
858
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000859 if (ValidSimple(TrueBBI, Dups, Prediction) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000860 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000861 TrueBBI.ExtraCost2, Prediction) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000862 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
863 // Simple (split, no rejoin):
864 // EBB
865 // | \_
866 // | |
867 // | TBB---> exit
Bob Wilson81051442010-06-15 22:18:54 +0000868 // |
Evan Cheng3a51c852007-06-16 09:34:52 +0000869 // FBB
870 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
871 Enqueued = true;
872 }
873
874 if (CanRevCond) {
875 // Try the other path...
Owen Andersonf31f33e2010-10-01 22:45:50 +0000876 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000877 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000878 MeetIfcvtSizeLimit(*FalseBBI.BB,
879 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000880 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000881 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
882 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
883 Enqueued = true;
884 }
885
Owen Andersonf31f33e2010-10-01 22:45:50 +0000886 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000887 Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000888 MeetIfcvtSizeLimit(*FalseBBI.BB,
889 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000890 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000891 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
892 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
893 Enqueued = true;
894 }
895
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000896 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
Bob Wilsonefd360c2010-10-26 00:02:21 +0000897 MeetIfcvtSizeLimit(*FalseBBI.BB,
898 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000899 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +0000900 FeasibilityAnalysis(FalseBBI, RevCond)) {
901 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
902 Enqueued = true;
Evan Cheng312b7232007-06-04 06:47:22 +0000903 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000904 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000905
Evan Cheng3a51c852007-06-16 09:34:52 +0000906 BBI.IsEnqueued = Enqueued;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000907 BBI.IsBeingAnalyzed = false;
908 BBI.IsAnalyzed = true;
909 return BBI;
Evan Cheng2e82cef2007-05-18 18:14:37 +0000910}
911
Evan Cheng905a8f42007-05-30 19:49:19 +0000912/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000913/// candidates.
914void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Cheng3a51c852007-06-16 09:34:52 +0000915 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng9808d312011-04-27 19:32:43 +0000916 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
917 MachineBasicBlock *BB = I;
918 AnalyzeBlock(BB, Tokens);
Evan Chengf5e53a52007-05-16 02:00:57 +0000919 }
Evan Cheng905a8f42007-05-30 19:49:19 +0000920
Evan Cheng20e05992007-06-01 00:12:12 +0000921 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +0000922 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +0000923}
924
Evan Cheng288f1542007-06-08 22:01:07 +0000925/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
926/// that all the intervening blocks are empty (given BB can fall through to its
927/// next block).
928static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000929 MachineFunction::iterator PI = BB;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000930 MachineFunction::iterator I = std::next(PI);
Evan Cheng2c1acd62007-06-05 07:05:25 +0000931 MachineFunction::iterator TI = ToBB;
932 MachineFunction::iterator E = BB->getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +0000933 while (I != TI) {
934 // Check isSuccessor to avoid case where the next block is empty, but
935 // it's not a successor.
936 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Cheng312b7232007-06-04 06:47:22 +0000937 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +0000938 PI = I++;
939 }
Evan Cheng312b7232007-06-04 06:47:22 +0000940 return true;
Evan Chenge26c0912007-05-21 22:22:58 +0000941}
942
Evan Cheng51eb2c32007-06-18 08:37:25 +0000943/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
944/// to determine if it can be if-converted. If predecessor is already enqueued,
945/// dequeue it!
946void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +0000947 for (const auto &Predecessor : BB->predecessors()) {
948 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Evan Chengadd97762007-06-14 23:34:09 +0000949 if (PBBI.IsDone || PBBI.BB == BB)
Evan Cheng9fc56c02007-06-14 23:13:19 +0000950 continue;
Evan Chengadd97762007-06-14 23:34:09 +0000951 PBBI.IsAnalyzed = false;
952 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +0000953 }
954}
955
Evan Chengc2237ce2007-05-29 22:31:16 +0000956/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
957///
958static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
959 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +0000960 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +0000961 SmallVector<MachineOperand, 0> NoCond;
Craig Topperc0196b12014-04-14 00:51:57 +0000962 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +0000963}
964
Evan Cheng288f1542007-06-08 22:01:07 +0000965/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
966/// successors.
967void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
Craig Topperc0196b12014-04-14 00:51:57 +0000968 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000969 SmallVector<MachineOperand, 4> Cond;
Evan Cheng0598b2d2007-06-18 22:44:57 +0000970 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
971 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng288f1542007-06-08 22:01:07 +0000972}
973
Matthias Braund616ccc2013-10-11 19:04:37 +0000974/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
975/// values defined in MI which are not live/used by MI.
Juergen Ributzka310034e2013-12-14 06:52:56 +0000976static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
Pete Cooper7605e372015-05-05 20:14:22 +0000977 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
978 Redefs.stepForward(*MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +0000979
Pete Cooper7605e372015-05-05 20:14:22 +0000980 // Now add the implicit uses for each of the clobbered values.
981 for (auto Reg : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +0000982 // FIXME: Const cast here is nasty, but better than making StepForward
983 // take a mutable instruction instead of const.
Pete Cooper27483912015-05-06 22:51:04 +0000984 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
985 MachineInstr *OpMI = Op.getParent();
Pete Cooper7605e372015-05-05 20:14:22 +0000986 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +0000987 if (Op.isRegMask()) {
988 // First handle regmasks. They clobber any entries in the mask which
989 // means that we need a def for those registers.
Pete Cooper7605e372015-05-05 20:14:22 +0000990 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Pete Cooperce9ad752015-05-05 22:09:41 +0000991
992 // We also need to add an implicit def of this register for the later
993 // use to read from.
994 // For the register allocator to have allocated a register clobbered
995 // by the call which is used later, it must be the case that
996 // the call doesn't return.
997 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
998 continue;
999 }
1000 assert(Op.isReg() && "Register operand required");
Pete Cooper27483912015-05-06 22:51:04 +00001001 if (Op.isDead()) {
1002 // If we found a dead def, but it needs to be live, then remove the dead
1003 // flag.
1004 if (Redefs.contains(Op.getReg()))
1005 Op.setIsDead(false);
1006 }
Pete Cooperce9ad752015-05-05 22:09:41 +00001007 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
Matthias Braund616ccc2013-10-11 19:04:37 +00001008 }
1009}
1010
1011/**
1012 * Remove kill flags from operands with a registers in the @p DontKill set.
1013 */
Juergen Ributzka310034e2013-12-14 06:52:56 +00001014static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
Matthias Braund616ccc2013-10-11 19:04:37 +00001015 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1016 if (!O->isReg() || !O->isKill())
1017 continue;
Juergen Ributzka310034e2013-12-14 06:52:56 +00001018 if (DontKill.contains(O->getReg()))
Matthias Braund616ccc2013-10-11 19:04:37 +00001019 O->setIsKill(false);
1020 }
1021}
1022
1023/**
1024 * Walks a range of machine instructions and removes kill flags for registers
1025 * in the @p DontKill set.
1026 */
1027static void RemoveKills(MachineBasicBlock::iterator I,
1028 MachineBasicBlock::iterator E,
Juergen Ributzka310034e2013-12-14 06:52:56 +00001029 const LivePhysRegs &DontKill,
Matthias Braund616ccc2013-10-11 19:04:37 +00001030 const MCRegisterInfo &MCRI) {
1031 for ( ; I != E; ++I)
Juergen Ributzka310034e2013-12-14 06:52:56 +00001032 RemoveKills(*I, DontKill);
Evan Chengf128bdc2010-06-16 07:35:02 +00001033}
1034
Evan Cheng312b7232007-06-04 06:47:22 +00001035/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenge26c0912007-05-21 22:22:58 +00001036///
Evan Cheng3a51c852007-06-16 09:34:52 +00001037bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001038 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1039 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1040 BBInfo *CvtBBI = &TrueBBI;
1041 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001042
Owen Anderson4f6bf042008-08-14 22:49:33 +00001043 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001044 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001045 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001046
Evan Cheng51eb2c32007-06-18 08:37:25 +00001047 if (CvtBBI->IsDone ||
1048 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001049 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001050 BBI.IsAnalyzed = false;
1051 CvtBBI->IsAnalyzed = false;
1052 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001053 }
Evan Chengd0e66912007-05-23 07:23:16 +00001054
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001055 if (CvtBBI->BB->hasAddressTaken())
1056 // Conservatively abort if-conversion if BB's address is taken.
1057 return false;
1058
Evan Cheng3a51c852007-06-16 09:34:52 +00001059 if (Kind == ICSimpleFalse)
Dan Gohman97d95d62008-10-21 03:29:32 +00001060 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001061 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001062
Bob Wilson45814342010-06-19 05:33:57 +00001063 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001064 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001065 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001066 Redefs.addLiveIns(CvtBBI->BB);
1067 Redefs.addLiveIns(NextBBI->BB);
Matthias Braund616ccc2013-10-11 19:04:37 +00001068
1069 // Compute a set of registers which must not be killed by instructions in
1070 // BB1: This is everything live-in to BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001071 DontKill.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001072 DontKill.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001073
Evan Cheng92fb5452007-06-15 07:36:12 +00001074 if (CvtBBI->BB->pred_size() > 1) {
1075 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001076 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001077 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001078 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001079
1080 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1081 // explicitly remove CvtBBI as a successor.
1082 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001083 } else {
Matthias Braund616ccc2013-10-11 19:04:37 +00001084 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
Andrew Trick276dd452013-10-14 20:45:17 +00001085 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001086
Evan Cheng92fb5452007-06-15 07:36:12 +00001087 // Merge converted block into entry block.
1088 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1089 MergeBlocks(BBI, *CvtBBI);
1090 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001091
Evan Chenge4ec9182007-06-06 02:08:52 +00001092 bool IterIfcvt = true;
Evan Cheng288f1542007-06-08 22:01:07 +00001093 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc2237ce2007-05-29 22:31:16 +00001094 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001095 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001096 // Now ifcvt'd block will look like this:
1097 // BB:
1098 // ...
1099 // t, f = cmp
1100 // if t op
1101 // b BBf
1102 //
1103 // We cannot further ifcvt this block because the unconditional branch
1104 // will have to be predicated on the new condition, that will not be
1105 // available if cmp executes.
1106 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001107 }
Evan Chenge26c0912007-05-21 22:22:58 +00001108
Evan Cheng288f1542007-06-08 22:01:07 +00001109 RemoveExtraEdges(BBI);
1110
Evan Chengd0e66912007-05-23 07:23:16 +00001111 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001112 if (!IterIfcvt)
1113 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001114 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001115 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001116
1117 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001118 return true;
1119}
1120
Manman Renb6819182014-01-29 23:18:47 +00001121/// Scale down weights to fit into uint32_t. NewTrue is the new weight
1122/// for successor TrueBB, and NewFalse is the new weight for successor
1123/// FalseBB.
1124static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1125 MachineBasicBlock *MBB,
1126 const MachineBasicBlock *TrueBB,
1127 const MachineBasicBlock *FalseBB,
1128 const MachineBranchProbabilityInfo *MBPI) {
1129 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1130 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1131 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1132 SE = MBB->succ_end();
1133 SI != SE; ++SI) {
1134 if (*SI == TrueBB)
1135 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1136 else if (*SI == FalseBB)
1137 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1138 else
1139 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1140 }
1141}
1142
Evan Chengaf716102007-05-16 21:54:37 +00001143/// IfConvertTriangle - If convert a triangle sub-CFG.
1144///
Evan Cheng3a51c852007-06-16 09:34:52 +00001145bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001146 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001147 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1148 BBInfo *CvtBBI = &TrueBBI;
1149 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001150 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001151
Owen Anderson4f6bf042008-08-14 22:49:33 +00001152 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001153 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001154 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001155
Evan Cheng51eb2c32007-06-18 08:37:25 +00001156 if (CvtBBI->IsDone ||
1157 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001158 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001159 BBI.IsAnalyzed = false;
1160 CvtBBI->IsAnalyzed = false;
1161 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001162 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001163
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001164 if (CvtBBI->BB->hasAddressTaken())
1165 // Conservatively abort if-conversion if BB's address is taken.
1166 return false;
1167
Evan Cheng3a51c852007-06-16 09:34:52 +00001168 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman97d95d62008-10-21 03:29:32 +00001169 if (TII->ReverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001170 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001171
Evan Cheng3a51c852007-06-16 09:34:52 +00001172 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001173 if (ReverseBranchCondition(*CvtBBI)) {
1174 // BB has been changed, modify its predecessors (except for this
1175 // one) so they don't get ifcvt'ed based on bad intel.
1176 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1177 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1178 MachineBasicBlock *PBB = *PI;
1179 if (PBB == BBI.BB)
1180 continue;
1181 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1182 if (PBBI.IsEnqueued) {
1183 PBBI.IsAnalyzed = false;
1184 PBBI.IsEnqueued = false;
1185 }
Evan Chengadd97762007-06-14 23:34:09 +00001186 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001187 }
1188 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001189
Bob Wilson45814342010-06-19 05:33:57 +00001190 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001191 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001192 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001193 Redefs.addLiveIns(CvtBBI->BB);
1194 Redefs.addLiveIns(NextBBI->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001195
Andrew Trick276dd452013-10-14 20:45:17 +00001196 DontKill.clear();
1197
Craig Topperc0196b12014-04-14 00:51:57 +00001198 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Manman Ren37c92672014-02-07 00:38:56 +00001199 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
Manman Renb6819182014-01-29 23:18:47 +00001200 uint32_t WeightScale = 0;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001201
Manman Renb6819182014-01-29 23:18:47 +00001202 if (HasEarlyExit) {
Manman Ren37c92672014-02-07 00:38:56 +00001203 // Get weights before modifying CvtBBI->BB and BBI.BB.
Manman Renb6819182014-01-29 23:18:47 +00001204 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1205 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
Manman Ren37c92672014-02-07 00:38:56 +00001206 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1207 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
Manman Renb6819182014-01-29 23:18:47 +00001208 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
1209 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001210
Bob Wilson1e5da552010-06-29 00:55:23 +00001211 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001212 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2371f4f2009-05-13 23:25:24 +00001213 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001214 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001215 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Hal Finkel95081bf2013-04-10 22:05:25 +00001216
1217 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1218 // explicitly remove CvtBBI as a successor.
1219 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Cheng92fb5452007-06-15 07:36:12 +00001220 } else {
1221 // Predicate the 'true' block after removing its branch.
1222 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Andrew Trick276dd452013-10-14 20:45:17 +00001223 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001224
Evan Cheng0598b2d2007-06-18 22:44:57 +00001225 // Now merge the entry of the triangle with the true block.
1226 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson1e5da552010-06-29 00:55:23 +00001227 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001228 }
1229
Evan Cheng312b7232007-06-04 06:47:22 +00001230 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001231 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001232 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1233 CvtBBI->BrCond.end());
Evan Cheng6a2cf072007-06-01 07:41:07 +00001234 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001235 llvm_unreachable("Unable to reverse branch condition!");
Craig Topperc0196b12014-04-14 00:51:57 +00001236 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001237 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Manman Renb6819182014-01-29 23:18:47 +00001238 // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1239 // New_Weight(BBI.BB, NextBBI->BB) =
1240 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1241 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1242 // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1243 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1244
Manman Renb6819182014-01-29 23:18:47 +00001245 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1246 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
1247 // We need to scale down all weights of BBI.BB to fit uint32_t.
1248 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1249 // the next block.
1250 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1251 CvtBBI->FalseBB, MBPI);
Evan Cheng92fb5452007-06-15 07:36:12 +00001252 }
Evan Cheng7783f822007-06-08 09:36:04 +00001253
1254 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001255 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001256 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001257 bool IterIfcvt = true;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001258 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001259 if (!isFallThrough) {
1260 // Only merge them if the true block does not fallthrough to the false
1261 // block. By not merging them, we make it possible to iteratively
1262 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001263 if (!HasEarlyExit &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001264 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1265 !NextBBI->BB->hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001266 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001267 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001268 } else {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001269 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1270 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001271 }
Evan Cheng7783f822007-06-08 09:36:04 +00001272 // Mixed predicated and unpredicated code. This cannot be iteratively
1273 // predicated.
1274 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001275 }
Evan Chenge26c0912007-05-21 22:22:58 +00001276
Evan Cheng288f1542007-06-08 22:01:07 +00001277 RemoveExtraEdges(BBI);
Evan Chenge26c0912007-05-21 22:22:58 +00001278
Evan Chengd0e66912007-05-23 07:23:16 +00001279 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001280 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001281 BBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001282 InvalidatePreds(BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001283 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001284 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001285 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001286
1287 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001288 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001289}
1290
Evan Chengaf716102007-05-16 21:54:37 +00001291/// IfConvertDiamond - If convert a diamond sub-CFG.
1292///
Evan Cheng51eb2c32007-06-18 08:37:25 +00001293bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1294 unsigned NumDups1, unsigned NumDups2) {
Evan Cheng312b7232007-06-04 06:47:22 +00001295 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2e82cef2007-05-18 18:14:37 +00001296 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng3a51c852007-06-16 09:34:52 +00001297 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson2371f4f2009-05-13 23:25:24 +00001298 // True block must fall through or end with an unanalyzable terminator.
Evan Cheng3a51c852007-06-16 09:34:52 +00001299 if (!TailBB) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001300 if (blockAlwaysFallThrough(TrueBBI))
1301 TailBB = FalseBBI.TrueBB;
1302 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Chengf5e53a52007-05-16 02:00:57 +00001303 }
Evan Chenge26c0912007-05-21 22:22:58 +00001304
Evan Cheng51eb2c32007-06-18 08:37:25 +00001305 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1306 TrueBBI.BB->pred_size() > 1 ||
1307 FalseBBI.BB->pred_size() > 1) {
1308 // Something has changed. It's no longer safe to predicate these blocks.
1309 BBI.IsAnalyzed = false;
1310 TrueBBI.IsAnalyzed = false;
1311 FalseBBI.IsAnalyzed = false;
1312 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001313 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001314
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001315 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1316 // Conservatively abort if-conversion if either BB has its address taken.
1317 return false;
1318
Bob Wilson1e5da552010-06-29 00:55:23 +00001319 // Put the predicated instructions from the 'true' block before the
1320 // instructions from the 'false' block, unless the true block would clobber
1321 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001322 BBInfo *BBI1 = &TrueBBI;
1323 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001324 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman97d95d62008-10-21 03:29:32 +00001325 if (TII->ReverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001326 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001327 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1328 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001329
Evan Cheng3a51c852007-06-16 09:34:52 +00001330 // Figure out the more profitable ordering.
1331 bool DoSwap = false;
1332 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1333 DoSwap = true;
1334 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001335 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001336 DoSwap = true;
Evan Cheng3a51c852007-06-16 09:34:52 +00001337 }
1338 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001339 std::swap(BBI1, BBI2);
1340 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001341 }
Evan Cheng79484222007-06-05 23:46:14 +00001342
Evan Cheng51eb2c32007-06-18 08:37:25 +00001343 // Remove the conditional branch from entry to the blocks.
1344 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1345
Jim Grosbach8a6deef2010-06-25 22:02:28 +00001346 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001347 // predicated instructions.
Andrew Trick276dd452013-10-14 20:45:17 +00001348 Redefs.init(TRI);
Juergen Ributzka310034e2013-12-14 06:52:56 +00001349 Redefs.addLiveIns(BBI1->BB);
Evan Chengf128bdc2010-06-16 07:35:02 +00001350
Evan Cheng51eb2c32007-06-18 08:37:25 +00001351 // Remove the duplicated instructions at the beginnings of both paths.
1352 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1353 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbach412800d2010-06-14 21:30:32 +00001354 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1355 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1356 // Skip dbg_value instructions
1357 while (DI1 != DIE1 && DI1->isDebugValue())
1358 ++DI1;
1359 while (DI2 != DIE2 && DI2->isDebugValue())
1360 ++DI2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001361 BBI1->NonPredSize -= NumDups1;
1362 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001363
1364 // Skip past the dups on each side separately since there may be
1365 // differing dbg_value entries.
1366 for (unsigned i = 0; i < NumDups1; ++DI1) {
1367 if (!DI1->isDebugValue())
1368 ++i;
1369 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001370 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001371 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001372 if (!DI2->isDebugValue())
1373 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001374 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001375
Matthias Braund616ccc2013-10-11 19:04:37 +00001376 // Compute a set of registers which must not be killed by instructions in BB1:
1377 // This is everything used+live in BB2 after the duplicated instructions. We
1378 // can compute this set by simulating liveness backwards from the end of BB2.
Andrew Trick276dd452013-10-14 20:45:17 +00001379 DontKill.init(TRI);
Benjamin Kramera9767ae2013-10-11 19:49:09 +00001380 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1381 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
Juergen Ributzka310034e2013-12-14 06:52:56 +00001382 DontKill.stepBackward(*I);
Matthias Braund616ccc2013-10-11 19:04:37 +00001383 }
1384
1385 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1386 ++I) {
Pete Cooper7605e372015-05-05 20:14:22 +00001387 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1388 Redefs.stepForward(*I, IgnoredClobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001389 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001390 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1391 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1392
Evan Cheng4266a792011-12-19 22:01:30 +00001393 // Remove branch from 'true' block and remove duplicated instructions.
Evan Cheng79484222007-06-05 23:46:14 +00001394 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001395 DI1 = BBI1->BB->end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001396 for (unsigned i = 0; i != NumDups2; ) {
1397 // NumDups2 only counted non-dbg_value instructions, so this won't
1398 // run off the head of the list.
1399 assert (DI1 != BBI1->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001400 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001401 // skip dbg_value instructions
1402 if (!DI1->isDebugValue())
1403 ++i;
1404 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001405 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng79484222007-06-05 23:46:14 +00001406
Matthias Braund616ccc2013-10-11 19:04:37 +00001407 // Kill flags in the true block for registers living into the false block
1408 // must be removed.
1409 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1410
Evan Cheng4266a792011-12-19 22:01:30 +00001411 // Remove 'false' block branch and find the last instruction to predicate.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001412 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1413 DI2 = BBI2->BB->end();
1414 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001415 // NumDups2 only counted non-dbg_value instructions, so this won't
1416 // run off the head of the list.
1417 assert (DI2 != BBI2->BB->begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001418 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001419 // skip dbg_value instructions
1420 if (!DI2->isDebugValue())
1421 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001422 }
Evan Cheng4266a792011-12-19 22:01:30 +00001423
1424 // Remember which registers would later be defined by the false block.
1425 // This allows us not to predicate instructions in the true block that would
1426 // later be re-defined. That is, rather than
1427 // subeq r0, r1, #1
1428 // addne r0, r1, #1
1429 // generate:
1430 // sub r0, r1, #1
1431 // addne r0, r1, #1
1432 SmallSet<unsigned, 4> RedefsByFalse;
1433 SmallSet<unsigned, 4> ExtUses;
1434 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1435 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1436 if (FI->isDebugValue())
1437 continue;
1438 SmallVector<unsigned, 4> Defs;
1439 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1440 const MachineOperand &MO = FI->getOperand(i);
1441 if (!MO.isReg())
1442 continue;
1443 unsigned Reg = MO.getReg();
1444 if (!Reg)
1445 continue;
1446 if (MO.isDef()) {
1447 Defs.push_back(Reg);
1448 } else if (!RedefsByFalse.count(Reg)) {
1449 // These are defined before ctrl flow reach the 'false' instructions.
1450 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001451 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1452 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001453 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001454 }
1455 }
1456
1457 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1458 unsigned Reg = Defs[i];
1459 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001460 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1461 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001462 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001463 }
1464 }
1465 }
1466 }
1467
1468 // Predicate the 'true' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001469 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001470
1471 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001472 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001473
Evan Cheng0598b2d2007-06-18 22:44:57 +00001474 // Merge the true block into the entry of the diamond.
Craig Topperc0196b12014-04-14 00:51:57 +00001475 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1476 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
Evan Cheng30565992007-06-06 00:57:55 +00001477
Bob Wilson2371f4f2009-05-13 23:25:24 +00001478 // If the if-converted block falls through or unconditionally branches into
1479 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001480 // fold the tail block in as well. Otherwise, unless it falls through to the
1481 // tail, add a unconditional branch to it.
1482 if (TailBB) {
Pete Cooper77c703f2011-11-04 23:49:14 +00001483 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001484 bool CanMergeTail = !TailBBI.HasFallThrough &&
1485 !TailBBI.BB->hasAddressTaken();
Bob Wilson1e5da552010-06-29 00:55:23 +00001486 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1487 // check if there are any other predecessors besides those.
1488 unsigned NumPreds = TailBB->pred_size();
1489 if (NumPreds > 1)
1490 CanMergeTail = false;
1491 else if (NumPreds == 1 && CanMergeTail) {
1492 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1493 if (*PI != BBI1->BB && *PI != BBI2->BB)
1494 CanMergeTail = false;
1495 }
1496 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001497 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001498 TailBBI.IsDone = true;
1499 } else {
Bob Wilson1e5da552010-06-29 00:55:23 +00001500 BBI.BB->addSuccessor(TailBB);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001501 InsertUncondBranch(BBI.BB, TailBB, TII);
1502 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001503 }
Evan Chenge26c0912007-05-21 22:22:58 +00001504 }
1505
Bob Wilson1e5da552010-06-29 00:55:23 +00001506 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1507 // which can happen here if TailBB is unanalyzable and is merged, so
1508 // explicitly remove BBI1 and BBI2 as successors.
1509 BBI.BB->removeSuccessor(BBI1->BB);
1510 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng288f1542007-06-08 22:01:07 +00001511 RemoveExtraEdges(BBI);
1512
Evan Cheng79484222007-06-05 23:46:14 +00001513 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001514 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001515 InvalidatePreds(BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001516
1517 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001518 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001519}
1520
Evan Cheng4266a792011-12-19 22:01:30 +00001521static bool MaySpeculate(const MachineInstr *MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001522 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001523 bool SawStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001524 if (!MI->isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001525 return false;
1526
1527 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1528 const MachineOperand &MO = MI->getOperand(i);
1529 if (!MO.isReg())
1530 continue;
1531 unsigned Reg = MO.getReg();
1532 if (!Reg)
1533 continue;
1534 if (MO.isDef() && !LaterRedefs.count(Reg))
1535 return false;
1536 }
1537
1538 return true;
1539}
1540
Evan Cheng51eb2c32007-06-18 08:37:25 +00001541/// PredicateBlock - Predicate instructions from the start of the block to the
1542/// specified end with the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001543void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001544 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001545 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001546 SmallSet<unsigned, 4> *LaterRedefs) {
1547 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001548 bool MaySpec = LaterRedefs != nullptr;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001549 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbacha1e08fb2010-06-04 23:01:26 +00001550 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001551 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001552 // It may be possible not to predicate an instruction if it's the 'true'
1553 // side of a diamond and the 'false' side may re-define the instruction's
1554 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001555 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001556 AnyUnpred = true;
1557 continue;
1558 }
1559 // If any instruction is predicated, then every instruction after it must
1560 // be predicated.
1561 MaySpec = false;
Evan Cheng312b7232007-06-04 06:47:22 +00001562 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001563#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001564 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001565#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001566 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00001567 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001568
Bob Wilson45814342010-06-19 05:33:57 +00001569 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001570 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001571 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00001572 }
Evan Chengd0e66912007-05-23 07:23:16 +00001573
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001574 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00001575
Evan Cheng92fb5452007-06-15 07:36:12 +00001576 BBI.IsAnalyzed = false;
1577 BBI.NonPredSize = 0;
1578
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001579 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00001580 if (AnyUnpred)
1581 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00001582}
1583
Evan Cheng92fb5452007-06-15 07:36:12 +00001584/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1585/// the destination block. Skip end of block branches if IgnoreBr is true.
1586void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001587 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00001588 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00001589 MachineFunction &MF = *ToBBI.BB->getParent();
1590
Evan Cheng92fb5452007-06-15 07:36:12 +00001591 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1592 E = FromBBI.BB->end(); I != E; ++I) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001593 // Do not copy the end of the block branches.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001594 if (IgnoreBr && I->isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00001595 break;
1596
Dan Gohman3b460302008-07-07 23:14:23 +00001597 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng92fb5452007-06-15 07:36:12 +00001598 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00001599 ToBBI.NonPredSize++;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +00001600 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1601 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00001602 if (NumCycles > 1)
1603 ToBBI.ExtraCost += NumCycles-1;
1604 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00001605
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00001606 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng92fb5452007-06-15 07:36:12 +00001607 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00001608#ifndef NDEBUG
David Greene72e47cd2010-01-04 22:02:01 +00001609 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00001610#endif
Craig Topperc0196b12014-04-14 00:51:57 +00001611 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00001612 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001613 }
1614
Bob Wilson45814342010-06-19 05:33:57 +00001615 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00001616 // if-conversion, add an implicit kill.
Juergen Ributzka310034e2013-12-14 06:52:56 +00001617 UpdatePredRedefs(MI, Redefs);
Matthias Braund616ccc2013-10-11 19:04:37 +00001618
1619 // Some kill flags may not be correct anymore.
Andrew Trick276dd452013-10-14 20:45:17 +00001620 if (!DontKill.empty())
Juergen Ributzka310034e2013-12-14 06:52:56 +00001621 RemoveKills(*MI, DontKill);
Evan Cheng92fb5452007-06-15 07:36:12 +00001622 }
1623
Bob Wilson1e5da552010-06-29 00:55:23 +00001624 if (!IgnoreBr) {
1625 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1626 FromBBI.BB->succ_end());
1627 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001628 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00001629
Bob Wilson1e5da552010-06-29 00:55:23 +00001630 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1631 MachineBasicBlock *Succ = Succs[i];
1632 // Fallthrough edge can't be transferred.
1633 if (Succ == FallThrough)
1634 continue;
1635 ToBBI.BB->addSuccessor(Succ);
1636 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00001637 }
1638
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001639 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1640 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001641
1642 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1643 ToBBI.IsAnalyzed = false;
1644
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001645 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00001646}
1647
Evan Cheng0f745da2007-05-18 00:20:58 +00001648/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson1e5da552010-06-29 00:55:23 +00001649/// This will leave FromBB as an empty block, so remove all of its
1650/// successor edges except for the fall-through edge. If AddEdges is true,
1651/// i.e., when FromBBI's branch is being moved, add those successor edges to
1652/// ToBBI.
1653void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001654 assert(!FromBBI.BB->hasAddressTaken() &&
1655 "Removing a BB whose address is taken!");
1656
Evan Cheng0f745da2007-05-18 00:20:58 +00001657 ToBBI.BB->splice(ToBBI.BB->end(),
1658 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chengd0e66912007-05-23 07:23:16 +00001659
Evan Chengbe9859e2007-06-07 02:12:15 +00001660 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1661 FromBBI.BB->succ_end());
Evan Cheng288f1542007-06-08 22:01:07 +00001662 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Craig Topperc0196b12014-04-14 00:51:57 +00001663 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng312b7232007-06-04 06:47:22 +00001664
Evan Chengbe9859e2007-06-07 02:12:15 +00001665 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1666 MachineBasicBlock *Succ = Succs[i];
Evan Cheng288f1542007-06-08 22:01:07 +00001667 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00001668 if (Succ == FallThrough)
1669 continue;
1670 FromBBI.BB->removeSuccessor(Succ);
Jakob Stoklund Olesene0ef4742013-01-24 23:59:08 +00001671 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
Bob Wilson1e5da552010-06-29 00:55:23 +00001672 ToBBI.BB->addSuccessor(Succ);
Evan Chengbe9859e2007-06-07 02:12:15 +00001673 }
1674
Bob Wilson2371f4f2009-05-13 23:25:24 +00001675 // Now FromBBI always falls through to the next block!
Bob Wilson43f21dd2009-05-13 23:48:58 +00001676 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng288f1542007-06-08 22:01:07 +00001677 FromBBI.BB->addSuccessor(NBB);
1678
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00001679 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00001680 FromBBI.Predicate.clear();
1681
Evan Chengd0e66912007-05-23 07:23:16 +00001682 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001683 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00001684 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00001685 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00001686 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00001687 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00001688
Evan Cheng4dd31a72007-06-11 22:26:22 +00001689 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001690 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00001691 ToBBI.IsAnalyzed = false;
1692 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00001693}