blob: ce3eda789131998d5b8dc84955741491a5665c77 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "ifcvt"
Evan Cheng9dcb7602009-09-04 07:47:40 +000015#include "BranchFolding.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000016#include "llvm/Function.h"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
Owen Andersond4397bb2010-09-28 20:42:15 +000020#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0cf9a822010-09-10 01:29:16 +000022#include "llvm/Target/TargetInstrItineraries.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Target/TargetLowering.h"
24#include "llvm/Target/TargetMachine.h"
Evan Cheng160f30c2010-06-16 07:35:02 +000025#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/ADT/DepthFirstIterator.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33using namespace llvm;
34
Chris Lattner4335bff2008-01-07 05:40:58 +000035// Hidden options for help debugging.
36static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000039static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner4335bff2008-01-07 05:40:58 +000040 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000041static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000042 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000043static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner4335bff2008-01-07 05:40:58 +000044 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000045static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000047static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000051static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner4335bff2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Evan Cheng160f30c2010-06-16 07:35:02 +000053static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055
56STATISTIC(NumSimple, "Number of simple if-conversions performed");
57STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
59STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
60STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
64STATISTIC(NumDupBBs, "Number of duplicated blocks");
65
66namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000067 class IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000068 enum IfcvtKind {
69 ICNotClassfied, // BB data valid, but not classified.
70 ICSimpleFalse, // Same as ICSimple, but on the false path.
71 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
72 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
73 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
74 ICTriangleFalse, // Same as ICTriangle, but on the false path.
75 ICTriangle, // BB is entry of a triangle sub-CFG.
76 ICDiamond // BB is entry of a diamond sub-CFG.
77 };
78
79 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80 /// if-conversion feasibility analysis. This includes results from
81 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
82 /// classification, and common tail block of its successors (if it's a
83 /// diamond shape), its size, whether it's predicable, and whether any
84 /// instruction can clobber the 'would-be' predicate.
85 ///
86 /// IsDone - True if BB is not to be considered for ifcvt.
87 /// IsBeingAnalyzed - True if BB is currently being analyzed.
88 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
89 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
90 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
91 /// HasFallThrough - True if BB may fallthrough to the following BB.
92 /// IsUnpredicable - True if BB is known to be unpredicable.
93 /// ClobbersPred - True if BB could modify predicates (e.g. has
94 /// cmp, call, etc.)
95 /// NonPredSize - Number of non-predicated instructions.
Bob Wilson9c30a772010-10-26 00:02:21 +000096 /// ExtraCost - Extra cost for microcoded instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 /// BB - Corresponding MachineBasicBlock.
98 /// TrueBB / FalseBB- See AnalyzeBranch().
99 /// BrCond - Conditions for end of block conditional branches.
100 /// Predicate - Predicate used in the BB.
101 struct BBInfo {
102 bool IsDone : 1;
103 bool IsBeingAnalyzed : 1;
104 bool IsAnalyzed : 1;
105 bool IsEnqueued : 1;
106 bool IsBrAnalyzable : 1;
107 bool HasFallThrough : 1;
108 bool IsUnpredicable : 1;
109 bool CannotBeCopied : 1;
110 bool ClobbersPred : 1;
111 unsigned NonPredSize;
Bob Wilson9c30a772010-10-26 00:02:21 +0000112 unsigned ExtraCost;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 MachineBasicBlock *BB;
114 MachineBasicBlock *TrueBB;
115 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000116 SmallVector<MachineOperand, 4> BrCond;
117 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
119 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
120 HasFallThrough(false), IsUnpredicable(false),
121 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Bob Wilson9c30a772010-10-26 00:02:21 +0000122 ExtraCost(0), BB(0), TrueBB(0), FalseBB(0) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 };
124
Bob Wilson01320da2010-06-15 18:19:27 +0000125 /// IfcvtToken - Record information about pending if-conversions to attempt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 /// BBI - Corresponding BBInfo.
127 /// Kind - Type of block. See IfcvtKind.
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000128 /// NeedSubsumption - True if the to-be-predicated BB has already been
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 /// predicated.
130 /// NumDups - Number of instructions that would be duplicated due
131 /// to this if-conversion. (For diamonds, the number of
132 /// identical instructions at the beginnings of both
133 /// paths).
134 /// NumDups2 - For diamonds, the number of identical instructions
135 /// at the ends of both paths.
136 struct IfcvtToken {
137 BBInfo &BBI;
138 IfcvtKind Kind;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000139 bool NeedSubsumption;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 unsigned NumDups;
141 unsigned NumDups2;
142 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000143 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 };
145
146 /// Roots - Basic blocks that do not have successors. These are the starting
147 /// points of Graph traversal.
148 std::vector<MachineBasicBlock*> Roots;
149
150 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
151 /// basic block number.
152 std::vector<BBInfo> BBAnalysis;
153
154 const TargetLowering *TLI;
155 const TargetInstrInfo *TII;
Evan Cheng160f30c2010-06-16 07:35:02 +0000156 const TargetRegisterInfo *TRI;
Evan Cheng0cf9a822010-09-10 01:29:16 +0000157 const InstrItineraryData *InstrItins;
Owen Andersond4397bb2010-09-28 20:42:15 +0000158 const MachineLoopInfo *MLI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 bool MadeChange;
Owen Anderson03f2a7b2009-06-24 23:41:44 +0000160 int FnNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 public:
162 static char ID;
Owen Andersona65d6a62010-10-19 17:21:58 +0000163 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164 initializeIfConverterPass(*PassRegistry::getPassRegistry());
165 }
Owen Andersond4397bb2010-09-28 20:42:15 +0000166
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<MachineLoopInfo>();
169 MachineFunctionPass::getAnalysisUsage(AU);
170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171
172 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000173 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
175 private:
176 bool ReverseBranchCondition(BBInfo &BBI);
Owen Anderson97d32912010-10-01 22:45:50 +0000177 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178 float Prediction, float Confidence) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Anderson97d32912010-10-01 22:45:50 +0000180 bool FalseBranch, unsigned &Dups,
181 float Prediction, float Confidence) const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183 unsigned &Dups1, unsigned &Dups2) const;
184 void ScanInstructions(BBInfo &BBI);
185 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000187 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 bool isTriangle = false, bool RevBranch = false);
Bob Wilson89b9c322010-06-15 18:57:15 +0000189 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 void InvalidatePreds(MachineBasicBlock *BB);
191 void RemoveExtraEdges(BBInfo &BBI);
192 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
194 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195 unsigned NumDups1, unsigned NumDups2);
196 void PredicateBlock(BBInfo &BBI,
197 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +0000198 SmallVectorImpl<MachineOperand> &Cond,
199 SmallSet<unsigned, 4> &Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000201 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +0000202 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 bool IgnoreBr = false);
Bob Wilson2e99a562010-06-29 00:55:23 +0000204 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205
Owen Andersond4397bb2010-09-28 20:42:15 +0000206 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
Owen Anderson97d32912010-10-01 22:45:50 +0000207 float Prediction, float Confidence) const {
208 return Size > 0 && TII->isProfitableToIfCvt(BB, Size,
209 Prediction, Confidence);
Evan Cheng09f72522010-06-25 22:42:03 +0000210 }
211
212 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
Owen Andersond4397bb2010-09-28 20:42:15 +0000213 MachineBasicBlock &FBB, unsigned FSize,
Owen Anderson97d32912010-10-01 22:45:50 +0000214 float Prediction, float Confidence) const {
Evan Cheng09f72522010-06-25 22:42:03 +0000215 return TSize > 0 && FSize > 0 &&
Owen Anderson97d32912010-10-01 22:45:50 +0000216 TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize,
217 Prediction, Confidence);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 }
219
220 // blockAlwaysFallThrough - Block ends without a terminator.
221 bool blockAlwaysFallThrough(BBInfo &BBI) const {
222 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
223 }
224
225 // IfcvtTokenCmp - Used to sort if-conversion candidates.
226 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
227 int Incr1 = (C1->Kind == ICDiamond)
228 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
229 int Incr2 = (C2->Kind == ICDiamond)
230 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
231 if (Incr1 > Incr2)
232 return true;
233 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000234 // Favors subsumption.
235 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000237 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 // Favors diamond over triangle, etc.
239 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
240 return true;
241 else if (C1->Kind == C2->Kind)
242 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
243 }
244 }
245 return false;
246 }
247 };
248
249 char IfConverter::ID = 0;
250}
251
Owen Andersoncdb0c032010-10-12 19:48:12 +0000252INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
253INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
254INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilson93ab5612009-10-28 20:46:46 +0000255
256FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257
258bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
259 TLI = MF.getTarget().getTargetLowering();
260 TII = MF.getTarget().getInstrInfo();
Evan Cheng160f30c2010-06-16 07:35:02 +0000261 TRI = MF.getTarget().getRegisterInfo();
Owen Andersond4397bb2010-09-28 20:42:15 +0000262 MLI = &getAnalysis<MachineLoopInfo>();
Evan Cheng0cf9a822010-09-10 01:29:16 +0000263 InstrItins = MF.getTarget().getInstrItineraryData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 if (!TII) return false;
265
Evan Cheng24ff0562010-06-18 23:09:54 +0000266 // Tail merge tend to expose more if-conversion opportunities.
267 BranchFolder BF(true);
268 bool BFChange = BF.OptimizeFunction(MF, TII,
269 MF.getTarget().getRegisterInfo(),
270 getAnalysisIfAvailable<MachineModuleInfo>());
271
David Greenead778702010-01-04 22:02:01 +0000272 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000273 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
275 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greenead778702010-01-04 22:02:01 +0000276 DEBUG(dbgs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277 return false;
278 }
David Greenead778702010-01-04 22:02:01 +0000279 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280
281 MF.RenumberBlocks();
282 BBAnalysis.resize(MF.getNumBlockIDs());
283
284 // Look for root nodes, i.e. blocks without successors.
285 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000286 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 Roots.push_back(I);
288
289 std::vector<IfcvtToken*> Tokens;
290 MadeChange = false;
291 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
292 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
293 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000294 // Do an initial analysis for each basic block and find all the potential
295 // candidates to perform if-conversion.
Bob Wilson89b9c322010-06-15 18:57:15 +0000296 bool Change = false;
297 AnalyzeBlocks(MF, Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 while (!Tokens.empty()) {
299 IfcvtToken *Token = Tokens.back();
300 Tokens.pop_back();
301 BBInfo &BBI = Token->BBI;
302 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000303 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000304 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000305
306 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307
308 // If the block has been evicted out of the queue or it has already been
309 // marked dead (due to it being predicated), then skip it.
310 if (BBI.IsDone)
311 BBI.IsEnqueued = false;
312 if (!BBI.IsEnqueued)
313 continue;
314
315 BBI.IsEnqueued = false;
316
317 bool RetVal = false;
318 switch (Kind) {
319 default: assert(false && "Unexpected!");
320 break;
321 case ICSimple:
322 case ICSimpleFalse: {
323 bool isFalse = Kind == ICSimpleFalse;
324 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000325 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
326 " false" : "")
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000327 << "): BB#" << BBI.BB->getNumber() << " ("
328 << ((Kind == ICSimpleFalse)
329 ? BBI.FalseBB->getNumber()
330 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 RetVal = IfConvertSimple(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000332 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000333 if (RetVal) {
Dan Gohman559d5132010-06-22 15:08:57 +0000334 if (isFalse) ++NumSimpleFalse;
335 else ++NumSimple;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000336 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 break;
338 }
339 case ICTriangle:
340 case ICTriangleRev:
341 case ICTriangleFalse:
342 case ICTriangleFRev: {
343 bool isFalse = Kind == ICTriangleFalse;
344 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
345 if (DisableTriangle && !isFalse && !isRev) break;
346 if (DisableTriangleR && !isFalse && isRev) break;
347 if (DisableTriangleF && isFalse && !isRev) break;
348 if (DisableTriangleFR && isFalse && isRev) break;
David Greenead778702010-01-04 22:02:01 +0000349 DEBUG(dbgs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 if (isFalse)
David Greenead778702010-01-04 22:02:01 +0000351 DEBUG(dbgs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 if (isRev)
David Greenead778702010-01-04 22:02:01 +0000353 DEBUG(dbgs() << " rev");
354 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000355 << BBI.TrueBB->getNumber() << ",F:"
356 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 RetVal = IfConvertTriangle(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000358 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 if (RetVal) {
360 if (isFalse) {
Dan Gohman559d5132010-06-22 15:08:57 +0000361 if (isRev) ++NumTriangleFRev;
362 else ++NumTriangleFalse;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 } else {
Dan Gohman559d5132010-06-22 15:08:57 +0000364 if (isRev) ++NumTriangleRev;
365 else ++NumTriangle;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 }
367 }
368 break;
369 }
370 case ICDiamond: {
371 if (DisableDiamond) break;
David Greenead778702010-01-04 22:02:01 +0000372 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000373 << BBI.TrueBB->getNumber() << ",F:"
374 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000375 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greenead778702010-01-04 22:02:01 +0000376 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohman559d5132010-06-22 15:08:57 +0000377 if (RetVal) ++NumDiamonds;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 break;
379 }
380 }
381
382 Change |= RetVal;
383
384 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
385 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
386 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
387 break;
388 }
389
390 if (!Change)
391 break;
392 MadeChange |= Change;
393 }
394
395 // Delete tokens in case of early exit.
396 while (!Tokens.empty()) {
397 IfcvtToken *Token = Tokens.back();
398 Tokens.pop_back();
399 delete Token;
400 }
401
402 Tokens.clear();
403 Roots.clear();
404 BBAnalysis.clear();
405
Evan Chengd50455b2010-06-18 22:17:13 +0000406 if (MadeChange && IfCvtBranchFold) {
Bob Wilson93ab5612009-10-28 20:46:46 +0000407 BranchFolder BF(false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000408 BF.OptimizeFunction(MF, TII,
409 MF.getTarget().getRegisterInfo(),
410 getAnalysisIfAvailable<MachineModuleInfo>());
411 }
412
Evan Cheng24ff0562010-06-18 23:09:54 +0000413 MadeChange |= BFChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return MadeChange;
415}
416
417/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
418/// its 'true' successor.
419static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
420 MachineBasicBlock *TrueBB) {
421 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
422 E = BB->succ_end(); SI != E; ++SI) {
423 MachineBasicBlock *SuccBB = *SI;
424 if (SuccBB != TrueBB)
425 return SuccBB;
426 }
427 return NULL;
428}
429
430/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000431/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000433 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
435 TII->RemoveBranch(*BBI.BB);
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000436 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 std::swap(BBI.TrueBB, BBI.FalseBB);
438 return true;
439 }
440 return false;
441}
442
443/// getNextBlock - Returns the next block in the function blocks ordering. If
444/// it is the end, returns NULL.
445static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
446 MachineFunction::iterator I = BB;
447 MachineFunction::iterator E = BB->getParent()->end();
448 if (++I == E)
449 return NULL;
450 return I;
451}
452
453/// ValidSimple - Returns true if the 'true' block (along with its
454/// predecessor) forms a valid simple shape for ifcvt. It also returns the
455/// number of instructions that the ifcvt would need to duplicate if performed
456/// in Dups.
Owen Andersond4397bb2010-09-28 20:42:15 +0000457bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Owen Anderson97d32912010-10-01 22:45:50 +0000458 float Prediction, float Confidence) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 Dups = 0;
460 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
461 return false;
462
463 if (TrueBBI.IsBrAnalyzable)
464 return false;
465
466 if (TrueBBI.BB->pred_size() > 1) {
467 if (TrueBBI.CannotBeCopied ||
Owen Andersond4397bb2010-09-28 20:42:15 +0000468 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Owen Anderson97d32912010-10-01 22:45:50 +0000469 Prediction, Confidence))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 return false;
471 Dups = TrueBBI.NonPredSize;
472 }
473
474 return true;
475}
476
477/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
478/// with their common predecessor) forms a valid triangle shape for ifcvt.
479/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000480/// branches to the 'false' block rather than the other way around. It also
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481/// returns the number of instructions that the ifcvt would need to duplicate
482/// if performed in 'Dups'.
483bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Anderson97d32912010-10-01 22:45:50 +0000484 bool FalseBranch, unsigned &Dups,
485 float Prediction, float Confidence) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 Dups = 0;
487 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
488 return false;
489
490 if (TrueBBI.BB->pred_size() > 1) {
491 if (TrueBBI.CannotBeCopied)
492 return false;
493
494 unsigned Size = TrueBBI.NonPredSize;
495 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000496 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000497 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 --Size;
499 else {
500 MachineBasicBlock *FExit = FalseBranch
501 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
502 if (FExit)
503 // Require a conditional branch
504 ++Size;
505 }
506 }
Owen Anderson97d32912010-10-01 22:45:50 +0000507 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
508 Prediction, Confidence))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 return false;
510 Dups = Size;
511 }
512
513 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
514 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
515 MachineFunction::iterator I = TrueBBI.BB;
516 if (++I == TrueBBI.BB->getParent()->end())
517 return false;
518 TExit = I;
519 }
520 return TExit && TExit == FalseBBI.BB;
521}
522
523static
524MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
525 const TargetInstrInfo *TII) {
526 MachineBasicBlock::iterator I = BB->end();
527 while (I != BB->begin()) {
528 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000529 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 break;
531 }
532 return I;
533}
534
535/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
536/// with their common predecessor) forms a valid diamond shape for ifcvt.
537bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
538 unsigned &Dups1, unsigned &Dups2) const {
539 Dups1 = Dups2 = 0;
540 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
541 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
542 return false;
543
544 MachineBasicBlock *TT = TrueBBI.TrueBB;
545 MachineBasicBlock *FT = FalseBBI.TrueBB;
546
547 if (!TT && blockAlwaysFallThrough(TrueBBI))
548 TT = getNextBlock(TrueBBI.BB);
549 if (!FT && blockAlwaysFallThrough(FalseBBI))
550 FT = getNextBlock(FalseBBI.BB);
551 if (TT != FT)
552 return false;
553 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
554 return false;
555 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
556 return false;
557
558 // FIXME: Allow true block to have an early exit?
559 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
560 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
561 return false;
562
563 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
564 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000565 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
566 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
567 // Skip dbg_value instructions
568 while (TI != TIE && TI->isDebugValue())
569 ++TI;
570 while (FI != FIE && FI->isDebugValue())
571 ++FI;
572 while (TI != TIE && FI != FIE) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000573 // Skip dbg_value instructions. These do not count.
574 if (TI->isDebugValue()) {
575 while (TI != TIE && TI->isDebugValue())
576 ++TI;
577 if (TI == TIE)
578 break;
579 }
580 if (FI->isDebugValue()) {
581 while (FI != FIE && FI->isDebugValue())
582 ++FI;
583 if (FI == FIE)
584 break;
585 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 if (!TI->isIdenticalTo(FI))
587 break;
588 ++Dups1;
589 ++TI;
590 ++FI;
591 }
592
593 TI = firstNonBranchInst(TrueBBI.BB, TII);
594 FI = firstNonBranchInst(FalseBBI.BB, TII);
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000595 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
596 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Evan Chenga03a63c2010-06-18 21:52:57 +0000597 // Skip dbg_value instructions at end of the bb's.
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000598 while (TI != TIB && TI->isDebugValue())
599 --TI;
600 while (FI != FIB && FI->isDebugValue())
601 --FI;
602 while (TI != TIB && FI != FIB) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000603 // Skip dbg_value instructions. These do not count.
604 if (TI->isDebugValue()) {
605 while (TI != TIB && TI->isDebugValue())
606 --TI;
607 if (TI == TIB)
608 break;
609 }
610 if (FI->isDebugValue()) {
611 while (FI != FIB && FI->isDebugValue())
612 --FI;
613 if (FI == FIB)
614 break;
615 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 if (!TI->isIdenticalTo(FI))
617 break;
618 ++Dups2;
619 --TI;
620 --FI;
621 }
622
623 return true;
624}
625
626/// ScanInstructions - Scan all the instructions in the block to determine if
627/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000628/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629/// instruction which can clobber a predicate (e.g. condition code register).
630/// If so, the block is not predicable unless it's the last instruction.
631void IfConverter::ScanInstructions(BBInfo &BBI) {
632 if (BBI.IsDone)
633 return;
634
635 bool AlreadyPredicated = BBI.Predicate.size() > 0;
636 // First analyze the end of BB branches.
637 BBI.TrueBB = BBI.FalseBB = NULL;
638 BBI.BrCond.clear();
639 BBI.IsBrAnalyzable =
640 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
641 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
642
643 if (BBI.BrCond.size()) {
644 // No false branch. This BB must end with a conditional branch and a
645 // fallthrough.
646 if (!BBI.FalseBB)
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000647 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000648 if (!BBI.FalseBB) {
649 // Malformed bcc? True and false blocks are the same?
650 BBI.IsUnpredicable = true;
651 return;
652 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 }
654
655 // Then scan all the instructions.
656 BBI.NonPredSize = 0;
Bob Wilson9c30a772010-10-26 00:02:21 +0000657 BBI.ExtraCost = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
660 I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +0000661 if (I->isDebugValue())
662 continue;
663
Chris Lattner5b930372008-01-07 07:27:27 +0000664 const TargetInstrDesc &TID = I->getDesc();
665 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 BBI.CannotBeCopied = true;
667
668 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000669 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670
671 if (!isCondBr) {
Evan Cheng0cf9a822010-09-10 01:29:16 +0000672 if (!isPredicated) {
Bob Wilson9c30a772010-10-26 00:02:21 +0000673 BBI.NonPredSize++;
Evan Cheng0cf9a822010-09-10 01:29:16 +0000674 unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
Bob Wilson9c30a772010-10-26 00:02:21 +0000675 if (NumOps > 1)
676 BBI.ExtraCost += NumOps-1;
Evan Cheng0cf9a822010-09-10 01:29:16 +0000677 } else if (!AlreadyPredicated) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 // FIXME: This instruction is already predicated before the
679 // if-conversion pass. It's probably something like a conditional move.
680 // Mark this block unpredicable for now.
681 BBI.IsUnpredicable = true;
682 return;
683 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 }
685
686 if (BBI.ClobbersPred && !isPredicated) {
687 // Predicate modification instruction should end the block (except for
688 // already predicated instructions and end of block branches).
689 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000690 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 continue;
692 }
693
694 // Predicate may have been modified, the subsequent (currently)
695 // unpredicated instructions cannot be correctly predicated.
696 BBI.IsUnpredicable = true;
697 return;
698 }
699
700 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
701 // still potentially predicable.
702 std::vector<MachineOperand> PredDefs;
703 if (TII->DefinesPredicate(I, PredDefs))
704 BBI.ClobbersPred = true;
705
Evan Cheng76fe9892009-11-21 06:20:26 +0000706 if (!TII->isPredicable(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 BBI.IsUnpredicable = true;
708 return;
709 }
710 }
711}
712
713/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
714/// predicated by the specified predicate.
715bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000716 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 bool isTriangle, bool RevBranch) {
718 // If the block is dead or unpredicable, then it cannot be predicated.
719 if (BBI.IsDone || BBI.IsUnpredicable)
720 return false;
721
722 // If it is already predicated, check if its predicate subsumes the new
723 // predicate.
724 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
725 return false;
726
727 if (BBI.BrCond.size()) {
728 if (!isTriangle)
729 return false;
730
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000731 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000732 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
733 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (RevBranch) {
735 if (TII->ReverseBranchCondition(Cond))
736 return false;
737 }
738 if (TII->ReverseBranchCondition(RevPred) ||
739 !TII->SubsumesPredicate(Cond, RevPred))
740 return false;
741 }
742
743 return true;
744}
745
746/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
747/// the specified block. Record its successors and whether it looks like an
748/// if-conversion candidate.
749IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
750 std::vector<IfcvtToken*> &Tokens) {
751 BBInfo &BBI = BBAnalysis[BB->getNumber()];
752
753 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
754 return BBI;
755
756 BBI.BB = BB;
757 BBI.IsBeingAnalyzed = true;
758
759 ScanInstructions(BBI);
760
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000761 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000762 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 BBI.IsBeingAnalyzed = false;
764 BBI.IsAnalyzed = true;
765 return BBI;
766 }
767
768 // Do not ifcvt if either path is a back edge to the entry block.
769 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
770 BBI.IsBeingAnalyzed = false;
771 BBI.IsAnalyzed = true;
772 return BBI;
773 }
774
Evan Cheng4eb66e62009-06-15 21:24:34 +0000775 // Do not ifcvt if true and false fallthrough blocks are the same.
776 if (!BBI.FalseBB) {
777 BBI.IsBeingAnalyzed = false;
778 BBI.IsAnalyzed = true;
779 return BBI;
780 }
781
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
783 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
784
785 if (TrueBBI.IsDone && FalseBBI.IsDone) {
786 BBI.IsBeingAnalyzed = false;
787 BBI.IsAnalyzed = true;
788 return BBI;
789 }
790
Owen Andersond131b5b2008-08-14 22:49:33 +0000791 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
793
794 unsigned Dups = 0;
795 unsigned Dups2 = 0;
796 bool TNeedSub = TrueBBI.Predicate.size() > 0;
797 bool FNeedSub = FalseBBI.Predicate.size() > 0;
798 bool Enqueued = false;
Owen Andersond4397bb2010-09-28 20:42:15 +0000799
800 // Try to predict the branch, using loop info to guide us.
801 // General heuristics are:
802 // - backedge -> 90% taken
803 // - early exit -> 20% taken
Owen Anderson97d32912010-10-01 22:45:50 +0000804 // - branch predictor confidence -> 90%
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000805 float Prediction = 0.5f;
Owen Anderson97d32912010-10-01 22:45:50 +0000806 float Confidence = 0.9f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000807 MachineLoop *Loop = MLI->getLoopFor(BB);
808 if (Loop) {
809 if (TrueBBI.BB == Loop->getHeader())
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000810 Prediction = 0.9f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000811 else if (FalseBBI.BB == Loop->getHeader())
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000812 Prediction = 0.1f;
813
Owen Andersond4397bb2010-09-28 20:42:15 +0000814 MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
815 MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
816 if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000817 Prediction = 0.2f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000818 else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
Benjamin Kramer4aad8bd2010-09-29 22:38:50 +0000819 Prediction = 0.8f;
Owen Andersond4397bb2010-09-28 20:42:15 +0000820 }
821
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000823 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
824 TrueBBI.ExtraCost),
825 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
826 FalseBBI.ExtraCost),
Owen Anderson97d32912010-10-01 22:45:50 +0000827 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
829 FeasibilityAnalysis(FalseBBI, RevCond)) {
830 // Diamond:
831 // EBB
832 // / \_
833 // | |
834 // TBB FBB
835 // \ /
836 // TailBB
837 // Note TailBB can be empty.
838 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
839 Dups2));
840 Enqueued = true;
841 }
842
Owen Anderson97d32912010-10-01 22:45:50 +0000843 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000844 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000845 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
847 // Triangle:
848 // EBB
849 // | \_
850 // | |
851 // | TBB
852 // | /
853 // FBB
854 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
855 Enqueued = true;
856 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000857
Owen Anderson97d32912010-10-01 22:45:50 +0000858 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000859 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000860 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
862 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
863 Enqueued = true;
864 }
865
Owen Anderson97d32912010-10-01 22:45:50 +0000866 if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000867 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000868 Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
870 // Simple (split, no rejoin):
871 // EBB
872 // | \_
873 // | |
874 // | TBB---> exit
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000875 // |
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876 // FBB
877 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
878 Enqueued = true;
879 }
880
881 if (CanRevCond) {
882 // Try the other path...
Owen Anderson97d32912010-10-01 22:45:50 +0000883 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
884 1.0-Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000885 MeetIfcvtSizeLimit(*FalseBBI.BB,
886 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000887 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
889 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
890 Enqueued = true;
891 }
892
Owen Anderson97d32912010-10-01 22:45:50 +0000893 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
894 1.0-Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000895 MeetIfcvtSizeLimit(*FalseBBI.BB,
896 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000897 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
899 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
900 Enqueued = true;
901 }
902
Owen Anderson97d32912010-10-01 22:45:50 +0000903 if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
Bob Wilson9c30a772010-10-26 00:02:21 +0000904 MeetIfcvtSizeLimit(*FalseBBI.BB,
905 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Anderson97d32912010-10-01 22:45:50 +0000906 1.0-Prediction, Confidence) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 FeasibilityAnalysis(FalseBBI, RevCond)) {
908 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
909 Enqueued = true;
910 }
911 }
912
913 BBI.IsEnqueued = Enqueued;
914 BBI.IsBeingAnalyzed = false;
915 BBI.IsAnalyzed = true;
916 return BBI;
917}
918
919/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson89b9c322010-06-15 18:57:15 +0000920/// candidates.
921void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 std::vector<IfcvtToken*> &Tokens) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 std::set<MachineBasicBlock*> Visited;
924 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
925 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
926 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
927 MachineBasicBlock *BB = *I;
928 AnalyzeBlock(BB, Tokens);
929 }
930 }
931
932 // Sort to favor more complex ifcvt scheme.
933 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934}
935
936/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
937/// that all the intervening blocks are empty (given BB can fall through to its
938/// next block).
939static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng160f30c2010-06-16 07:35:02 +0000940 MachineFunction::iterator PI = BB;
941 MachineFunction::iterator I = llvm::next(PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 MachineFunction::iterator TI = ToBB;
943 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng160f30c2010-06-16 07:35:02 +0000944 while (I != TI) {
945 // Check isSuccessor to avoid case where the next block is empty, but
946 // it's not a successor.
947 if (I == E || !I->empty() || !PI->isSuccessor(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 return false;
Evan Cheng160f30c2010-06-16 07:35:02 +0000949 PI = I++;
950 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 return true;
952}
953
954/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
955/// to determine if it can be if-converted. If predecessor is already enqueued,
956/// dequeue it!
957void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
958 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
959 E = BB->pred_end(); PI != E; ++PI) {
960 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
961 if (PBBI.IsDone || PBBI.BB == BB)
962 continue;
963 PBBI.IsAnalyzed = false;
964 PBBI.IsEnqueued = false;
965 }
966}
967
968/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
969///
970static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
971 const TargetInstrInfo *TII) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000972 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmane458ea82008-08-22 16:07:55 +0000973 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000974 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975}
976
977/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
978/// successors.
979void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
980 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000981 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
983 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
984}
985
Evan Cheng160f30c2010-06-16 07:35:02 +0000986/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
987/// modeled as read + write (sort like two-address instructions). These
988/// routines track register liveness and add implicit uses to if-converted
989/// instructions to conform to the model.
990static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
991 const TargetRegisterInfo *TRI) {
992 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
993 E = BB->livein_end(); I != E; ++I) {
994 unsigned Reg = *I;
995 Redefs.insert(Reg);
996 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
997 *Subreg; ++Subreg)
998 Redefs.insert(*Subreg);
999 }
1000}
1001
1002static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
1003 const TargetRegisterInfo *TRI,
1004 bool AddImpUse = false) {
1005 SmallVector<unsigned, 4> Defs;
1006 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1007 const MachineOperand &MO = MI->getOperand(i);
1008 if (!MO.isReg())
1009 continue;
1010 unsigned Reg = MO.getReg();
1011 if (!Reg)
1012 continue;
1013 if (MO.isDef())
1014 Defs.push_back(Reg);
1015 else if (MO.isKill()) {
1016 Redefs.erase(Reg);
1017 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1018 Redefs.erase(*SR);
1019 }
1020 }
1021 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1022 unsigned Reg = Defs[i];
1023 if (Redefs.count(Reg)) {
1024 if (AddImpUse)
1025 // Treat predicated update as read + write.
1026 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Jim Grosbachf44b1712010-06-25 22:02:28 +00001027 true/*IsImp*/,false/*IsKill*/));
Evan Cheng160f30c2010-06-16 07:35:02 +00001028 } else {
1029 Redefs.insert(Reg);
1030 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1031 Redefs.insert(*SR);
1032 }
1033 }
1034}
1035
1036static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1037 MachineBasicBlock::iterator E,
1038 SmallSet<unsigned,4> &Redefs,
1039 const TargetRegisterInfo *TRI) {
1040 while (I != E) {
1041 UpdatePredRedefs(I, Redefs, TRI);
1042 ++I;
1043 }
1044}
1045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1047///
1048bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1049 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1050 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1051 BBInfo *CvtBBI = &TrueBBI;
1052 BBInfo *NextBBI = &FalseBBI;
1053
Owen Andersond131b5b2008-08-14 22:49:33 +00001054 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 if (Kind == ICSimpleFalse)
1056 std::swap(CvtBBI, NextBBI);
1057
1058 if (CvtBBI->IsDone ||
1059 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1060 // Something has changed. It's no longer safe to predicate this block.
1061 BBI.IsAnalyzed = false;
1062 CvtBBI->IsAnalyzed = false;
1063 return false;
1064 }
1065
1066 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001067 if (TII->ReverseBranchCondition(Cond))
1068 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069
Bob Wilson8d7f1622010-06-19 05:33:57 +00001070 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001071 // predicated instructions.
1072 SmallSet<unsigned, 4> Redefs;
1073 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1074 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 if (CvtBBI->BB->pred_size() > 1) {
1077 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001078 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001080 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 } else {
Evan Cheng160f30c2010-06-16 07:35:02 +00001082 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083
1084 // Merge converted block into entry block.
1085 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1086 MergeBlocks(BBI, *CvtBBI);
1087 }
1088
1089 bool IterIfcvt = true;
1090 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1091 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1092 BBI.HasFallThrough = false;
1093 // Now ifcvt'd block will look like this:
1094 // BB:
1095 // ...
1096 // t, f = cmp
1097 // if t op
1098 // b BBf
1099 //
1100 // We cannot further ifcvt this block because the unconditional branch
1101 // will have to be predicated on the new condition, that will not be
1102 // available if cmp executes.
1103 IterIfcvt = false;
1104 }
1105
1106 RemoveExtraEdges(BBI);
1107
1108 // Update block info. BB can be iteratively if-converted.
1109 if (!IterIfcvt)
1110 BBI.IsDone = true;
1111 InvalidatePreds(BBI.BB);
1112 CvtBBI->IsDone = true;
1113
1114 // FIXME: Must maintain LiveIns.
1115 return true;
1116}
1117
1118/// IfConvertTriangle - If convert a triangle sub-CFG.
1119///
1120bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1121 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1122 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1123 BBInfo *CvtBBI = &TrueBBI;
1124 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001125 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126
Owen Andersond131b5b2008-08-14 22:49:33 +00001127 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1129 std::swap(CvtBBI, NextBBI);
1130
1131 if (CvtBBI->IsDone ||
1132 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1133 // Something has changed. It's no longer safe to predicate this block.
1134 BBI.IsAnalyzed = false;
1135 CvtBBI->IsAnalyzed = false;
1136 return false;
1137 }
1138
1139 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001140 if (TII->ReverseBranchCondition(Cond))
1141 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142
1143 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001144 if (ReverseBranchCondition(*CvtBBI)) {
1145 // BB has been changed, modify its predecessors (except for this
1146 // one) so they don't get ifcvt'ed based on bad intel.
1147 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1148 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1149 MachineBasicBlock *PBB = *PI;
1150 if (PBB == BBI.BB)
1151 continue;
1152 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1153 if (PBBI.IsEnqueued) {
1154 PBBI.IsAnalyzed = false;
1155 PBBI.IsEnqueued = false;
1156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157 }
1158 }
1159 }
1160
Bob Wilson8d7f1622010-06-19 05:33:57 +00001161 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001162 // predicated instructions.
1163 SmallSet<unsigned, 4> Redefs;
1164 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1165 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1166
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson2e99a562010-06-29 00:55:23 +00001168 if (CvtBBI->BB->pred_size() > 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001170 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001172 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 } else {
1174 // Predicate the 'true' block after removing its branch.
1175 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng160f30c2010-06-16 07:35:02 +00001176 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 // Now merge the entry of the triangle with the true block.
1179 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson2e99a562010-06-29 00:55:23 +00001180 MergeBlocks(BBI, *CvtBBI, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 }
1182
1183 // If 'true' block has a 'false' successor, add an exit branch to it.
1184 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001185 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1186 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 if (TII->ReverseBranchCondition(RevCond))
1188 assert(false && "Unable to reverse branch condition!");
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001189 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1191 }
1192
1193 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001194 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 bool FalseBBDead = false;
1196 bool IterIfcvt = true;
1197 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1198 if (!isFallThrough) {
1199 // Only merge them if the true block does not fallthrough to the false
1200 // block. By not merging them, we make it possible to iteratively
1201 // ifcvt the blocks.
1202 if (!HasEarlyExit &&
1203 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1204 MergeBlocks(BBI, *NextBBI);
1205 FalseBBDead = true;
1206 } else {
1207 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1208 BBI.HasFallThrough = false;
1209 }
1210 // Mixed predicated and unpredicated code. This cannot be iteratively
1211 // predicated.
1212 IterIfcvt = false;
1213 }
1214
1215 RemoveExtraEdges(BBI);
1216
1217 // Update block info. BB can be iteratively if-converted.
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001218 if (!IterIfcvt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 BBI.IsDone = true;
1220 InvalidatePreds(BBI.BB);
1221 CvtBBI->IsDone = true;
1222 if (FalseBBDead)
1223 NextBBI->IsDone = true;
1224
1225 // FIXME: Must maintain LiveIns.
1226 return true;
1227}
1228
1229/// IfConvertDiamond - If convert a diamond sub-CFG.
1230///
1231bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1232 unsigned NumDups1, unsigned NumDups2) {
1233 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1234 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1235 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001236 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 if (!TailBB) {
1238 if (blockAlwaysFallThrough(TrueBBI))
1239 TailBB = FalseBBI.TrueBB;
1240 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1241 }
1242
1243 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1244 TrueBBI.BB->pred_size() > 1 ||
1245 FalseBBI.BB->pred_size() > 1) {
1246 // Something has changed. It's no longer safe to predicate these blocks.
1247 BBI.IsAnalyzed = false;
1248 TrueBBI.IsAnalyzed = false;
1249 FalseBBI.IsAnalyzed = false;
1250 return false;
1251 }
1252
Bob Wilson2e99a562010-06-29 00:55:23 +00001253 // Put the predicated instructions from the 'true' block before the
1254 // instructions from the 'false' block, unless the true block would clobber
1255 // the predicate, in which case, do the opposite.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 BBInfo *BBI1 = &TrueBBI;
1257 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001258 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001259 if (TII->ReverseBranchCondition(RevCond))
1260 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001261 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1262 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263
1264 // Figure out the more profitable ordering.
1265 bool DoSwap = false;
1266 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1267 DoSwap = true;
1268 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1269 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1270 DoSwap = true;
1271 }
1272 if (DoSwap) {
1273 std::swap(BBI1, BBI2);
1274 std::swap(Cond1, Cond2);
1275 }
1276
1277 // Remove the conditional branch from entry to the blocks.
1278 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1279
Jim Grosbachf44b1712010-06-25 22:02:28 +00001280 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng160f30c2010-06-16 07:35:02 +00001281 // predicated instructions.
1282 SmallSet<unsigned, 4> Redefs;
1283 InitPredRedefs(BBI1->BB, Redefs, TRI);
1284
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 // Remove the duplicated instructions at the beginnings of both paths.
1286 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1287 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachf8648062010-06-14 21:30:32 +00001288 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1289 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1290 // Skip dbg_value instructions
1291 while (DI1 != DIE1 && DI1->isDebugValue())
1292 ++DI1;
1293 while (DI2 != DIE2 && DI2->isDebugValue())
1294 ++DI2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 BBI1->NonPredSize -= NumDups1;
1296 BBI2->NonPredSize -= NumDups1;
Jim Grosbach8ea33f62010-06-28 20:26:00 +00001297
1298 // Skip past the dups on each side separately since there may be
1299 // differing dbg_value entries.
1300 for (unsigned i = 0; i < NumDups1; ++DI1) {
1301 if (!DI1->isDebugValue())
1302 ++i;
1303 }
Jim Grosbach1213ebc2010-06-25 23:05:46 +00001304 while (NumDups1 != 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 ++DI2;
Jim Grosbach8ea33f62010-06-28 20:26:00 +00001306 if (!DI2->isDebugValue())
1307 --NumDups1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001309
1310 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1312 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1313
1314 // Predicate the 'true' block after removing its branch.
1315 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1316 DI1 = BBI1->BB->end();
Jim Grosbachf8648062010-06-14 21:30:32 +00001317 for (unsigned i = 0; i != NumDups2; ) {
1318 // NumDups2 only counted non-dbg_value instructions, so this won't
1319 // run off the head of the list.
1320 assert (DI1 != BBI1->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 --DI1;
Jim Grosbachf8648062010-06-14 21:30:32 +00001322 // skip dbg_value instructions
1323 if (!DI1->isDebugValue())
1324 ++i;
1325 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng160f30c2010-06-16 07:35:02 +00001327 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328
1329 // Predicate the 'false' block.
1330 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1331 DI2 = BBI2->BB->end();
1332 while (NumDups2 != 0) {
Jim Grosbachf8648062010-06-14 21:30:32 +00001333 // NumDups2 only counted non-dbg_value instructions, so this won't
1334 // run off the head of the list.
1335 assert (DI2 != BBI2->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 --DI2;
Jim Grosbachf8648062010-06-14 21:30:32 +00001337 // skip dbg_value instructions
1338 if (!DI2->isDebugValue())
1339 --NumDups2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001341 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342
1343 // Merge the true block into the entry of the diamond.
Bob Wilson2e99a562010-06-29 00:55:23 +00001344 MergeBlocks(BBI, *BBI1, TailBB == 0);
1345 MergeBlocks(BBI, *BBI2, TailBB == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001347 // If the if-converted block falls through or unconditionally branches into
1348 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 // fold the tail block in as well. Otherwise, unless it falls through to the
1350 // tail, add a unconditional branch to it.
1351 if (TailBB) {
1352 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson2e99a562010-06-29 00:55:23 +00001353 bool CanMergeTail = !TailBBI.HasFallThrough;
1354 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1355 // check if there are any other predecessors besides those.
1356 unsigned NumPreds = TailBB->pred_size();
1357 if (NumPreds > 1)
1358 CanMergeTail = false;
1359 else if (NumPreds == 1 && CanMergeTail) {
1360 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1361 if (*PI != BBI1->BB && *PI != BBI2->BB)
1362 CanMergeTail = false;
1363 }
1364 if (CanMergeTail) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 MergeBlocks(BBI, TailBBI);
1366 TailBBI.IsDone = true;
1367 } else {
Bob Wilson2e99a562010-06-29 00:55:23 +00001368 BBI.BB->addSuccessor(TailBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 InsertUncondBranch(BBI.BB, TailBB, TII);
1370 BBI.HasFallThrough = false;
1371 }
1372 }
1373
Bob Wilson2e99a562010-06-29 00:55:23 +00001374 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1375 // which can happen here if TailBB is unanalyzable and is merged, so
1376 // explicitly remove BBI1 and BBI2 as successors.
1377 BBI.BB->removeSuccessor(BBI1->BB);
1378 BBI.BB->removeSuccessor(BBI2->BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 RemoveExtraEdges(BBI);
1380
1381 // Update block info.
1382 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1383 InvalidatePreds(BBI.BB);
1384
1385 // FIXME: Must maintain LiveIns.
1386 return true;
1387}
1388
1389/// PredicateBlock - Predicate instructions from the start of the block to the
1390/// specified end with the specified condition.
1391void IfConverter::PredicateBlock(BBInfo &BBI,
1392 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +00001393 SmallVectorImpl<MachineOperand> &Cond,
1394 SmallSet<unsigned, 4> &Redefs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001396 if (I->isDebugValue() || TII->isPredicated(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 continue;
1398 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001399#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001400 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001401#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001402 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001404
Bob Wilson8d7f1622010-06-19 05:33:57 +00001405 // If the predicated instruction now redefines a register as the result of
Evan Cheng160f30c2010-06-16 07:35:02 +00001406 // if-conversion, add an implicit kill.
1407 UpdatePredRedefs(I, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 }
1409
1410 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1411
1412 BBI.IsAnalyzed = false;
1413 BBI.NonPredSize = 0;
1414
Dan Gohman559d5132010-06-22 15:08:57 +00001415 ++NumIfConvBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416}
1417
1418/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1419/// the destination block. Skip end of block branches if IgnoreBr is true.
1420void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001421 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +00001422 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001424 MachineFunction &MF = *ToBBI.BB->getParent();
1425
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1427 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001428 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 // Do not copy the end of the block branches.
Bob Wilsond00487b2010-06-18 17:07:23 +00001430 if (IgnoreBr && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 break;
1432
Dan Gohman221a4372008-07-07 23:14:23 +00001433 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilson9c30a772010-10-26 00:02:21 +00001435 ToBBI.NonPredSize++;
Evan Cheng0cf9a822010-09-10 01:29:16 +00001436 unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
Bob Wilson9c30a772010-10-26 00:02:21 +00001437 if (NumOps > 1)
1438 ToBBI.ExtraCost += NumOps-1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439
Bob Wilsond00487b2010-06-18 17:07:23 +00001440 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001442#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001443 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001444#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001445 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001447 }
1448
Bob Wilson8d7f1622010-06-19 05:33:57 +00001449 // If the predicated instruction now redefines a register as the result of
Evan Cheng160f30c2010-06-16 07:35:02 +00001450 // if-conversion, add an implicit kill.
1451 UpdatePredRedefs(MI, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 }
1453
Bob Wilson2e99a562010-06-29 00:55:23 +00001454 if (!IgnoreBr) {
1455 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1456 FromBBI.BB->succ_end());
1457 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1458 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459
Bob Wilson2e99a562010-06-29 00:55:23 +00001460 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1461 MachineBasicBlock *Succ = Succs[i];
1462 // Fallthrough edge can't be transferred.
1463 if (Succ == FallThrough)
1464 continue;
1465 ToBBI.BB->addSuccessor(Succ);
1466 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 }
1468
1469 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1470 std::back_inserter(ToBBI.Predicate));
1471 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1472
1473 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1474 ToBBI.IsAnalyzed = false;
1475
Dan Gohman559d5132010-06-22 15:08:57 +00001476 ++NumDupBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477}
1478
1479/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson2e99a562010-06-29 00:55:23 +00001480/// This will leave FromBB as an empty block, so remove all of its
1481/// successor edges except for the fall-through edge. If AddEdges is true,
1482/// i.e., when FromBBI's branch is being moved, add those successor edges to
1483/// ToBBI.
1484void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 ToBBI.BB->splice(ToBBI.BB->end(),
1486 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1487
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1489 FromBBI.BB->succ_end());
1490 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1491 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1492
1493 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1494 MachineBasicBlock *Succ = Succs[i];
1495 // Fallthrough edge can't be transferred.
1496 if (Succ == FallThrough)
1497 continue;
1498 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson2e99a562010-06-29 00:55:23 +00001499 if (AddEdges)
1500 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 }
1502
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001503 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001504 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 FromBBI.BB->addSuccessor(NBB);
1506
1507 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1508 std::back_inserter(ToBBI.Predicate));
1509 FromBBI.Predicate.clear();
1510
1511 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilson9c30a772010-10-26 00:02:21 +00001512 ToBBI.ExtraCost += FromBBI.ExtraCost;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 FromBBI.NonPredSize = 0;
Bob Wilson9c30a772010-10-26 00:02:21 +00001514 FromBBI.ExtraCost = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515
1516 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1517 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1518 ToBBI.IsAnalyzed = false;
1519 FromBBI.IsAnalyzed = false;
1520}