blob: 41734dd7b306f51eb2b6355e1021769b290e896a [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"
20#include "llvm/Target/TargetInstrInfo.h"
21#include "llvm/Target/TargetLowering.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000025#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30using namespace llvm;
31
Chris Lattner4335bff2008-01-07 05:40:58 +000032// Hidden options for help debugging.
33static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
34static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
35static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000036static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner4335bff2008-01-07 05:40:58 +000037 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000038static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000039 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000040static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner4335bff2008-01-07 05:40:58 +000041 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000042static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000043 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000044static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000045 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000046static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000047 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000048static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner4335bff2008-01-07 05:40:58 +000049 cl::init(false), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050
51STATISTIC(NumSimple, "Number of simple if-conversions performed");
52STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
53STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
54STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
55STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
56STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
57STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
58STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
59STATISTIC(NumDupBBs, "Number of duplicated blocks");
60
61namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000062 class IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063 enum IfcvtKind {
64 ICNotClassfied, // BB data valid, but not classified.
65 ICSimpleFalse, // Same as ICSimple, but on the false path.
66 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
67 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
68 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
69 ICTriangleFalse, // Same as ICTriangle, but on the false path.
70 ICTriangle, // BB is entry of a triangle sub-CFG.
71 ICDiamond // BB is entry of a diamond sub-CFG.
72 };
73
74 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
75 /// if-conversion feasibility analysis. This includes results from
76 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
77 /// classification, and common tail block of its successors (if it's a
78 /// diamond shape), its size, whether it's predicable, and whether any
79 /// instruction can clobber the 'would-be' predicate.
80 ///
81 /// IsDone - True if BB is not to be considered for ifcvt.
82 /// IsBeingAnalyzed - True if BB is currently being analyzed.
83 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
84 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
85 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
86 /// HasFallThrough - True if BB may fallthrough to the following BB.
87 /// IsUnpredicable - True if BB is known to be unpredicable.
88 /// ClobbersPred - True if BB could modify predicates (e.g. has
89 /// cmp, call, etc.)
90 /// NonPredSize - Number of non-predicated instructions.
91 /// BB - Corresponding MachineBasicBlock.
92 /// TrueBB / FalseBB- See AnalyzeBranch().
93 /// BrCond - Conditions for end of block conditional branches.
94 /// Predicate - Predicate used in the BB.
95 struct BBInfo {
96 bool IsDone : 1;
97 bool IsBeingAnalyzed : 1;
98 bool IsAnalyzed : 1;
99 bool IsEnqueued : 1;
100 bool IsBrAnalyzable : 1;
101 bool HasFallThrough : 1;
102 bool IsUnpredicable : 1;
103 bool CannotBeCopied : 1;
104 bool ClobbersPred : 1;
105 unsigned NonPredSize;
106 MachineBasicBlock *BB;
107 MachineBasicBlock *TrueBB;
108 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000109 SmallVector<MachineOperand, 4> BrCond;
110 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
112 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
113 HasFallThrough(false), IsUnpredicable(false),
114 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
115 BB(0), TrueBB(0), FalseBB(0) {}
116 };
117
Bob Wilson01320da2010-06-15 18:19:27 +0000118 /// IfcvtToken - Record information about pending if-conversions to attempt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119 /// BBI - Corresponding BBInfo.
120 /// Kind - Type of block. See IfcvtKind.
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000121 /// NeedSubsumption - True if the to-be-predicated BB has already been
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 /// predicated.
123 /// NumDups - Number of instructions that would be duplicated due
124 /// to this if-conversion. (For diamonds, the number of
125 /// identical instructions at the beginnings of both
126 /// paths).
127 /// NumDups2 - For diamonds, the number of identical instructions
128 /// at the ends of both paths.
129 struct IfcvtToken {
130 BBInfo &BBI;
131 IfcvtKind Kind;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000132 bool NeedSubsumption;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 unsigned NumDups;
134 unsigned NumDups2;
135 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000136 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137 };
138
139 /// Roots - Basic blocks that do not have successors. These are the starting
140 /// points of Graph traversal.
141 std::vector<MachineBasicBlock*> Roots;
142
143 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
144 /// basic block number.
145 std::vector<BBInfo> BBAnalysis;
146
147 const TargetLowering *TLI;
148 const TargetInstrInfo *TII;
149 bool MadeChange;
Owen Anderson03f2a7b2009-06-24 23:41:44 +0000150 int FnNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 public:
152 static char ID;
Bob Wilson93ab5612009-10-28 20:46:46 +0000153 IfConverter() : MachineFunctionPass(&ID), FnNum(-1) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154
155 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000156 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157
158 private:
159 bool ReverseBranchCondition(BBInfo &BBI);
160 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
161 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
162 bool FalseBranch, unsigned &Dups) const;
163 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
164 unsigned &Dups1, unsigned &Dups2) const;
165 void ScanInstructions(BBInfo &BBI);
166 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
167 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000168 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 bool isTriangle = false, bool RevBranch = false);
Bob Wilson89b9c322010-06-15 18:57:15 +0000170 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 void InvalidatePreds(MachineBasicBlock *BB);
172 void RemoveExtraEdges(BBInfo &BBI);
173 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
174 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
175 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
176 unsigned NumDups1, unsigned NumDups2);
177 void PredicateBlock(BBInfo &BBI,
178 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +0000179 SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000181 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 bool IgnoreBr = false);
183 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
184
185 bool MeetIfcvtSizeLimit(unsigned Size) const {
186 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
187 }
188
189 // blockAlwaysFallThrough - Block ends without a terminator.
190 bool blockAlwaysFallThrough(BBInfo &BBI) const {
191 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
192 }
193
194 // IfcvtTokenCmp - Used to sort if-conversion candidates.
195 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
196 int Incr1 = (C1->Kind == ICDiamond)
197 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
198 int Incr2 = (C2->Kind == ICDiamond)
199 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
200 if (Incr1 > Incr2)
201 return true;
202 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000203 // Favors subsumption.
204 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000206 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 // Favors diamond over triangle, etc.
208 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
209 return true;
210 else if (C1->Kind == C2->Kind)
211 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
212 }
213 }
214 return false;
215 }
216 };
217
218 char IfConverter::ID = 0;
219}
220
Bob Wilson93ab5612009-10-28 20:46:46 +0000221static RegisterPass<IfConverter>
222X("if-converter", "If Converter");
223
224FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225
226bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
227 TLI = MF.getTarget().getTargetLowering();
228 TII = MF.getTarget().getInstrInfo();
229 if (!TII) return false;
230
David Greenead778702010-01-04 22:02:01 +0000231 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000232 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233
234 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greenead778702010-01-04 22:02:01 +0000235 DEBUG(dbgs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return false;
237 }
David Greenead778702010-01-04 22:02:01 +0000238 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 MF.RenumberBlocks();
241 BBAnalysis.resize(MF.getNumBlockIDs());
242
243 // Look for root nodes, i.e. blocks without successors.
244 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000245 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 Roots.push_back(I);
247
248 std::vector<IfcvtToken*> Tokens;
249 MadeChange = false;
250 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
251 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
252 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000253 // Do an initial analysis for each basic block and find all the potential
254 // candidates to perform if-conversion.
Bob Wilson89b9c322010-06-15 18:57:15 +0000255 bool Change = false;
256 AnalyzeBlocks(MF, Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 while (!Tokens.empty()) {
258 IfcvtToken *Token = Tokens.back();
259 Tokens.pop_back();
260 BBInfo &BBI = Token->BBI;
261 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000262 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000263 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000264
265 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266
267 // If the block has been evicted out of the queue or it has already been
268 // marked dead (due to it being predicated), then skip it.
269 if (BBI.IsDone)
270 BBI.IsEnqueued = false;
271 if (!BBI.IsEnqueued)
272 continue;
273
274 BBI.IsEnqueued = false;
275
276 bool RetVal = false;
277 switch (Kind) {
278 default: assert(false && "Unexpected!");
279 break;
280 case ICSimple:
281 case ICSimpleFalse: {
282 bool isFalse = Kind == ICSimpleFalse;
283 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000284 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
285 " false" : "")
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000286 << "): BB#" << BBI.BB->getNumber() << " ("
287 << ((Kind == ICSimpleFalse)
288 ? BBI.FalseBB->getNumber()
289 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 RetVal = IfConvertSimple(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000291 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000292 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 if (isFalse) NumSimpleFalse++;
294 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000295 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 break;
297 }
298 case ICTriangle:
299 case ICTriangleRev:
300 case ICTriangleFalse:
301 case ICTriangleFRev: {
302 bool isFalse = Kind == ICTriangleFalse;
303 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
304 if (DisableTriangle && !isFalse && !isRev) break;
305 if (DisableTriangleR && !isFalse && isRev) break;
306 if (DisableTriangleF && isFalse && !isRev) break;
307 if (DisableTriangleFR && isFalse && isRev) break;
David Greenead778702010-01-04 22:02:01 +0000308 DEBUG(dbgs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 if (isFalse)
David Greenead778702010-01-04 22:02:01 +0000310 DEBUG(dbgs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311 if (isRev)
David Greenead778702010-01-04 22:02:01 +0000312 DEBUG(dbgs() << " rev");
313 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000314 << BBI.TrueBB->getNumber() << ",F:"
315 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 RetVal = IfConvertTriangle(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000317 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 if (RetVal) {
319 if (isFalse) {
320 if (isRev) NumTriangleFRev++;
321 else NumTriangleFalse++;
322 } else {
323 if (isRev) NumTriangleRev++;
324 else NumTriangle++;
325 }
326 }
327 break;
328 }
329 case ICDiamond: {
330 if (DisableDiamond) break;
David Greenead778702010-01-04 22:02:01 +0000331 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000332 << BBI.TrueBB->getNumber() << ",F:"
333 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000334 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greenead778702010-01-04 22:02:01 +0000335 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 if (RetVal) NumDiamonds++;
337 break;
338 }
339 }
340
341 Change |= RetVal;
342
343 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
344 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
345 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
346 break;
347 }
348
349 if (!Change)
350 break;
351 MadeChange |= Change;
352 }
353
354 // Delete tokens in case of early exit.
355 while (!Tokens.empty()) {
356 IfcvtToken *Token = Tokens.back();
357 Tokens.pop_back();
358 delete Token;
359 }
360
361 Tokens.clear();
362 Roots.clear();
363 BBAnalysis.clear();
364
Evan Cheng9dcb7602009-09-04 07:47:40 +0000365 if (MadeChange) {
Bob Wilson93ab5612009-10-28 20:46:46 +0000366 BranchFolder BF(false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000367 BF.OptimizeFunction(MF, TII,
368 MF.getTarget().getRegisterInfo(),
369 getAnalysisIfAvailable<MachineModuleInfo>());
370 }
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 return MadeChange;
373}
374
375/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
376/// its 'true' successor.
377static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
378 MachineBasicBlock *TrueBB) {
379 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
380 E = BB->succ_end(); SI != E; ++SI) {
381 MachineBasicBlock *SuccBB = *SI;
382 if (SuccBB != TrueBB)
383 return SuccBB;
384 }
385 return NULL;
386}
387
388/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000389/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
391 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
392 TII->RemoveBranch(*BBI.BB);
393 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
394 std::swap(BBI.TrueBB, BBI.FalseBB);
395 return true;
396 }
397 return false;
398}
399
400/// getNextBlock - Returns the next block in the function blocks ordering. If
401/// it is the end, returns NULL.
402static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
403 MachineFunction::iterator I = BB;
404 MachineFunction::iterator E = BB->getParent()->end();
405 if (++I == E)
406 return NULL;
407 return I;
408}
409
410/// ValidSimple - Returns true if the 'true' block (along with its
411/// predecessor) forms a valid simple shape for ifcvt. It also returns the
412/// number of instructions that the ifcvt would need to duplicate if performed
413/// in Dups.
414bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
415 Dups = 0;
416 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
417 return false;
418
419 if (TrueBBI.IsBrAnalyzable)
420 return false;
421
422 if (TrueBBI.BB->pred_size() > 1) {
423 if (TrueBBI.CannotBeCopied ||
424 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
425 return false;
426 Dups = TrueBBI.NonPredSize;
427 }
428
429 return true;
430}
431
432/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
433/// with their common predecessor) forms a valid triangle shape for ifcvt.
434/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000435/// branches to the 'false' block rather than the other way around. It also
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436/// returns the number of instructions that the ifcvt would need to duplicate
437/// if performed in 'Dups'.
438bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
439 bool FalseBranch, unsigned &Dups) const {
440 Dups = 0;
441 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
442 return false;
443
444 if (TrueBBI.BB->pred_size() > 1) {
445 if (TrueBBI.CannotBeCopied)
446 return false;
447
448 unsigned Size = TrueBBI.NonPredSize;
449 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000450 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000451 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 --Size;
453 else {
454 MachineBasicBlock *FExit = FalseBranch
455 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
456 if (FExit)
457 // Require a conditional branch
458 ++Size;
459 }
460 }
461 if (Size > TLI->getIfCvtDupBlockSizeLimit())
462 return false;
463 Dups = Size;
464 }
465
466 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
467 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
468 MachineFunction::iterator I = TrueBBI.BB;
469 if (++I == TrueBBI.BB->getParent()->end())
470 return false;
471 TExit = I;
472 }
473 return TExit && TExit == FalseBBI.BB;
474}
475
476static
477MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
478 const TargetInstrInfo *TII) {
479 MachineBasicBlock::iterator I = BB->end();
480 while (I != BB->begin()) {
481 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000482 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 break;
484 }
485 return I;
486}
487
488/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
489/// with their common predecessor) forms a valid diamond shape for ifcvt.
490bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
491 unsigned &Dups1, unsigned &Dups2) const {
492 Dups1 = Dups2 = 0;
493 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
494 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
495 return false;
496
497 MachineBasicBlock *TT = TrueBBI.TrueBB;
498 MachineBasicBlock *FT = FalseBBI.TrueBB;
499
500 if (!TT && blockAlwaysFallThrough(TrueBBI))
501 TT = getNextBlock(TrueBBI.BB);
502 if (!FT && blockAlwaysFallThrough(FalseBBI))
503 FT = getNextBlock(FalseBBI.BB);
504 if (TT != FT)
505 return false;
506 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
507 return false;
508 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
509 return false;
510
511 // FIXME: Allow true block to have an early exit?
512 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
513 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
514 return false;
515
516 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
517 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000518 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
519 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
520 // Skip dbg_value instructions
521 while (TI != TIE && TI->isDebugValue())
522 ++TI;
523 while (FI != FIE && FI->isDebugValue())
524 ++FI;
525 while (TI != TIE && FI != FIE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526 if (!TI->isIdenticalTo(FI))
527 break;
528 ++Dups1;
529 ++TI;
530 ++FI;
531 }
532
533 TI = firstNonBranchInst(TrueBBI.BB, TII);
534 FI = firstNonBranchInst(FalseBBI.BB, TII);
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000535 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
536 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
537 // Skip dbg_value instructions
538 while (TI != TIB && TI->isDebugValue())
539 --TI;
540 while (FI != FIB && FI->isDebugValue())
541 --FI;
542 while (TI != TIB && FI != FIB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 if (!TI->isIdenticalTo(FI))
544 break;
545 ++Dups2;
546 --TI;
547 --FI;
548 }
549
550 return true;
551}
552
553/// ScanInstructions - Scan all the instructions in the block to determine if
554/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000555/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556/// instruction which can clobber a predicate (e.g. condition code register).
557/// If so, the block is not predicable unless it's the last instruction.
558void IfConverter::ScanInstructions(BBInfo &BBI) {
559 if (BBI.IsDone)
560 return;
561
562 bool AlreadyPredicated = BBI.Predicate.size() > 0;
563 // First analyze the end of BB branches.
564 BBI.TrueBB = BBI.FalseBB = NULL;
565 BBI.BrCond.clear();
566 BBI.IsBrAnalyzable =
567 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
568 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
569
570 if (BBI.BrCond.size()) {
571 // No false branch. This BB must end with a conditional branch and a
572 // fallthrough.
573 if (!BBI.FalseBB)
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000574 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000575 if (!BBI.FalseBB) {
576 // Malformed bcc? True and false blocks are the same?
577 BBI.IsUnpredicable = true;
578 return;
579 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 }
581
582 // Then scan all the instructions.
583 BBI.NonPredSize = 0;
584 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
586 I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +0000587 if (I->isDebugValue())
588 continue;
589
Chris Lattner5b930372008-01-07 07:27:27 +0000590 const TargetInstrDesc &TID = I->getDesc();
591 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 BBI.CannotBeCopied = true;
593
594 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000595 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596
597 if (!isCondBr) {
598 if (!isPredicated)
599 BBI.NonPredSize++;
600 else if (!AlreadyPredicated) {
601 // FIXME: This instruction is already predicated before the
602 // if-conversion pass. It's probably something like a conditional move.
603 // Mark this block unpredicable for now.
604 BBI.IsUnpredicable = true;
605 return;
606 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 }
608
609 if (BBI.ClobbersPred && !isPredicated) {
610 // Predicate modification instruction should end the block (except for
611 // already predicated instructions and end of block branches).
612 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000613 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 continue;
615 }
616
617 // Predicate may have been modified, the subsequent (currently)
618 // unpredicated instructions cannot be correctly predicated.
619 BBI.IsUnpredicable = true;
620 return;
621 }
622
623 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
624 // still potentially predicable.
625 std::vector<MachineOperand> PredDefs;
626 if (TII->DefinesPredicate(I, PredDefs))
627 BBI.ClobbersPred = true;
628
Evan Cheng76fe9892009-11-21 06:20:26 +0000629 if (!TII->isPredicable(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 BBI.IsUnpredicable = true;
631 return;
632 }
633 }
634}
635
636/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
637/// predicated by the specified predicate.
638bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000639 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 bool isTriangle, bool RevBranch) {
641 // If the block is dead or unpredicable, then it cannot be predicated.
642 if (BBI.IsDone || BBI.IsUnpredicable)
643 return false;
644
645 // If it is already predicated, check if its predicate subsumes the new
646 // predicate.
647 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
648 return false;
649
650 if (BBI.BrCond.size()) {
651 if (!isTriangle)
652 return false;
653
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000654 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000655 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
656 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657 if (RevBranch) {
658 if (TII->ReverseBranchCondition(Cond))
659 return false;
660 }
661 if (TII->ReverseBranchCondition(RevPred) ||
662 !TII->SubsumesPredicate(Cond, RevPred))
663 return false;
664 }
665
666 return true;
667}
668
669/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
670/// the specified block. Record its successors and whether it looks like an
671/// if-conversion candidate.
672IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
673 std::vector<IfcvtToken*> &Tokens) {
674 BBInfo &BBI = BBAnalysis[BB->getNumber()];
675
676 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
677 return BBI;
678
679 BBI.BB = BB;
680 BBI.IsBeingAnalyzed = true;
681
682 ScanInstructions(BBI);
683
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000684 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000685 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 BBI.IsBeingAnalyzed = false;
687 BBI.IsAnalyzed = true;
688 return BBI;
689 }
690
691 // Do not ifcvt if either path is a back edge to the entry block.
692 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
693 BBI.IsBeingAnalyzed = false;
694 BBI.IsAnalyzed = true;
695 return BBI;
696 }
697
Evan Cheng4eb66e62009-06-15 21:24:34 +0000698 // Do not ifcvt if true and false fallthrough blocks are the same.
699 if (!BBI.FalseBB) {
700 BBI.IsBeingAnalyzed = false;
701 BBI.IsAnalyzed = true;
702 return BBI;
703 }
704
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
706 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
707
708 if (TrueBBI.IsDone && FalseBBI.IsDone) {
709 BBI.IsBeingAnalyzed = false;
710 BBI.IsAnalyzed = true;
711 return BBI;
712 }
713
Owen Andersond131b5b2008-08-14 22:49:33 +0000714 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
716
717 unsigned Dups = 0;
718 unsigned Dups2 = 0;
719 bool TNeedSub = TrueBBI.Predicate.size() > 0;
720 bool FNeedSub = FalseBBI.Predicate.size() > 0;
721 bool Enqueued = false;
722 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
723 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
724 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
725 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
726 FeasibilityAnalysis(FalseBBI, RevCond)) {
727 // Diamond:
728 // EBB
729 // / \_
730 // | |
731 // TBB FBB
732 // \ /
733 // TailBB
734 // Note TailBB can be empty.
735 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
736 Dups2));
737 Enqueued = true;
738 }
739
740 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
741 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
742 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
743 // Triangle:
744 // EBB
745 // | \_
746 // | |
747 // | TBB
748 // | /
749 // FBB
750 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
751 Enqueued = true;
752 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000753
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
755 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
756 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
757 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
758 Enqueued = true;
759 }
760
761 if (ValidSimple(TrueBBI, Dups) &&
762 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
763 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
764 // Simple (split, no rejoin):
765 // EBB
766 // | \_
767 // | |
768 // | TBB---> exit
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000769 // |
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 // FBB
771 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
772 Enqueued = true;
773 }
774
775 if (CanRevCond) {
776 // Try the other path...
777 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
778 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
779 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
780 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
781 Enqueued = true;
782 }
783
784 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
785 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
786 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
787 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
788 Enqueued = true;
789 }
790
791 if (ValidSimple(FalseBBI, Dups) &&
792 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
793 FeasibilityAnalysis(FalseBBI, RevCond)) {
794 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
795 Enqueued = true;
796 }
797 }
798
799 BBI.IsEnqueued = Enqueued;
800 BBI.IsBeingAnalyzed = false;
801 BBI.IsAnalyzed = true;
802 return BBI;
803}
804
805/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson89b9c322010-06-15 18:57:15 +0000806/// candidates.
807void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 std::vector<IfcvtToken*> &Tokens) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 std::set<MachineBasicBlock*> Visited;
810 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
811 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
812 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
813 MachineBasicBlock *BB = *I;
814 AnalyzeBlock(BB, Tokens);
815 }
816 }
817
818 // Sort to favor more complex ifcvt scheme.
819 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820}
821
822/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
823/// that all the intervening blocks are empty (given BB can fall through to its
824/// next block).
825static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
826 MachineFunction::iterator I = BB;
827 MachineFunction::iterator TI = ToBB;
828 MachineFunction::iterator E = BB->getParent()->end();
829 while (++I != TI)
830 if (I == E || !I->empty())
831 return false;
832 return true;
833}
834
835/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
836/// to determine if it can be if-converted. If predecessor is already enqueued,
837/// dequeue it!
838void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
839 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
840 E = BB->pred_end(); PI != E; ++PI) {
841 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
842 if (PBBI.IsDone || PBBI.BB == BB)
843 continue;
844 PBBI.IsAnalyzed = false;
845 PBBI.IsEnqueued = false;
846 }
847}
848
849/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
850///
851static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
852 const TargetInstrInfo *TII) {
Dan Gohmane458ea82008-08-22 16:07:55 +0000853 SmallVector<MachineOperand, 0> NoCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
855}
856
857/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
858/// successors.
859void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
860 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000861 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
863 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
864}
865
866/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
867///
868bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
869 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
870 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
871 BBInfo *CvtBBI = &TrueBBI;
872 BBInfo *NextBBI = &FalseBBI;
873
Owen Andersond131b5b2008-08-14 22:49:33 +0000874 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 if (Kind == ICSimpleFalse)
876 std::swap(CvtBBI, NextBBI);
877
878 if (CvtBBI->IsDone ||
879 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
880 // Something has changed. It's no longer safe to predicate this block.
881 BBI.IsAnalyzed = false;
882 CvtBBI->IsAnalyzed = false;
883 return false;
884 }
885
886 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000887 if (TII->ReverseBranchCondition(Cond))
888 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889
890 if (CvtBBI->BB->pred_size() > 1) {
891 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000892 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 // the entry block.
894 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
895 } else {
896 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
897
898 // Merge converted block into entry block.
899 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
900 MergeBlocks(BBI, *CvtBBI);
901 }
902
903 bool IterIfcvt = true;
904 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
905 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
906 BBI.HasFallThrough = false;
907 // Now ifcvt'd block will look like this:
908 // BB:
909 // ...
910 // t, f = cmp
911 // if t op
912 // b BBf
913 //
914 // We cannot further ifcvt this block because the unconditional branch
915 // will have to be predicated on the new condition, that will not be
916 // available if cmp executes.
917 IterIfcvt = false;
918 }
919
920 RemoveExtraEdges(BBI);
921
922 // Update block info. BB can be iteratively if-converted.
923 if (!IterIfcvt)
924 BBI.IsDone = true;
925 InvalidatePreds(BBI.BB);
926 CvtBBI->IsDone = true;
927
928 // FIXME: Must maintain LiveIns.
929 return true;
930}
931
932/// IfConvertTriangle - If convert a triangle sub-CFG.
933///
934bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
935 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
936 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
937 BBInfo *CvtBBI = &TrueBBI;
938 BBInfo *NextBBI = &FalseBBI;
939
Owen Andersond131b5b2008-08-14 22:49:33 +0000940 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
942 std::swap(CvtBBI, NextBBI);
943
944 if (CvtBBI->IsDone ||
945 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
946 // Something has changed. It's no longer safe to predicate this block.
947 BBI.IsAnalyzed = false;
948 CvtBBI->IsAnalyzed = false;
949 return false;
950 }
951
952 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000953 if (TII->ReverseBranchCondition(Cond))
954 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955
956 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000957 if (ReverseBranchCondition(*CvtBBI)) {
958 // BB has been changed, modify its predecessors (except for this
959 // one) so they don't get ifcvt'ed based on bad intel.
960 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
961 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
962 MachineBasicBlock *PBB = *PI;
963 if (PBB == BBI.BB)
964 continue;
965 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
966 if (PBBI.IsEnqueued) {
967 PBBI.IsAnalyzed = false;
968 PBBI.IsEnqueued = false;
969 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 }
971 }
972 }
973
974 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
975 bool DupBB = CvtBBI->BB->pred_size() > 1;
976 if (DupBB) {
977 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000978 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979 // the entry block.
980 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
981 } else {
982 // Predicate the 'true' block after removing its branch.
983 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
984 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 // Now merge the entry of the triangle with the true block.
987 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
988 MergeBlocks(BBI, *CvtBBI);
989 }
990
991 // If 'true' block has a 'false' successor, add an exit branch to it.
992 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000993 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
994 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 if (TII->ReverseBranchCondition(RevCond))
996 assert(false && "Unable to reverse branch condition!");
997 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond);
998 BBI.BB->addSuccessor(CvtBBI->FalseBB);
999 }
1000
1001 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001002 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 bool FalseBBDead = false;
1004 bool IterIfcvt = true;
1005 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1006 if (!isFallThrough) {
1007 // Only merge them if the true block does not fallthrough to the false
1008 // block. By not merging them, we make it possible to iteratively
1009 // ifcvt the blocks.
1010 if (!HasEarlyExit &&
1011 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1012 MergeBlocks(BBI, *NextBBI);
1013 FalseBBDead = true;
1014 } else {
1015 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1016 BBI.HasFallThrough = false;
1017 }
1018 // Mixed predicated and unpredicated code. This cannot be iteratively
1019 // predicated.
1020 IterIfcvt = false;
1021 }
1022
1023 RemoveExtraEdges(BBI);
1024
1025 // Update block info. BB can be iteratively if-converted.
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001026 if (!IterIfcvt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 BBI.IsDone = true;
1028 InvalidatePreds(BBI.BB);
1029 CvtBBI->IsDone = true;
1030 if (FalseBBDead)
1031 NextBBI->IsDone = true;
1032
1033 // FIXME: Must maintain LiveIns.
1034 return true;
1035}
1036
1037/// IfConvertDiamond - If convert a diamond sub-CFG.
1038///
1039bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1040 unsigned NumDups1, unsigned NumDups2) {
1041 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1042 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1043 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001044 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 if (!TailBB) {
1046 if (blockAlwaysFallThrough(TrueBBI))
1047 TailBB = FalseBBI.TrueBB;
1048 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1049 }
1050
1051 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1052 TrueBBI.BB->pred_size() > 1 ||
1053 FalseBBI.BB->pred_size() > 1) {
1054 // Something has changed. It's no longer safe to predicate these blocks.
1055 BBI.IsAnalyzed = false;
1056 TrueBBI.IsAnalyzed = false;
1057 FalseBBI.IsAnalyzed = false;
1058 return false;
1059 }
1060
1061 // Merge the 'true' and 'false' blocks by copying the instructions
1062 // from the 'false' block to the 'true' block. That is, unless the true
1063 // block would clobber the predicate, in that case, do the opposite.
1064 BBInfo *BBI1 = &TrueBBI;
1065 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001066 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001067 if (TII->ReverseBranchCondition(RevCond))
1068 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001069 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1070 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071
1072 // Figure out the more profitable ordering.
1073 bool DoSwap = false;
1074 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1075 DoSwap = true;
1076 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1077 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1078 DoSwap = true;
1079 }
1080 if (DoSwap) {
1081 std::swap(BBI1, BBI2);
1082 std::swap(Cond1, Cond2);
1083 }
1084
1085 // Remove the conditional branch from entry to the blocks.
1086 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1087
1088 // Remove the duplicated instructions at the beginnings of both paths.
1089 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1090 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachf8648062010-06-14 21:30:32 +00001091 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1092 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1093 // Skip dbg_value instructions
1094 while (DI1 != DIE1 && DI1->isDebugValue())
1095 ++DI1;
1096 while (DI2 != DIE2 && DI2->isDebugValue())
1097 ++DI2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 BBI1->NonPredSize -= NumDups1;
1099 BBI2->NonPredSize -= NumDups1;
1100 while (NumDups1 != 0) {
1101 ++DI1;
1102 ++DI2;
1103 --NumDups1;
1104 }
1105 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1106 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1107
1108 // Predicate the 'true' block after removing its branch.
1109 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1110 DI1 = BBI1->BB->end();
Jim Grosbachf8648062010-06-14 21:30:32 +00001111 for (unsigned i = 0; i != NumDups2; ) {
1112 // NumDups2 only counted non-dbg_value instructions, so this won't
1113 // run off the head of the list.
1114 assert (DI1 != BBI1->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 --DI1;
Jim Grosbachf8648062010-06-14 21:30:32 +00001116 // skip dbg_value instructions
1117 if (!DI1->isDebugValue())
1118 ++i;
1119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 BBI1->BB->erase(DI1, BBI1->BB->end());
1121 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1);
1122
1123 // Predicate the 'false' block.
1124 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1125 DI2 = BBI2->BB->end();
1126 while (NumDups2 != 0) {
Jim Grosbachf8648062010-06-14 21:30:32 +00001127 // NumDups2 only counted non-dbg_value instructions, so this won't
1128 // run off the head of the list.
1129 assert (DI2 != BBI2->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 --DI2;
Jim Grosbachf8648062010-06-14 21:30:32 +00001131 // skip dbg_value instructions
1132 if (!DI2->isDebugValue())
1133 --NumDups2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 }
1135 PredicateBlock(*BBI2, DI2, *Cond2);
1136
1137 // Merge the true block into the entry of the diamond.
1138 MergeBlocks(BBI, *BBI1);
1139 MergeBlocks(BBI, *BBI2);
1140
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001141 // If the if-converted block falls through or unconditionally branches into
1142 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 // fold the tail block in as well. Otherwise, unless it falls through to the
1144 // tail, add a unconditional branch to it.
1145 if (TailBB) {
1146 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1147 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1148 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1149 MergeBlocks(BBI, TailBBI);
1150 TailBBI.IsDone = true;
1151 } else {
1152 InsertUncondBranch(BBI.BB, TailBB, TII);
1153 BBI.HasFallThrough = false;
1154 }
1155 }
1156
1157 RemoveExtraEdges(BBI);
1158
1159 // Update block info.
1160 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1161 InvalidatePreds(BBI.BB);
1162
1163 // FIXME: Must maintain LiveIns.
1164 return true;
1165}
1166
1167/// PredicateBlock - Predicate instructions from the start of the block to the
1168/// specified end with the specified condition.
1169void IfConverter::PredicateBlock(BBInfo &BBI,
1170 MachineBasicBlock::iterator E,
Owen Andersond131b5b2008-08-14 22:49:33 +00001171 SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001173 if (I->isDebugValue() || TII->isPredicated(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 continue;
1175 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001176#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001177 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001178#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001179 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 }
1181 }
1182
1183 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1184
1185 BBI.IsAnalyzed = false;
1186 BBI.NonPredSize = 0;
1187
1188 NumIfConvBBs++;
1189}
1190
1191/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1192/// the destination block. Skip end of block branches if IgnoreBr is true.
1193void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001194 SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001196 MachineFunction &MF = *ToBBI.BB->getParent();
1197
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1199 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001200 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 bool isPredicated = TII->isPredicated(I);
1202 // Do not copy the end of the block branches.
Chris Lattner5b930372008-01-07 07:27:27 +00001203 if (IgnoreBr && !isPredicated && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 break;
1205
Dan Gohman221a4372008-07-07 23:14:23 +00001206 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1208 ToBBI.NonPredSize++;
1209
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001210 if (!isPredicated && !MI->isDebugValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001212#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001213 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001214#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001215 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 }
1217 }
1218
1219 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1220 FromBBI.BB->succ_end());
1221 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1222 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1223
1224 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1225 MachineBasicBlock *Succ = Succs[i];
1226 // Fallthrough edge can't be transferred.
1227 if (Succ == FallThrough)
1228 continue;
Dan Gohman710011c2009-05-05 21:10:19 +00001229 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 }
1231
1232 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1233 std::back_inserter(ToBBI.Predicate));
1234 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1235
1236 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1237 ToBBI.IsAnalyzed = false;
1238
1239 NumDupBBs++;
1240}
1241
1242/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1243///
1244void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1245 ToBBI.BB->splice(ToBBI.BB->end(),
1246 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1247
Bob Wilsonf3dc37d2009-05-14 18:08:41 +00001248 // Redirect all branches to FromBB to ToBB.
1249 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1250 FromBBI.BB->pred_end());
1251 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1252 MachineBasicBlock *Pred = Preds[i];
1253 if (Pred == ToBBI.BB)
1254 continue;
1255 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1256 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001257
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1259 FromBBI.BB->succ_end());
1260 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1261 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1262
1263 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1264 MachineBasicBlock *Succ = Succs[i];
1265 // Fallthrough edge can't be transferred.
1266 if (Succ == FallThrough)
1267 continue;
1268 FromBBI.BB->removeSuccessor(Succ);
Dan Gohman710011c2009-05-05 21:10:19 +00001269 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 }
1271
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001272 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001273 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 FromBBI.BB->addSuccessor(NBB);
1275
1276 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1277 std::back_inserter(ToBBI.Predicate));
1278 FromBBI.Predicate.clear();
1279
1280 ToBBI.NonPredSize += FromBBI.NonPredSize;
1281 FromBBI.NonPredSize = 0;
1282
1283 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1284 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1285 ToBBI.IsAnalyzed = false;
1286 FromBBI.IsAnalyzed = false;
1287}