blob: 36e6fc727bf978f07851c992753f4257e1f7717c [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"
Evan Cheng160f30c2010-06-16 07:35:02 +000023#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/ADT/DepthFirstIterator.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/STLExtras.h"
31using namespace llvm;
32
Chris Lattner4335bff2008-01-07 05:40:58 +000033// Hidden options for help debugging.
34static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
35static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
36static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000037static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner4335bff2008-01-07 05:40:58 +000038 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000039static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000040 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000041static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner4335bff2008-01-07 05:40:58 +000042 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000043static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000044 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000045static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner4335bff2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000047static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner4335bff2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson2f5b10d2010-06-15 22:18:54 +000049static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner4335bff2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Evan Cheng160f30c2010-06-16 07:35:02 +000051static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
52 cl::init(true), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053
54STATISTIC(NumSimple, "Number of simple if-conversions performed");
55STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
56STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
57STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
58STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
59STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
60STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
61STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
62STATISTIC(NumDupBBs, "Number of duplicated blocks");
63
64namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000065 class IfConverter : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 enum IfcvtKind {
67 ICNotClassfied, // BB data valid, but not classified.
68 ICSimpleFalse, // Same as ICSimple, but on the false path.
69 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
70 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
71 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
72 ICTriangleFalse, // Same as ICTriangle, but on the false path.
73 ICTriangle, // BB is entry of a triangle sub-CFG.
74 ICDiamond // BB is entry of a diamond sub-CFG.
75 };
76
77 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
78 /// if-conversion feasibility analysis. This includes results from
79 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
80 /// classification, and common tail block of its successors (if it's a
81 /// diamond shape), its size, whether it's predicable, and whether any
82 /// instruction can clobber the 'would-be' predicate.
83 ///
84 /// IsDone - True if BB is not to be considered for ifcvt.
85 /// IsBeingAnalyzed - True if BB is currently being analyzed.
86 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
87 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
88 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
89 /// HasFallThrough - True if BB may fallthrough to the following BB.
90 /// IsUnpredicable - True if BB is known to be unpredicable.
91 /// ClobbersPred - True if BB could modify predicates (e.g. has
92 /// cmp, call, etc.)
93 /// NonPredSize - Number of non-predicated instructions.
94 /// BB - Corresponding MachineBasicBlock.
95 /// TrueBB / FalseBB- See AnalyzeBranch().
96 /// BrCond - Conditions for end of block conditional branches.
97 /// Predicate - Predicate used in the BB.
98 struct BBInfo {
99 bool IsDone : 1;
100 bool IsBeingAnalyzed : 1;
101 bool IsAnalyzed : 1;
102 bool IsEnqueued : 1;
103 bool IsBrAnalyzable : 1;
104 bool HasFallThrough : 1;
105 bool IsUnpredicable : 1;
106 bool CannotBeCopied : 1;
107 bool ClobbersPred : 1;
108 unsigned NonPredSize;
109 MachineBasicBlock *BB;
110 MachineBasicBlock *TrueBB;
111 MachineBasicBlock *FalseBB;
Owen Andersond131b5b2008-08-14 22:49:33 +0000112 SmallVector<MachineOperand, 4> BrCond;
113 SmallVector<MachineOperand, 4> Predicate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
115 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
116 HasFallThrough(false), IsUnpredicable(false),
117 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
118 BB(0), TrueBB(0), FalseBB(0) {}
119 };
120
Bob Wilson01320da2010-06-15 18:19:27 +0000121 /// IfcvtToken - Record information about pending if-conversions to attempt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 /// BBI - Corresponding BBInfo.
123 /// Kind - Type of block. See IfcvtKind.
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000124 /// NeedSubsumption - True if the to-be-predicated BB has already been
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 /// predicated.
126 /// NumDups - Number of instructions that would be duplicated due
127 /// to this if-conversion. (For diamonds, the number of
128 /// identical instructions at the beginnings of both
129 /// paths).
130 /// NumDups2 - For diamonds, the number of identical instructions
131 /// at the ends of both paths.
132 struct IfcvtToken {
133 BBInfo &BBI;
134 IfcvtKind Kind;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000135 bool NeedSubsumption;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 unsigned NumDups;
137 unsigned NumDups2;
138 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000139 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 };
141
142 /// Roots - Basic blocks that do not have successors. These are the starting
143 /// points of Graph traversal.
144 std::vector<MachineBasicBlock*> Roots;
145
146 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
147 /// basic block number.
148 std::vector<BBInfo> BBAnalysis;
149
150 const TargetLowering *TLI;
151 const TargetInstrInfo *TII;
Evan Cheng160f30c2010-06-16 07:35:02 +0000152 const TargetRegisterInfo *TRI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 bool MadeChange;
Owen Anderson03f2a7b2009-06-24 23:41:44 +0000154 int FnNum;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 public:
156 static char ID;
Bob Wilson93ab5612009-10-28 20:46:46 +0000157 IfConverter() : MachineFunctionPass(&ID), FnNum(-1) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158
159 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chenga911dfe2008-06-04 09:15:51 +0000160 virtual const char *getPassName() const { return "If Converter"; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
162 private:
163 bool ReverseBranchCondition(BBInfo &BBI);
164 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const;
165 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
166 bool FalseBranch, unsigned &Dups) const;
167 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
168 unsigned &Dups1, unsigned &Dups2) const;
169 void ScanInstructions(BBInfo &BBI);
170 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
171 std::vector<IfcvtToken*> &Tokens);
Owen Andersond131b5b2008-08-14 22:49:33 +0000172 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 bool isTriangle = false, bool RevBranch = false);
Bob Wilson89b9c322010-06-15 18:57:15 +0000174 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 void InvalidatePreds(MachineBasicBlock *BB);
176 void RemoveExtraEdges(BBInfo &BBI);
177 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
178 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
179 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
180 unsigned NumDups1, unsigned NumDups2);
181 void PredicateBlock(BBInfo &BBI,
182 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +0000183 SmallVectorImpl<MachineOperand> &Cond,
184 SmallSet<unsigned, 4> &Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000186 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +0000187 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 bool IgnoreBr = false);
189 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI);
190
191 bool MeetIfcvtSizeLimit(unsigned Size) const {
192 return Size > 0 && Size <= TLI->getIfCvtBlockSizeLimit();
193 }
194
195 // blockAlwaysFallThrough - Block ends without a terminator.
196 bool blockAlwaysFallThrough(BBInfo &BBI) const {
197 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
198 }
199
200 // IfcvtTokenCmp - Used to sort if-conversion candidates.
201 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
202 int Incr1 = (C1->Kind == ICDiamond)
203 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
204 int Incr2 = (C2->Kind == ICDiamond)
205 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
206 if (Incr1 > Incr2)
207 return true;
208 else if (Incr1 == Incr2) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000209 // Favors subsumption.
210 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 return true;
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000212 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 // Favors diamond over triangle, etc.
214 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
215 return true;
216 else if (C1->Kind == C2->Kind)
217 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
218 }
219 }
220 return false;
221 }
222 };
223
224 char IfConverter::ID = 0;
225}
226
Bob Wilson93ab5612009-10-28 20:46:46 +0000227static RegisterPass<IfConverter>
228X("if-converter", "If Converter");
229
230FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231
232bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
233 TLI = MF.getTarget().getTargetLowering();
234 TII = MF.getTarget().getInstrInfo();
Evan Cheng160f30c2010-06-16 07:35:02 +0000235 TRI = MF.getTarget().getRegisterInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 if (!TII) return false;
237
David Greenead778702010-01-04 22:02:01 +0000238 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000239 << MF.getFunction()->getName() << "\'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greenead778702010-01-04 22:02:01 +0000242 DEBUG(dbgs() << " skipped\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 return false;
244 }
David Greenead778702010-01-04 22:02:01 +0000245 DEBUG(dbgs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
247 MF.RenumberBlocks();
248 BBAnalysis.resize(MF.getNumBlockIDs());
249
250 // Look for root nodes, i.e. blocks without successors.
251 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman301f4052008-01-29 13:02:09 +0000252 if (I->succ_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 Roots.push_back(I);
254
255 std::vector<IfcvtToken*> Tokens;
256 MadeChange = false;
257 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
258 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
259 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000260 // Do an initial analysis for each basic block and find all the potential
261 // candidates to perform if-conversion.
Bob Wilson89b9c322010-06-15 18:57:15 +0000262 bool Change = false;
263 AnalyzeBlocks(MF, Tokens);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 while (!Tokens.empty()) {
265 IfcvtToken *Token = Tokens.back();
266 Tokens.pop_back();
267 BBInfo &BBI = Token->BBI;
268 IfcvtKind Kind = Token->Kind;
Nuno Lopes06cea782008-11-04 13:02:59 +0000269 unsigned NumDups = Token->NumDups;
Duncan Sands5c2a51a2008-11-04 18:05:30 +0000270 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes06cea782008-11-04 13:02:59 +0000271
272 delete Token;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273
274 // If the block has been evicted out of the queue or it has already been
275 // marked dead (due to it being predicated), then skip it.
276 if (BBI.IsDone)
277 BBI.IsEnqueued = false;
278 if (!BBI.IsEnqueued)
279 continue;
280
281 BBI.IsEnqueued = false;
282
283 bool RetVal = false;
284 switch (Kind) {
285 default: assert(false && "Unexpected!");
286 break;
287 case ICSimple:
288 case ICSimpleFalse: {
289 bool isFalse = Kind == ICSimpleFalse;
290 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000291 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
292 " false" : "")
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000293 << "): BB#" << BBI.BB->getNumber() << " ("
294 << ((Kind == ICSimpleFalse)
295 ? BBI.FalseBB->getNumber()
296 : BBI.TrueBB->getNumber()) << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 RetVal = IfConvertSimple(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000298 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000299 if (RetVal) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 if (isFalse) NumSimpleFalse++;
301 else NumSimple++;
Anton Korobeynikov53422f62008-02-20 11:10:28 +0000302 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 break;
304 }
305 case ICTriangle:
306 case ICTriangleRev:
307 case ICTriangleFalse:
308 case ICTriangleFRev: {
309 bool isFalse = Kind == ICTriangleFalse;
310 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
311 if (DisableTriangle && !isFalse && !isRev) break;
312 if (DisableTriangleR && !isFalse && isRev) break;
313 if (DisableTriangleF && isFalse && !isRev) break;
314 if (DisableTriangleFR && isFalse && isRev) break;
David Greenead778702010-01-04 22:02:01 +0000315 DEBUG(dbgs() << "Ifcvt (Triangle");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 if (isFalse)
David Greenead778702010-01-04 22:02:01 +0000317 DEBUG(dbgs() << " false");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 if (isRev)
David Greenead778702010-01-04 22:02:01 +0000319 DEBUG(dbgs() << " rev");
320 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000321 << BBI.TrueBB->getNumber() << ",F:"
322 << BBI.FalseBB->getNumber() << ") ");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 RetVal = IfConvertTriangle(BBI, Kind);
David Greenead778702010-01-04 22:02:01 +0000324 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 if (RetVal) {
326 if (isFalse) {
327 if (isRev) NumTriangleFRev++;
328 else NumTriangleFalse++;
329 } else {
330 if (isRev) NumTriangleRev++;
331 else NumTriangle++;
332 }
333 }
334 break;
335 }
336 case ICDiamond: {
337 if (DisableDiamond) break;
David Greenead778702010-01-04 22:02:01 +0000338 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingba5cfa32009-08-22 20:11:17 +0000339 << BBI.TrueBB->getNumber() << ",F:"
340 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes06cea782008-11-04 13:02:59 +0000341 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greenead778702010-01-04 22:02:01 +0000342 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 if (RetVal) NumDiamonds++;
344 break;
345 }
346 }
347
348 Change |= RetVal;
349
350 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
351 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
352 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
353 break;
354 }
355
356 if (!Change)
357 break;
358 MadeChange |= Change;
359 }
360
361 // Delete tokens in case of early exit.
362 while (!Tokens.empty()) {
363 IfcvtToken *Token = Tokens.back();
364 Tokens.pop_back();
365 delete Token;
366 }
367
368 Tokens.clear();
369 Roots.clear();
370 BBAnalysis.clear();
371
Evan Chengd50455b2010-06-18 22:17:13 +0000372 if (MadeChange && IfCvtBranchFold) {
Bob Wilson93ab5612009-10-28 20:46:46 +0000373 BranchFolder BF(false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000374 BF.OptimizeFunction(MF, TII,
375 MF.getTarget().getRegisterInfo(),
376 getAnalysisIfAvailable<MachineModuleInfo>());
377 }
378
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 return MadeChange;
380}
381
382/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
383/// its 'true' successor.
384static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
385 MachineBasicBlock *TrueBB) {
386 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
387 E = BB->succ_end(); SI != E; ++SI) {
388 MachineBasicBlock *SuccBB = *SI;
389 if (SuccBB != TrueBB)
390 return SuccBB;
391 }
392 return NULL;
393}
394
395/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000396/// branch. Swap block's 'true' and 'false' successors.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000398 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
400 TII->RemoveBranch(*BBI.BB);
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000401 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 std::swap(BBI.TrueBB, BBI.FalseBB);
403 return true;
404 }
405 return false;
406}
407
408/// getNextBlock - Returns the next block in the function blocks ordering. If
409/// it is the end, returns NULL.
410static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
411 MachineFunction::iterator I = BB;
412 MachineFunction::iterator E = BB->getParent()->end();
413 if (++I == E)
414 return NULL;
415 return I;
416}
417
418/// ValidSimple - Returns true if the 'true' block (along with its
419/// predecessor) forms a valid simple shape for ifcvt. It also returns the
420/// number of instructions that the ifcvt would need to duplicate if performed
421/// in Dups.
422bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups) const {
423 Dups = 0;
424 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
425 return false;
426
427 if (TrueBBI.IsBrAnalyzable)
428 return false;
429
430 if (TrueBBI.BB->pred_size() > 1) {
431 if (TrueBBI.CannotBeCopied ||
432 TrueBBI.NonPredSize > TLI->getIfCvtDupBlockSizeLimit())
433 return false;
434 Dups = TrueBBI.NonPredSize;
435 }
436
437 return true;
438}
439
440/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
441/// with their common predecessor) forms a valid triangle shape for ifcvt.
442/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000443/// branches to the 'false' block rather than the other way around. It also
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444/// returns the number of instructions that the ifcvt would need to duplicate
445/// if performed in 'Dups'.
446bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
447 bool FalseBranch, unsigned &Dups) const {
448 Dups = 0;
449 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
450 return false;
451
452 if (TrueBBI.BB->pred_size() > 1) {
453 if (TrueBBI.CannotBeCopied)
454 return false;
455
456 unsigned Size = TrueBBI.NonPredSize;
457 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman301f4052008-01-29 13:02:09 +0000458 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000459 // Ends with an unconditional branch. It will be removed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 --Size;
461 else {
462 MachineBasicBlock *FExit = FalseBranch
463 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
464 if (FExit)
465 // Require a conditional branch
466 ++Size;
467 }
468 }
469 if (Size > TLI->getIfCvtDupBlockSizeLimit())
470 return false;
471 Dups = Size;
472 }
473
474 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
475 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
476 MachineFunction::iterator I = TrueBBI.BB;
477 if (++I == TrueBBI.BB->getParent()->end())
478 return false;
479 TExit = I;
480 }
481 return TExit && TExit == FalseBBI.BB;
482}
483
484static
485MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
486 const TargetInstrInfo *TII) {
487 MachineBasicBlock::iterator I = BB->end();
488 while (I != BB->begin()) {
489 --I;
Chris Lattner5b930372008-01-07 07:27:27 +0000490 if (!I->getDesc().isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 break;
492 }
493 return I;
494}
495
496/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
497/// with their common predecessor) forms a valid diamond shape for ifcvt.
498bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
499 unsigned &Dups1, unsigned &Dups2) const {
500 Dups1 = Dups2 = 0;
501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
502 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
503 return false;
504
505 MachineBasicBlock *TT = TrueBBI.TrueBB;
506 MachineBasicBlock *FT = FalseBBI.TrueBB;
507
508 if (!TT && blockAlwaysFallThrough(TrueBBI))
509 TT = getNextBlock(TrueBBI.BB);
510 if (!FT && blockAlwaysFallThrough(FalseBBI))
511 FT = getNextBlock(FalseBBI.BB);
512 if (TT != FT)
513 return false;
514 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
515 return false;
516 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
517 return false;
518
519 // FIXME: Allow true block to have an early exit?
520 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
521 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
522 return false;
523
524 MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
525 MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000526 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
527 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
528 // Skip dbg_value instructions
529 while (TI != TIE && TI->isDebugValue())
530 ++TI;
531 while (FI != FIE && FI->isDebugValue())
532 ++FI;
533 while (TI != TIE && FI != FIE) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000534 // Skip dbg_value instructions. These do not count.
535 if (TI->isDebugValue()) {
536 while (TI != TIE && TI->isDebugValue())
537 ++TI;
538 if (TI == TIE)
539 break;
540 }
541 if (FI->isDebugValue()) {
542 while (FI != FIE && FI->isDebugValue())
543 ++FI;
544 if (FI == FIE)
545 break;
546 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 if (!TI->isIdenticalTo(FI))
548 break;
549 ++Dups1;
550 ++TI;
551 ++FI;
552 }
553
554 TI = firstNonBranchInst(TrueBBI.BB, TII);
555 FI = firstNonBranchInst(FalseBBI.BB, TII);
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000556 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
557 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Evan Chenga03a63c2010-06-18 21:52:57 +0000558 // Skip dbg_value instructions at end of the bb's.
Jim Grosbach8b5e7c92010-06-07 21:28:55 +0000559 while (TI != TIB && TI->isDebugValue())
560 --TI;
561 while (FI != FIB && FI->isDebugValue())
562 --FI;
563 while (TI != TIB && FI != FIB) {
Evan Chenga03a63c2010-06-18 21:52:57 +0000564 // Skip dbg_value instructions. These do not count.
565 if (TI->isDebugValue()) {
566 while (TI != TIB && TI->isDebugValue())
567 --TI;
568 if (TI == TIB)
569 break;
570 }
571 if (FI->isDebugValue()) {
572 while (FI != FIB && FI->isDebugValue())
573 --FI;
574 if (FI == FIB)
575 break;
576 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 if (!TI->isIdenticalTo(FI))
578 break;
579 ++Dups2;
580 --TI;
581 --FI;
582 }
583
584 return true;
585}
586
587/// ScanInstructions - Scan all the instructions in the block to determine if
588/// the block is predicable. In most cases, that means all the instructions
Chris Lattner62327602008-01-07 01:56:04 +0000589/// in the block are isPredicable(). Also checks if the block contains any
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590/// instruction which can clobber a predicate (e.g. condition code register).
591/// If so, the block is not predicable unless it's the last instruction.
592void IfConverter::ScanInstructions(BBInfo &BBI) {
593 if (BBI.IsDone)
594 return;
595
596 bool AlreadyPredicated = BBI.Predicate.size() > 0;
597 // First analyze the end of BB branches.
598 BBI.TrueBB = BBI.FalseBB = NULL;
599 BBI.BrCond.clear();
600 BBI.IsBrAnalyzable =
601 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
602 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
603
604 if (BBI.BrCond.size()) {
605 // No false branch. This BB must end with a conditional branch and a
606 // fallthrough.
607 if (!BBI.FalseBB)
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000608 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng4eb66e62009-06-15 21:24:34 +0000609 if (!BBI.FalseBB) {
610 // Malformed bcc? True and false blocks are the same?
611 BBI.IsUnpredicable = true;
612 return;
613 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 }
615
616 // Then scan all the instructions.
617 BBI.NonPredSize = 0;
618 BBI.ClobbersPred = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
620 I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +0000621 if (I->isDebugValue())
622 continue;
623
Chris Lattner5b930372008-01-07 07:27:27 +0000624 const TargetInstrDesc &TID = I->getDesc();
625 if (TID.isNotDuplicable())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 BBI.CannotBeCopied = true;
627
628 bool isPredicated = TII->isPredicated(I);
Chris Lattner5b930372008-01-07 07:27:27 +0000629 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630
631 if (!isCondBr) {
632 if (!isPredicated)
633 BBI.NonPredSize++;
634 else if (!AlreadyPredicated) {
635 // FIXME: This instruction is already predicated before the
636 // if-conversion pass. It's probably something like a conditional move.
637 // Mark this block unpredicable for now.
638 BBI.IsUnpredicable = true;
639 return;
640 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642
643 if (BBI.ClobbersPred && !isPredicated) {
644 // Predicate modification instruction should end the block (except for
645 // already predicated instructions and end of block branches).
646 if (isCondBr) {
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000647 // A conditional branch is not predicable, but it may be eliminated.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 continue;
649 }
650
651 // Predicate may have been modified, the subsequent (currently)
652 // unpredicated instructions cannot be correctly predicated.
653 BBI.IsUnpredicable = true;
654 return;
655 }
656
657 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
658 // still potentially predicable.
659 std::vector<MachineOperand> PredDefs;
660 if (TII->DefinesPredicate(I, PredDefs))
661 BBI.ClobbersPred = true;
662
Evan Cheng76fe9892009-11-21 06:20:26 +0000663 if (!TII->isPredicable(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 BBI.IsUnpredicable = true;
665 return;
666 }
667 }
668}
669
670/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
671/// predicated by the specified predicate.
672bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Andersond131b5b2008-08-14 22:49:33 +0000673 SmallVectorImpl<MachineOperand> &Pred,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 bool isTriangle, bool RevBranch) {
675 // If the block is dead or unpredicable, then it cannot be predicated.
676 if (BBI.IsDone || BBI.IsUnpredicable)
677 return false;
678
679 // If it is already predicated, check if its predicate subsumes the new
680 // predicate.
681 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
682 return false;
683
684 if (BBI.BrCond.size()) {
685 if (!isTriangle)
686 return false;
687
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000688 // Test predicate subsumption.
Owen Andersond131b5b2008-08-14 22:49:33 +0000689 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
690 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 if (RevBranch) {
692 if (TII->ReverseBranchCondition(Cond))
693 return false;
694 }
695 if (TII->ReverseBranchCondition(RevPred) ||
696 !TII->SubsumesPredicate(Cond, RevPred))
697 return false;
698 }
699
700 return true;
701}
702
703/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
704/// the specified block. Record its successors and whether it looks like an
705/// if-conversion candidate.
706IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
707 std::vector<IfcvtToken*> &Tokens) {
708 BBInfo &BBI = BBAnalysis[BB->getNumber()];
709
710 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
711 return BBI;
712
713 BBI.BB = BB;
714 BBI.IsBeingAnalyzed = true;
715
716 ScanInstructions(BBI);
717
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000718 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman301f4052008-01-29 13:02:09 +0000719 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 BBI.IsBeingAnalyzed = false;
721 BBI.IsAnalyzed = true;
722 return BBI;
723 }
724
725 // Do not ifcvt if either path is a back edge to the entry block.
726 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
727 BBI.IsBeingAnalyzed = false;
728 BBI.IsAnalyzed = true;
729 return BBI;
730 }
731
Evan Cheng4eb66e62009-06-15 21:24:34 +0000732 // Do not ifcvt if true and false fallthrough blocks are the same.
733 if (!BBI.FalseBB) {
734 BBI.IsBeingAnalyzed = false;
735 BBI.IsAnalyzed = true;
736 return BBI;
737 }
738
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
740 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
741
742 if (TrueBBI.IsDone && FalseBBI.IsDone) {
743 BBI.IsBeingAnalyzed = false;
744 BBI.IsAnalyzed = true;
745 return BBI;
746 }
747
Owen Andersond131b5b2008-08-14 22:49:33 +0000748 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
750
751 unsigned Dups = 0;
752 unsigned Dups2 = 0;
753 bool TNeedSub = TrueBBI.Predicate.size() > 0;
754 bool FNeedSub = FalseBBI.Predicate.size() > 0;
755 bool Enqueued = false;
756 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
757 MeetIfcvtSizeLimit(TrueBBI.NonPredSize - (Dups + Dups2)) &&
758 MeetIfcvtSizeLimit(FalseBBI.NonPredSize - (Dups + Dups2)) &&
759 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
760 FeasibilityAnalysis(FalseBBI, RevCond)) {
761 // Diamond:
762 // EBB
763 // / \_
764 // | |
765 // TBB FBB
766 // \ /
767 // TailBB
768 // Note TailBB can be empty.
769 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
770 Dups2));
771 Enqueued = true;
772 }
773
774 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups) &&
775 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
776 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
777 // Triangle:
778 // EBB
779 // | \_
780 // | |
781 // | TBB
782 // | /
783 // FBB
784 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
785 Enqueued = true;
786 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000787
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups) &&
789 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
790 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
791 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
792 Enqueued = true;
793 }
794
795 if (ValidSimple(TrueBBI, Dups) &&
796 MeetIfcvtSizeLimit(TrueBBI.NonPredSize) &&
797 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
798 // Simple (split, no rejoin):
799 // EBB
800 // | \_
801 // | |
802 // | TBB---> exit
Bob Wilson2f5b10d2010-06-15 22:18:54 +0000803 // |
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 // FBB
805 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
806 Enqueued = true;
807 }
808
809 if (CanRevCond) {
810 // Try the other path...
811 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups) &&
812 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
813 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
814 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
815 Enqueued = true;
816 }
817
818 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups) &&
819 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
820 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
821 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
822 Enqueued = true;
823 }
824
825 if (ValidSimple(FalseBBI, Dups) &&
826 MeetIfcvtSizeLimit(FalseBBI.NonPredSize) &&
827 FeasibilityAnalysis(FalseBBI, RevCond)) {
828 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
829 Enqueued = true;
830 }
831 }
832
833 BBI.IsEnqueued = Enqueued;
834 BBI.IsBeingAnalyzed = false;
835 BBI.IsAnalyzed = true;
836 return BBI;
837}
838
839/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson89b9c322010-06-15 18:57:15 +0000840/// candidates.
841void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 std::vector<IfcvtToken*> &Tokens) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 std::set<MachineBasicBlock*> Visited;
844 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
845 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
846 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
847 MachineBasicBlock *BB = *I;
848 AnalyzeBlock(BB, Tokens);
849 }
850 }
851
852 // Sort to favor more complex ifcvt scheme.
853 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854}
855
856/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
857/// that all the intervening blocks are empty (given BB can fall through to its
858/// next block).
859static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng160f30c2010-06-16 07:35:02 +0000860 MachineFunction::iterator PI = BB;
861 MachineFunction::iterator I = llvm::next(PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 MachineFunction::iterator TI = ToBB;
863 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng160f30c2010-06-16 07:35:02 +0000864 while (I != TI) {
865 // Check isSuccessor to avoid case where the next block is empty, but
866 // it's not a successor.
867 if (I == E || !I->empty() || !PI->isSuccessor(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 return false;
Evan Cheng160f30c2010-06-16 07:35:02 +0000869 PI = I++;
870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 return true;
872}
873
874/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
875/// to determine if it can be if-converted. If predecessor is already enqueued,
876/// dequeue it!
877void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
878 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
879 E = BB->pred_end(); PI != E; ++PI) {
880 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
881 if (PBBI.IsDone || PBBI.BB == BB)
882 continue;
883 PBBI.IsAnalyzed = false;
884 PBBI.IsEnqueued = false;
885 }
886}
887
888/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
889///
890static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
891 const TargetInstrInfo *TII) {
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000892 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmane458ea82008-08-22 16:07:55 +0000893 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings9fa5e332010-06-17 22:43:56 +0000894 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895}
896
897/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
898/// successors.
899void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
900 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Andersond131b5b2008-08-14 22:49:33 +0000901 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
903 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
904}
905
Evan Cheng160f30c2010-06-16 07:35:02 +0000906/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
907/// modeled as read + write (sort like two-address instructions). These
908/// routines track register liveness and add implicit uses to if-converted
909/// instructions to conform to the model.
910static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
911 const TargetRegisterInfo *TRI) {
912 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
913 E = BB->livein_end(); I != E; ++I) {
914 unsigned Reg = *I;
915 Redefs.insert(Reg);
916 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
917 *Subreg; ++Subreg)
918 Redefs.insert(*Subreg);
919 }
920}
921
922static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
923 const TargetRegisterInfo *TRI,
924 bool AddImpUse = false) {
925 SmallVector<unsigned, 4> Defs;
926 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
927 const MachineOperand &MO = MI->getOperand(i);
928 if (!MO.isReg())
929 continue;
930 unsigned Reg = MO.getReg();
931 if (!Reg)
932 continue;
933 if (MO.isDef())
934 Defs.push_back(Reg);
935 else if (MO.isKill()) {
936 Redefs.erase(Reg);
937 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
938 Redefs.erase(*SR);
939 }
940 }
941 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
942 unsigned Reg = Defs[i];
943 if (Redefs.count(Reg)) {
944 if (AddImpUse)
945 // Treat predicated update as read + write.
946 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
947 true/*IsImp*/,false/*IsKill*/));
948 } else {
949 Redefs.insert(Reg);
950 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
951 Redefs.insert(*SR);
952 }
953 }
954}
955
956static void UpdatePredRedefs(MachineBasicBlock::iterator I,
957 MachineBasicBlock::iterator E,
958 SmallSet<unsigned,4> &Redefs,
959 const TargetRegisterInfo *TRI) {
960 while (I != E) {
961 UpdatePredRedefs(I, Redefs, TRI);
962 ++I;
963 }
964}
965
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
967///
968bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
969 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
970 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
971 BBInfo *CvtBBI = &TrueBBI;
972 BBInfo *NextBBI = &FalseBBI;
973
Owen Andersond131b5b2008-08-14 22:49:33 +0000974 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 if (Kind == ICSimpleFalse)
976 std::swap(CvtBBI, NextBBI);
977
978 if (CvtBBI->IsDone ||
979 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
980 // Something has changed. It's no longer safe to predicate this block.
981 BBI.IsAnalyzed = false;
982 CvtBBI->IsAnalyzed = false;
983 return false;
984 }
985
986 if (Kind == ICSimpleFalse)
Dan Gohman6a00fcb2008-10-21 03:29:32 +0000987 if (TII->ReverseBranchCondition(Cond))
988 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989
Evan Cheng160f30c2010-06-16 07:35:02 +0000990 // Initialize liveins to the first BB. These are potentiall re-defined by
991 // predicated instructions.
992 SmallSet<unsigned, 4> Redefs;
993 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
994 InitPredRedefs(NextBBI->BB, Redefs, TRI);
995
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 if (CvtBBI->BB->pred_size() > 1) {
997 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +0000998 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001000 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 } else {
Evan Cheng160f30c2010-06-16 07:35:02 +00001002 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003
1004 // Merge converted block into entry block.
1005 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1006 MergeBlocks(BBI, *CvtBBI);
1007 }
1008
1009 bool IterIfcvt = true;
1010 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1011 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1012 BBI.HasFallThrough = false;
1013 // Now ifcvt'd block will look like this:
1014 // BB:
1015 // ...
1016 // t, f = cmp
1017 // if t op
1018 // b BBf
1019 //
1020 // We cannot further ifcvt this block because the unconditional branch
1021 // will have to be predicated on the new condition, that will not be
1022 // available if cmp executes.
1023 IterIfcvt = false;
1024 }
1025
1026 RemoveExtraEdges(BBI);
1027
1028 // Update block info. BB can be iteratively if-converted.
1029 if (!IterIfcvt)
1030 BBI.IsDone = true;
1031 InvalidatePreds(BBI.BB);
1032 CvtBBI->IsDone = true;
1033
1034 // FIXME: Must maintain LiveIns.
1035 return true;
1036}
1037
1038/// IfConvertTriangle - If convert a triangle sub-CFG.
1039///
1040bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1041 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1042 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1043 BBInfo *CvtBBI = &TrueBBI;
1044 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001045 DebugLoc dl; // FIXME: this is nowhere
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
Owen Andersond131b5b2008-08-14 22:49:33 +00001047 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1049 std::swap(CvtBBI, NextBBI);
1050
1051 if (CvtBBI->IsDone ||
1052 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1053 // Something has changed. It's no longer safe to predicate this block.
1054 BBI.IsAnalyzed = false;
1055 CvtBBI->IsAnalyzed = false;
1056 return false;
1057 }
1058
1059 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001060 if (TII->ReverseBranchCondition(Cond))
1061 assert(false && "Unable to reverse branch condition!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062
1063 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001064 if (ReverseBranchCondition(*CvtBBI)) {
1065 // BB has been changed, modify its predecessors (except for this
1066 // one) so they don't get ifcvt'ed based on bad intel.
1067 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1068 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1069 MachineBasicBlock *PBB = *PI;
1070 if (PBB == BBI.BB)
1071 continue;
1072 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1073 if (PBBI.IsEnqueued) {
1074 PBBI.IsAnalyzed = false;
1075 PBBI.IsEnqueued = false;
1076 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 }
1078 }
1079 }
1080
Evan Cheng160f30c2010-06-16 07:35:02 +00001081 // Initialize liveins to the first BB. These are potentiall re-defined by
1082 // predicated instructions.
1083 SmallSet<unsigned, 4> Redefs;
1084 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1085 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1086
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1088 bool DupBB = CvtBBI->BB->pred_size() > 1;
1089 if (DupBB) {
1090 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001091 // Copy instructions in the true block, predicate them, and add them to
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 // the entry block.
Evan Cheng160f30c2010-06-16 07:35:02 +00001093 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 } else {
1095 // Predicate the 'true' block after removing its branch.
1096 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng160f30c2010-06-16 07:35:02 +00001097 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 // Now merge the entry of the triangle with the true block.
1100 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1101 MergeBlocks(BBI, *CvtBBI);
1102 }
1103
1104 // If 'true' block has a 'false' successor, add an exit branch to it.
1105 if (HasEarlyExit) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001106 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1107 CvtBBI->BrCond.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if (TII->ReverseBranchCondition(RevCond))
1109 assert(false && "Unable to reverse branch condition!");
Stuart Hastings9fa5e332010-06-17 22:43:56 +00001110 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1112 }
1113
1114 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001115 // predecessors. Otherwise, add an unconditional branch to 'false'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 bool FalseBBDead = false;
1117 bool IterIfcvt = true;
1118 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1119 if (!isFallThrough) {
1120 // Only merge them if the true block does not fallthrough to the false
1121 // block. By not merging them, we make it possible to iteratively
1122 // ifcvt the blocks.
1123 if (!HasEarlyExit &&
1124 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1125 MergeBlocks(BBI, *NextBBI);
1126 FalseBBDead = true;
1127 } else {
1128 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1129 BBI.HasFallThrough = false;
1130 }
1131 // Mixed predicated and unpredicated code. This cannot be iteratively
1132 // predicated.
1133 IterIfcvt = false;
1134 }
1135
1136 RemoveExtraEdges(BBI);
1137
1138 // Update block info. BB can be iteratively if-converted.
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001139 if (!IterIfcvt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 BBI.IsDone = true;
1141 InvalidatePreds(BBI.BB);
1142 CvtBBI->IsDone = true;
1143 if (FalseBBDead)
1144 NextBBI->IsDone = true;
1145
1146 // FIXME: Must maintain LiveIns.
1147 return true;
1148}
1149
1150/// IfConvertDiamond - If convert a diamond sub-CFG.
1151///
1152bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1153 unsigned NumDups1, unsigned NumDups2) {
1154 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1155 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1156 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001157 // True block must fall through or end with an unanalyzable terminator.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 if (!TailBB) {
1159 if (blockAlwaysFallThrough(TrueBBI))
1160 TailBB = FalseBBI.TrueBB;
1161 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1162 }
1163
1164 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1165 TrueBBI.BB->pred_size() > 1 ||
1166 FalseBBI.BB->pred_size() > 1) {
1167 // Something has changed. It's no longer safe to predicate these blocks.
1168 BBI.IsAnalyzed = false;
1169 TrueBBI.IsAnalyzed = false;
1170 FalseBBI.IsAnalyzed = false;
1171 return false;
1172 }
1173
1174 // Merge the 'true' and 'false' blocks by copying the instructions
1175 // from the 'false' block to the 'true' block. That is, unless the true
1176 // block would clobber the predicate, in that case, do the opposite.
1177 BBInfo *BBI1 = &TrueBBI;
1178 BBInfo *BBI2 = &FalseBBI;
Owen Andersond131b5b2008-08-14 22:49:33 +00001179 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman6a00fcb2008-10-21 03:29:32 +00001180 if (TII->ReverseBranchCondition(RevCond))
1181 assert(false && "Unable to reverse branch condition!");
Owen Andersond131b5b2008-08-14 22:49:33 +00001182 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1183 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184
1185 // Figure out the more profitable ordering.
1186 bool DoSwap = false;
1187 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1188 DoSwap = true;
1189 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1190 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1191 DoSwap = true;
1192 }
1193 if (DoSwap) {
1194 std::swap(BBI1, BBI2);
1195 std::swap(Cond1, Cond2);
1196 }
1197
1198 // Remove the conditional branch from entry to the blocks.
1199 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1200
Evan Cheng160f30c2010-06-16 07:35:02 +00001201 // Initialize liveins to the first BB. These are potentiall re-defined by
1202 // predicated instructions.
1203 SmallSet<unsigned, 4> Redefs;
1204 InitPredRedefs(BBI1->BB, Redefs, TRI);
1205
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 // Remove the duplicated instructions at the beginnings of both paths.
1207 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1208 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachf8648062010-06-14 21:30:32 +00001209 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1210 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1211 // Skip dbg_value instructions
1212 while (DI1 != DIE1 && DI1->isDebugValue())
1213 ++DI1;
1214 while (DI2 != DIE2 && DI2->isDebugValue())
1215 ++DI2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 BBI1->NonPredSize -= NumDups1;
1217 BBI2->NonPredSize -= NumDups1;
1218 while (NumDups1 != 0) {
1219 ++DI1;
1220 ++DI2;
1221 --NumDups1;
1222 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001223
1224 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1226 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1227
1228 // Predicate the 'true' block after removing its branch.
1229 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1230 DI1 = BBI1->BB->end();
Jim Grosbachf8648062010-06-14 21:30:32 +00001231 for (unsigned i = 0; i != NumDups2; ) {
1232 // NumDups2 only counted non-dbg_value instructions, so this won't
1233 // run off the head of the list.
1234 assert (DI1 != BBI1->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 --DI1;
Jim Grosbachf8648062010-06-14 21:30:32 +00001236 // skip dbg_value instructions
1237 if (!DI1->isDebugValue())
1238 ++i;
1239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng160f30c2010-06-16 07:35:02 +00001241 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242
1243 // Predicate the 'false' block.
1244 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1245 DI2 = BBI2->BB->end();
1246 while (NumDups2 != 0) {
Jim Grosbachf8648062010-06-14 21:30:32 +00001247 // NumDups2 only counted non-dbg_value instructions, so this won't
1248 // run off the head of the list.
1249 assert (DI2 != BBI2->BB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 --DI2;
Jim Grosbachf8648062010-06-14 21:30:32 +00001251 // skip dbg_value instructions
1252 if (!DI2->isDebugValue())
1253 --NumDups2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001255 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256
1257 // Merge the true block into the entry of the diamond.
1258 MergeBlocks(BBI, *BBI1);
1259 MergeBlocks(BBI, *BBI2);
1260
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001261 // If the if-converted block falls through or unconditionally branches into
1262 // the tail block, and the tail block does not have other predecessors, then
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 // fold the tail block in as well. Otherwise, unless it falls through to the
1264 // tail, add a unconditional branch to it.
1265 if (TailBB) {
1266 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1267 if (TailBB->pred_size() == 1 && !TailBBI.HasFallThrough) {
1268 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1269 MergeBlocks(BBI, TailBBI);
1270 TailBBI.IsDone = true;
1271 } else {
1272 InsertUncondBranch(BBI.BB, TailBB, TII);
1273 BBI.HasFallThrough = false;
1274 }
1275 }
1276
1277 RemoveExtraEdges(BBI);
1278
1279 // Update block info.
1280 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1281 InvalidatePreds(BBI.BB);
1282
1283 // FIXME: Must maintain LiveIns.
1284 return true;
1285}
1286
1287/// PredicateBlock - Predicate instructions from the start of the block to the
1288/// specified end with the specified condition.
1289void IfConverter::PredicateBlock(BBInfo &BBI,
1290 MachineBasicBlock::iterator E,
Evan Cheng160f30c2010-06-16 07:35:02 +00001291 SmallVectorImpl<MachineOperand> &Cond,
1292 SmallSet<unsigned, 4> &Redefs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach3c47a2c2010-06-04 23:01:26 +00001294 if (I->isDebugValue() || TII->isPredicated(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 continue;
1296 if (!TII->PredicateInstruction(I, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001297#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001298 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001299#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001300 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001302
1303 // If the predicated instruction now re-defines a register as the result of
1304 // if-conversion, add an implicit kill.
1305 UpdatePredRedefs(I, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 }
1307
1308 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1309
1310 BBI.IsAnalyzed = false;
1311 BBI.NonPredSize = 0;
1312
1313 NumIfConvBBs++;
1314}
1315
1316/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1317/// the destination block. Skip end of block branches if IgnoreBr is true.
1318void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Andersond131b5b2008-08-14 22:49:33 +00001319 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng160f30c2010-06-16 07:35:02 +00001320 SmallSet<unsigned, 4> &Redefs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 bool IgnoreBr) {
Dan Gohman221a4372008-07-07 23:14:23 +00001322 MachineFunction &MF = *ToBBI.BB->getParent();
1323
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1325 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +00001326 const TargetInstrDesc &TID = I->getDesc();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 // Do not copy the end of the block branches.
Bob Wilsond00487b2010-06-18 17:07:23 +00001328 if (IgnoreBr && TID.isBranch())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 break;
1330
Dan Gohman221a4372008-07-07 23:14:23 +00001331 MachineInstr *MI = MF.CloneMachineInstr(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1333 ToBBI.NonPredSize++;
1334
Bob Wilsond00487b2010-06-18 17:07:23 +00001335 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 if (!TII->PredicateInstruction(MI, Cond)) {
Edwin Török280d15b2009-07-12 20:07:01 +00001337#ifndef NDEBUG
David Greenead778702010-01-04 22:02:01 +00001338 dbgs() << "Unable to predicate " << *I << "!\n";
Edwin Török280d15b2009-07-12 20:07:01 +00001339#endif
Edwin Törökbd448e32009-07-14 16:55:14 +00001340 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
Evan Cheng160f30c2010-06-16 07:35:02 +00001342 }
1343
1344 // If the predicated instruction now re-defines a register as the result of
1345 // if-conversion, add an implicit kill.
1346 UpdatePredRedefs(MI, Redefs, TRI, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 }
1348
1349 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1350 FromBBI.BB->succ_end());
1351 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1352 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1353
1354 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1355 MachineBasicBlock *Succ = Succs[i];
1356 // Fallthrough edge can't be transferred.
1357 if (Succ == FallThrough)
1358 continue;
Dan Gohman710011c2009-05-05 21:10:19 +00001359 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 }
1361
1362 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1363 std::back_inserter(ToBBI.Predicate));
1364 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1365
1366 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1367 ToBBI.IsAnalyzed = false;
1368
1369 NumDupBBs++;
1370}
1371
1372/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1373///
1374void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
1375 ToBBI.BB->splice(ToBBI.BB->end(),
1376 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1377
Bob Wilsonf3dc37d2009-05-14 18:08:41 +00001378 // Redirect all branches to FromBB to ToBB.
1379 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
1380 FromBBI.BB->pred_end());
1381 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1382 MachineBasicBlock *Pred = Preds[i];
1383 if (Pred == ToBBI.BB)
1384 continue;
1385 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
1386 }
Bob Wilson2f5b10d2010-06-15 22:18:54 +00001387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1389 FromBBI.BB->succ_end());
1390 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1391 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1392
1393 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1394 MachineBasicBlock *Succ = Succs[i];
1395 // Fallthrough edge can't be transferred.
1396 if (Succ == FallThrough)
1397 continue;
1398 FromBBI.BB->removeSuccessor(Succ);
Dan Gohman710011c2009-05-05 21:10:19 +00001399 ToBBI.BB->addSuccessor(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400 }
1401
Bob Wilson4a2f20d2009-05-13 23:25:24 +00001402 // Now FromBBI always falls through to the next block!
Bob Wilson58c9e3c2009-05-13 23:48:58 +00001403 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 FromBBI.BB->addSuccessor(NBB);
1405
1406 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1407 std::back_inserter(ToBBI.Predicate));
1408 FromBBI.Predicate.clear();
1409
1410 ToBBI.NonPredSize += FromBBI.NonPredSize;
1411 FromBBI.NonPredSize = 0;
1412
1413 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1414 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1415 ToBBI.IsAnalyzed = false;
1416 FromBBI.IsAnalyzed = false;
1417}