blob: 5405fc8ae908f5468f014e4bf22e06be79ee022a [file] [log] [blame]
Evan Cheng4e654852007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the Evan Cheng and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Cheng5f702182007-06-01 00:12:12 +000014#define DEBUG_TYPE "ifcvt"
15#include "llvm/Function.h"
Evan Cheng4e654852007-05-16 02:00:57 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/CodeGen/MachineModuleInfo.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng86cbfea2007-05-18 00:20:58 +000020#include "llvm/Target/TargetLowering.h"
Evan Cheng4e654852007-05-16 02:00:57 +000021#include "llvm/Target/TargetMachine.h"
Evan Chengedf48962007-06-08 19:10:51 +000022#include "llvm/Support/CommandLine.h"
Evan Cheng4e654852007-05-16 02:00:57 +000023#include "llvm/Support/Debug.h"
Evan Cheng36489bb2007-05-18 19:26:33 +000024#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng4e654852007-05-16 02:00:57 +000025#include "llvm/ADT/Statistic.h"
26using namespace llvm;
27
Evan Chengedf48962007-06-08 19:10:51 +000028namespace {
29 // Hidden options for help debugging.
30 cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31 cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32 cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33 cl::opt<bool> DisableSimple("disable-ifcvt-simple",
34 cl::init(false), cl::Hidden);
35 cl::opt<bool> DisableSimpleFalse("disable-ifcvt-simple-false",
36 cl::init(false), cl::Hidden);
37 cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
38 cl::init(false), cl::Hidden);
39 cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
40 cl::init(false), cl::Hidden);
41}
42
Evan Chengb6665f62007-06-04 06:47:22 +000043STATISTIC(NumSimple, "Number of simple if-conversions performed");
44STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
45STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
46STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Evan Cheng4e654852007-05-16 02:00:57 +000047STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
48
49namespace {
50 class IfConverter : public MachineFunctionPass {
51 enum BBICKind {
Evan Chenga13aa952007-05-23 07:23:16 +000052 ICNotAnalyzed, // BB has not been analyzed.
53 ICReAnalyze, // BB must be re-analyzed.
Evan Cheng4e654852007-05-16 02:00:57 +000054 ICNotClassfied, // BB data valid, but not classified.
Evan Chengb6665f62007-06-04 06:47:22 +000055 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
56 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Chenga6b4f432007-05-21 22:22:58 +000057 ICTriangle, // BB is entry of a triangle sub-CFG.
58 ICDiamond, // BB is entry of a diamond sub-CFG.
59 ICChild, // BB is part of the sub-CFG that'll be predicated.
Evan Cheng7a655472007-06-06 10:16:17 +000060 ICDead // BB cannot be if-converted again.
Evan Cheng4e654852007-05-16 02:00:57 +000061 };
62
63 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
64 /// if-conversion feasibility analysis. This includes results from
65 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000066 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000067 /// diamond shape), its size, whether it's predicable, and whether any
68 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000069 ///
70 /// Kind - Type of block. See BBICKind.
71 /// NonPredSize - Number of non-predicated instructions.
Evan Chengb6665f62007-06-04 06:47:22 +000072 /// IsAnalyzable - True if AnalyzeBranch() returns false.
Evan Cheng7a655472007-06-06 10:16:17 +000073 /// ModifyPredicate - True if BB would modify the predicate (e.g. has
74 /// cmp, call, etc.)
Evan Chenga13aa952007-05-23 07:23:16 +000075 /// BB - Corresponding MachineBasicBlock.
76 /// TrueBB / FalseBB- See AnalyzeBranch().
77 /// BrCond - Conditions for end of block conditional branches.
78 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +000079 struct BBInfo {
80 BBICKind Kind;
Evan Chenga13aa952007-05-23 07:23:16 +000081 unsigned NonPredSize;
Evan Chengb6665f62007-06-04 06:47:22 +000082 bool IsAnalyzable;
Evan Chengd4de6d92007-06-07 02:12:15 +000083 bool hasFallThrough;
Evan Chenga13aa952007-05-23 07:23:16 +000084 bool ModifyPredicate;
Evan Cheng86cbfea2007-05-18 00:20:58 +000085 MachineBasicBlock *BB;
86 MachineBasicBlock *TrueBB;
87 MachineBasicBlock *FalseBB;
88 MachineBasicBlock *TailBB;
Evan Chenga13aa952007-05-23 07:23:16 +000089 std::vector<MachineOperand> BrCond;
90 std::vector<MachineOperand> Predicate;
Evan Chengb6665f62007-06-04 06:47:22 +000091 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
Evan Chengd4de6d92007-06-07 02:12:15 +000092 IsAnalyzable(false), hasFallThrough(false),
93 ModifyPredicate(false),
Evan Chenga6b4f432007-05-21 22:22:58 +000094 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
Evan Cheng4e654852007-05-16 02:00:57 +000095 };
96
Evan Cheng82582102007-05-30 19:49:19 +000097 /// Roots - Basic blocks that do not have successors. These are the starting
98 /// points of Graph traversal.
99 std::vector<MachineBasicBlock*> Roots;
100
Evan Cheng4e654852007-05-16 02:00:57 +0000101 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
102 /// basic block number.
103 std::vector<BBInfo> BBAnalysis;
104
Evan Cheng86cbfea2007-05-18 00:20:58 +0000105 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000106 const TargetInstrInfo *TII;
107 bool MadeChange;
108 public:
109 static char ID;
110 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
111
112 virtual bool runOnMachineFunction(MachineFunction &MF);
113 virtual const char *getPassName() const { return "If converter"; }
114
115 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000116 bool ReverseBranchCondition(BBInfo &BBI);
Evan Chengac5f1422007-06-08 09:36:04 +0000117 bool ValidSimple(BBInfo &TrueBBI) const;
118 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
119 bool FalseBranch = false) const;
Evan Chengd4de6d92007-06-07 02:12:15 +0000120 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000121 void ScanInstructions(BBInfo &BBI);
122 void AnalyzeBlock(MachineBasicBlock *BB);
123 bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
124 bool isTriangle = false, bool RevBranch = false);
Evan Cheng82582102007-05-30 19:49:19 +0000125 bool AttemptRestructuring(BBInfo &BBI);
126 bool AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000127 std::vector<BBInfo*> &Candidates);
Evan Cheng82582102007-05-30 19:49:19 +0000128 void ReTryPreds(MachineBasicBlock *BB);
Evan Chengb6665f62007-06-04 06:47:22 +0000129 bool IfConvertSimple(BBInfo &BBI);
Evan Cheng4e654852007-05-16 02:00:57 +0000130 bool IfConvertTriangle(BBInfo &BBI);
Evan Chengcf6cc112007-05-18 18:14:37 +0000131 bool IfConvertDiamond(BBInfo &BBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000132 void PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000133 std::vector<MachineOperand> &Cond,
134 bool IgnoreTerm = false);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000135 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
Evan Cheng5f702182007-06-01 00:12:12 +0000136
Evan Chengd4de6d92007-06-07 02:12:15 +0000137 // blockAlwaysFallThrough - Block ends without a terminator.
138 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng7a655472007-06-06 10:16:17 +0000139 return BBI.IsAnalyzable && BBI.TrueBB == NULL;
140 }
141
Evan Cheng5f702182007-06-01 00:12:12 +0000142 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
143 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
144 // Favor diamond over triangle, etc.
145 return (unsigned)C1->Kind < (unsigned)C2->Kind;
146 }
Evan Cheng4e654852007-05-16 02:00:57 +0000147 };
148 char IfConverter::ID = 0;
149}
150
151FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
152
153bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000154 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000155 TII = MF.getTarget().getInstrInfo();
156 if (!TII) return false;
157
Evan Chengedf48962007-06-08 19:10:51 +0000158 static int FnNum = -1;
159 DOUT << "\nIfcvt: function (" << ++FnNum << ") \'"
160 << MF.getFunction()->getName() << "\'";
161
162 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
163 DOUT << " skipped\n";
164 return false;
165 }
166 DOUT << "\n";
Evan Cheng5f702182007-06-01 00:12:12 +0000167
Evan Cheng4e654852007-05-16 02:00:57 +0000168 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000169 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000170
Evan Cheng82582102007-05-30 19:49:19 +0000171 // Look for root nodes, i.e. blocks without successors.
172 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
173 if (I->succ_size() == 0)
174 Roots.push_back(I);
175
Evan Cheng7f8ff8a2007-05-18 19:32:08 +0000176 std::vector<BBInfo*> Candidates;
Evan Cheng47d25022007-05-18 01:55:58 +0000177 MadeChange = false;
Evan Chengedf48962007-06-08 19:10:51 +0000178 while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
Evan Chenga13aa952007-05-23 07:23:16 +0000179 // Do an intial analysis for each basic block and finding all the potential
180 // candidates to perform if-convesion.
Evan Chengb6665f62007-06-04 06:47:22 +0000181 bool Change = AnalyzeBlocks(MF, Candidates);
Evan Chenga13aa952007-05-23 07:23:16 +0000182 while (!Candidates.empty()) {
183 BBInfo &BBI = *Candidates.back();
184 Candidates.pop_back();
Evan Chengb6665f62007-06-04 06:47:22 +0000185
186 bool RetVal = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000187 switch (BBI.Kind) {
188 default: assert(false && "Unexpected!");
189 break;
Evan Cheng5f702182007-06-01 00:12:12 +0000190 case ICReAnalyze:
Evan Chengf5305f92007-06-05 00:07:37 +0000191 // One or more of 'children' have been modified, abort!
192 case ICDead:
193 // Block has been already been if-converted, abort!
Evan Cheng5f702182007-06-01 00:12:12 +0000194 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000195 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000196 case ICSimpleFalse: {
197 bool isRev = BBI.Kind == ICSimpleFalse;
Evan Chengedf48962007-06-08 19:10:51 +0000198 if ((isRev && DisableSimpleFalse) || (!isRev && DisableSimple)) break;
Evan Chengb6665f62007-06-04 06:47:22 +0000199 DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
Evan Cheng7a655472007-06-06 10:16:17 +0000200 << "): BB#" << BBI.BB->getNumber() << " ("
201 << ((BBI.Kind == ICSimpleFalse)
202 ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000203 RetVal = IfConvertSimple(BBI);
204 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
205 if (RetVal)
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000206 if (isRev) NumSimpleRev++;
207 else NumSimple++;
Evan Chengb6665f62007-06-04 06:47:22 +0000208 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000209 }
Evan Chenga13aa952007-05-23 07:23:16 +0000210 case ICTriangle:
Evan Chengedf48962007-06-08 19:10:51 +0000211 if (DisableTriangle) break;
Evan Cheng7a655472007-06-06 10:16:17 +0000212 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " (T:"
213 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
214 << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000215 RetVal = IfConvertTriangle(BBI);
216 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
217 if (RetVal) NumTriangle++;
Evan Chenga13aa952007-05-23 07:23:16 +0000218 break;
219 case ICDiamond:
Evan Chengedf48962007-06-08 19:10:51 +0000220 if (DisableDiamond) break;
Evan Cheng7a655472007-06-06 10:16:17 +0000221 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
222 << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
223 if (BBI.TailBB)
224 DOUT << "," << BBI.TailBB->getNumber() ;
225 DOUT << ") ";
Evan Chengb6665f62007-06-04 06:47:22 +0000226 RetVal = IfConvertDiamond(BBI);
227 DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
228 if (RetVal) NumDiamonds++;
Evan Chenga13aa952007-05-23 07:23:16 +0000229 break;
230 }
Evan Chengb6665f62007-06-04 06:47:22 +0000231 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000232
233 if (IfCvtLimit != -1 && (int)NumIfConvBBs > IfCvtLimit)
234 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000235 }
Evan Chenga13aa952007-05-23 07:23:16 +0000236
Evan Chenga13aa952007-05-23 07:23:16 +0000237 if (!Change)
238 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000239 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000240 }
Evan Cheng47d25022007-05-18 01:55:58 +0000241
Evan Cheng82582102007-05-30 19:49:19 +0000242 Roots.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000243 BBAnalysis.clear();
244
Evan Cheng4e654852007-05-16 02:00:57 +0000245 return MadeChange;
246}
247
248static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000249 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000250 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
251 E = BB->succ_end(); SI != E; ++SI) {
252 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000253 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000254 return SuccBB;
255 }
256 return NULL;
257}
258
Evan Chengb6665f62007-06-04 06:47:22 +0000259bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
260 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
261 TII->RemoveBranch(*BBI.BB);
262 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
263 std::swap(BBI.TrueBB, BBI.FalseBB);
264 return true;
265 }
266 return false;
267}
268
Evan Chengac5f1422007-06-08 09:36:04 +0000269/// ValidSimple - Returns true if the 'true' block (along with its
270/// predecessor) forms a valid simple shape for ifcvt.
271bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
272 return !blockAlwaysFallThrough(TrueBBI) &&
273 TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
Evan Cheng7a655472007-06-06 10:16:17 +0000274}
275
Evan Chengac5f1422007-06-08 09:36:04 +0000276/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000277/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chengac5f1422007-06-08 09:36:04 +0000278bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
279 bool FalseBranch) const {
Evan Chengd4de6d92007-06-07 02:12:15 +0000280 if (TrueBBI.BB->pred_size() != 1)
281 return false;
282
Evan Chengac5f1422007-06-08 09:36:04 +0000283 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
284 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000285 MachineFunction::iterator I = TrueBBI.BB;
286 if (++I == TrueBBI.BB->getParent()->end())
287 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000288 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000289 }
Evan Chengac5f1422007-06-08 09:36:04 +0000290 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000291}
292
Evan Chengac5f1422007-06-08 09:36:04 +0000293/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000294/// with their common predecessor) forms a valid diamond shape for ifcvt.
295bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
Evan Chengac5f1422007-06-08 09:36:04 +0000296 // FIXME: Also look for fallthrough
Evan Chengd4de6d92007-06-07 02:12:15 +0000297 return (TrueBBI.TrueBB == FalseBBI.TrueBB &&
298 TrueBBI.BB->pred_size() == 1 &&
299 FalseBBI.BB->pred_size() == 1 &&
Evan Chengd4de6d92007-06-07 02:12:15 +0000300 !TrueBBI.FalseBB && !FalseBBI.FalseBB);
301}
302
Evan Chengac5f1422007-06-08 09:36:04 +0000303/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000304/// the specified block. Record its successors and whether it looks like an
305/// if-conversion candidate.
Evan Chengac5f1422007-06-08 09:36:04 +0000306void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000307 BBInfo &BBI = BBAnalysis[BB->getNumber()];
308
Evan Chengf5305f92007-06-05 00:07:37 +0000309 if (BBI.Kind == ICReAnalyze) {
Evan Chengb6665f62007-06-04 06:47:22 +0000310 BBI.BrCond.clear();
Evan Chengf5305f92007-06-05 00:07:37 +0000311 BBI.TrueBB = BBI.FalseBB = NULL;
312 } else {
Evan Chenga13aa952007-05-23 07:23:16 +0000313 if (BBI.Kind != ICNotAnalyzed)
314 return; // Already analyzed.
315 BBI.BB = BB;
316 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000317 }
Evan Cheng86cbfea2007-05-18 00:20:58 +0000318
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000319 // Look for 'root' of a simple (non-nested) triangle or diamond.
320 BBI.Kind = ICNotClassfied;
Evan Chengb6665f62007-06-04 06:47:22 +0000321 BBI.IsAnalyzable =
322 !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Chengd4de6d92007-06-07 02:12:15 +0000323 BBI.hasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
324 // Unanalyable or ends with fallthrough or unconditional branch.
Evan Chengb6665f62007-06-04 06:47:22 +0000325 if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000326 return;
Evan Chenge0043172007-06-05 20:38:42 +0000327 // Do not ifcvt if either path is a back edge to the entry block.
328 if (BBI.TrueBB == BB || BBI.FalseBB == BB)
329 return;
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000330
Evan Chengac5f1422007-06-08 09:36:04 +0000331 AnalyzeBlock(BBI.TrueBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000332 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengd6ddc302007-05-16 21:54:37 +0000333
334 // No false branch. This BB must end with a conditional branch and a
335 // fallthrough.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000336 if (!BBI.FalseBB)
337 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
338 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
Evan Chengc5d05ef2007-05-16 05:11:10 +0000339
Evan Chengac5f1422007-06-08 09:36:04 +0000340 AnalyzeBlock(BBI.FalseBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000341 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng7a655472007-06-06 10:16:17 +0000342
343 // If both paths are dead, then forget about it.
344 if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
345 BBI.Kind = ICDead;
346 return;
347 }
348
Evan Chengb6665f62007-06-04 06:47:22 +0000349 // Look for more opportunities to if-convert a triangle. Try to restructure
350 // the CFG to form a triangle with the 'false' path.
351 std::vector<MachineOperand> RevCond(BBI.BrCond);
352 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000353
354 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
355 !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
356 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
357 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000358 // Diamond:
359 // EBB
360 // / \_
361 // | |
362 // TBB FBB
363 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000364 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000365 // Note TailBB can be empty.
Evan Chenga6b4f432007-05-21 22:22:58 +0000366 BBI.Kind = ICDiamond;
367 TrueBBI.Kind = FalseBBI.Kind = ICChild;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000368 BBI.TailBB = TrueBBI.TrueBB;
Evan Chengb6665f62007-06-04 06:47:22 +0000369 } else {
370 // FIXME: Consider duplicating if BB is small.
Evan Chengac5f1422007-06-08 09:36:04 +0000371 if (ValidTriangle(TrueBBI, FalseBBI) &&
372 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
373 // Triangle:
374 // EBB
375 // | \_
376 // | |
377 // | TBB
378 // | /
379 // FBB
380 BBI.Kind = ICTriangle;
381 TrueBBI.Kind = ICChild;
382 } else if (ValidSimple(TrueBBI) &&
383 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
384 // Simple (split, no rejoin):
385 // EBB
386 // | \_
387 // | |
388 // | TBB---> exit
389 // |
390 // FBB
391 BBI.Kind = ICSimple;
392 TrueBBI.Kind = ICChild;
393 } else if (CanRevCond) {
Evan Chenge7052132007-06-06 00:57:55 +0000394 // Try the other path...
Evan Chengac5f1422007-06-08 09:36:04 +0000395 if (ValidTriangle(FalseBBI, TrueBBI) &&
396 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
397 // Reverse 'true' and 'false' paths.
398 ReverseBranchCondition(BBI);
399 BBI.Kind = ICTriangle;
400 FalseBBI.Kind = ICChild;
401 } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
402 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
403 ReverseBranchCondition(FalseBBI);
404 ReverseBranchCondition(BBI);
405 BBI.Kind = ICTriangle;
406 FalseBBI.Kind = ICChild;
407 } else if (ValidSimple(FalseBBI) &&
408 FeasibilityAnalysis(FalseBBI, RevCond)) {
409 BBI.Kind = ICSimpleFalse;
410 FalseBBI.Kind = ICChild;
Evan Chengb6665f62007-06-04 06:47:22 +0000411 }
412 }
Evan Cheng4e654852007-05-16 02:00:57 +0000413 }
414 return;
415}
416
Evan Chengcf6cc112007-05-18 18:14:37 +0000417/// FeasibilityAnalysis - Determine if the block is predicable. In most
418/// cases, that means all the instructions in the block has M_PREDICABLE flag.
419/// Also checks if the block contains any instruction which can clobber a
420/// predicate (e.g. condition code register). If so, the block is not
Evan Chengac5f1422007-06-08 09:36:04 +0000421/// predicable unless it's the last instruction.
Evan Chengb6665f62007-06-04 06:47:22 +0000422bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Evan Chengac5f1422007-06-08 09:36:04 +0000423 std::vector<MachineOperand> &Pred,
424 bool isTriangle, bool RevBranch) {
Evan Chengb6665f62007-06-04 06:47:22 +0000425 // If the block is dead, or it is going to be the entry block of a sub-CFG
426 // that will be if-converted, then it cannot be predicated.
427 if (BBI.Kind != ICNotAnalyzed &&
428 BBI.Kind != ICNotClassfied &&
429 BBI.Kind != ICChild)
430 return false;
431
432 // Check predication threshold.
Evan Chenga13aa952007-05-23 07:23:16 +0000433 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
Evan Chengb6665f62007-06-04 06:47:22 +0000434 return false;
435
436 // If it is already predicated, check if its predicate subsumes the new
437 // predicate.
Evan Chengac5f1422007-06-08 09:36:04 +0000438 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
Evan Chengb6665f62007-06-04 06:47:22 +0000439 return false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000440
Evan Chengac5f1422007-06-08 09:36:04 +0000441 bool SeenPredMod = false;
442 bool SeenCondBr = false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000443 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
444 I != E; ++I) {
Evan Chengac5f1422007-06-08 09:36:04 +0000445 const TargetInstrDescriptor *TID = I->getInstrDescriptor();
446 if (SeenPredMod) {
447 // Predicate modification instruction should end the block (except for
448 // already predicated instructions and end of block branches).
449 if (!TII->isPredicated(I)) {
450 // This is the 'true' block of a triangle, i.e. its 'true' block is
451 // the same as the 'false' block of the entry. So false positive
452 // is ok.
453 if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
454 (TID->Flags & M_BRANCH_FLAG) != 0 &&
455 (TID->Flags & M_BARRIER_FLAG) == 0) {
456 // This is the first conditional branch, test predicate subsumsion.
457 std::vector<MachineOperand> RevPred(Pred);
458 std::vector<MachineOperand> Cond(BBI.BrCond);
459 if (RevBranch) {
460 if (TII->ReverseBranchCondition(Cond))
461 return false;
462 }
463 if (TII->ReverseBranchCondition(RevPred) ||
464 !TII->SubsumesPredicate(Cond, RevPred))
465 return false;
466 SeenCondBr = true;
467 continue; // Conditional branches is not predicable.
468 }
469 return false;
470 }
471 }
472
473 if (TID->Flags & M_CLOBBERS_PRED) {
474 BBI.ModifyPredicate = true;
475 SeenPredMod = true;
476 }
477
Evan Chengcf6cc112007-05-18 18:14:37 +0000478 if (!I->isPredicable())
Evan Chengb6665f62007-06-04 06:47:22 +0000479 return false;
Evan Chengcf6cc112007-05-18 18:14:37 +0000480 }
481
Evan Chengb6665f62007-06-04 06:47:22 +0000482 return true;
Evan Chengcf6cc112007-05-18 18:14:37 +0000483}
484
Evan Cheng82582102007-05-30 19:49:19 +0000485/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
486/// expose more if-conversion opportunities. e.g.
487///
488/// cmp
489/// b le BB1
490/// / \____
491/// / |
492/// cmp |
493/// b eq BB1 |
494/// / \____ |
495/// / \ |
496/// BB1
497/// ==>
498///
499/// cmp
500/// b eq BB1
501/// / \____
502/// / |
503/// cmp |
504/// b le BB1 |
505/// / \____ |
506/// / \ |
507/// BB1
508bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
509 return false;
510}
511
512/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
513/// candidates. It returns true if any CFG restructuring is done to expose more
514/// if-conversion opportunities.
515bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000516 std::vector<BBInfo*> &Candidates) {
Evan Cheng82582102007-05-30 19:49:19 +0000517 bool Change = false;
Evan Cheng36489bb2007-05-18 19:26:33 +0000518 std::set<MachineBasicBlock*> Visited;
Evan Cheng82582102007-05-30 19:49:19 +0000519 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
520 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
521 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
522 MachineBasicBlock *BB = *I;
Evan Chengac5f1422007-06-08 09:36:04 +0000523 AnalyzeBlock(BB);
Evan Cheng82582102007-05-30 19:49:19 +0000524 BBInfo &BBI = BBAnalysis[BB->getNumber()];
525 switch (BBI.Kind) {
Evan Chengb6665f62007-06-04 06:47:22 +0000526 case ICSimple:
527 case ICSimpleFalse:
Evan Cheng82582102007-05-30 19:49:19 +0000528 case ICTriangle:
529 case ICDiamond:
530 Candidates.push_back(&BBI);
531 break;
532 default:
533 Change |= AttemptRestructuring(BBI);
534 break;
535 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000536 }
Evan Cheng4e654852007-05-16 02:00:57 +0000537 }
Evan Cheng82582102007-05-30 19:49:19 +0000538
Evan Cheng5f702182007-06-01 00:12:12 +0000539 // Sort to favor more complex ifcvt scheme.
540 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
541
Evan Cheng82582102007-05-30 19:49:19 +0000542 return Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000543}
544
Evan Chengb6665f62007-06-04 06:47:22 +0000545/// isNextBlock - Returns true either if ToBB the next block after BB or
546/// that all the intervening blocks are empty.
Evan Chenga6b4f432007-05-21 22:22:58 +0000547static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Chengb6665f62007-06-04 06:47:22 +0000548 MachineFunction::iterator I = BB;
Evan Chengc53ef582007-06-05 07:05:25 +0000549 MachineFunction::iterator TI = ToBB;
550 MachineFunction::iterator E = BB->getParent()->end();
551 while (++I != TI)
552 if (I == E || !I->empty())
Evan Chengb6665f62007-06-04 06:47:22 +0000553 return false;
554 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000555}
556
Evan Cheng82582102007-05-30 19:49:19 +0000557/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
Evan Chenga13aa952007-05-23 07:23:16 +0000558/// to determine if it can be if-converted.
Evan Cheng82582102007-05-30 19:49:19 +0000559void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000560 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
561 E = BB->pred_end(); PI != E; ++PI) {
562 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
563 PBBI.Kind = ICReAnalyze;
564 }
565}
566
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000567/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
568///
569static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
570 const TargetInstrInfo *TII) {
571 std::vector<MachineOperand> NoCond;
572 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
573}
574
Evan Chengb6665f62007-06-04 06:47:22 +0000575/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +0000576///
Evan Chengb6665f62007-06-04 06:47:22 +0000577bool IfConverter::IfConvertSimple(BBInfo &BBI) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000578 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
579 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
580 BBInfo *CvtBBI = &TrueBBI;
581 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000582
Evan Chengb6665f62007-06-04 06:47:22 +0000583 std::vector<MachineOperand> Cond(BBI.BrCond);
Evan Cheng7a655472007-06-06 10:16:17 +0000584 if (BBI.Kind == ICSimpleFalse) {
Evan Chengb5a06902007-06-01 20:29:21 +0000585 std::swap(CvtBBI, NextBBI);
Evan Chengb6665f62007-06-04 06:47:22 +0000586 TII->ReverseBranchCondition(Cond);
Evan Chengb5a06902007-06-01 20:29:21 +0000587 }
Evan Chenga13aa952007-05-23 07:23:16 +0000588
Evan Chengb6665f62007-06-04 06:47:22 +0000589 PredicateBlock(*CvtBBI, Cond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000590
Evan Chengb6665f62007-06-04 06:47:22 +0000591 // Merge converted block into entry block. Also add an unconditional branch
592 // to the 'false' branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000593 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000594 MergeBlocks(BBI, *CvtBBI);
Evan Chengac5f1422007-06-08 09:36:04 +0000595 BBI.BB->removeSuccessor(CvtBBI->BB);
Evan Chengd4de6d92007-06-07 02:12:15 +0000596
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000597 bool IterIfcvt = true;
598 if (!isNextBlock(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000599 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Chengd4de6d92007-06-07 02:12:15 +0000600 BBI.hasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +0000601 // Now ifcvt'd block will look like this:
602 // BB:
603 // ...
604 // t, f = cmp
605 // if t op
606 // b BBf
607 //
608 // We cannot further ifcvt this block because the unconditional branch
609 // will have to be predicated on the new condition, that will not be
610 // available if cmp executes.
611 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000612 }
Evan Chengb6665f62007-06-04 06:47:22 +0000613 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000614
Evan Chenga13aa952007-05-23 07:23:16 +0000615 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000616 if (IterIfcvt)
617 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000618 else
619 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000620 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000621 CvtBBI->Kind = ICDead;
622
623 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000624 return true;
625}
626
Evan Chengd6ddc302007-05-16 21:54:37 +0000627/// IfConvertTriangle - If convert a triangle sub-CFG.
628///
Evan Cheng4e654852007-05-16 02:00:57 +0000629bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000630 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng8c529382007-06-01 07:41:07 +0000631
Evan Chenga6b4f432007-05-21 22:22:58 +0000632 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000633 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
634 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000635
Evan Chengb6665f62007-06-04 06:47:22 +0000636 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +0000637 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
638 if (HasEarlyExit) {
Evan Cheng8c529382007-06-01 07:41:07 +0000639 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
640 if (TII->ReverseBranchCondition(RevCond))
641 assert(false && "Unable to reverse branch condition!");
642 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
643 }
644
Evan Chengac5f1422007-06-08 09:36:04 +0000645 // Now merge the entry of the triangle with the true block.
646 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
647 MergeBlocks(BBI, TrueBBI);
648
649 // Merge in the 'false' block if the 'false' block has no other
650 // predecessors. Otherwise, add a unconditional branch from to 'false'.
Evan Chenga6b4f432007-05-21 22:22:58 +0000651 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengf5305f92007-06-05 00:07:37 +0000652 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000653 bool IterIfcvt = true;
Evan Chengac5f1422007-06-08 09:36:04 +0000654 bool isFallThrough = isNextBlock(BBI.BB, FalseBBI.BB);
Evan Chengf4769612007-06-07 08:13:00 +0000655 if (!isFallThrough) {
656 // Only merge them if the true block does not fallthrough to the false
657 // block. By not merging them, we make it possible to iteratively
658 // ifcvt the blocks.
Evan Chengac5f1422007-06-08 09:36:04 +0000659 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
660 MergeBlocks(BBI, FalseBBI);
Evan Chengf4769612007-06-07 08:13:00 +0000661 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +0000662 } else {
Evan Chengac5f1422007-06-08 09:36:04 +0000663 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
Evan Chengf4769612007-06-07 08:13:00 +0000664 TrueBBI.hasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +0000665 }
Evan Chengac5f1422007-06-08 09:36:04 +0000666 // Mixed predicated and unpredicated code. This cannot be iteratively
667 // predicated.
668 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000669 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000670
Evan Cheng27af5c42007-06-07 22:31:28 +0000671 // Remove entry to false edge if false block is merged in as well.
Evan Chengac5f1422007-06-08 09:36:04 +0000672 if (FalseBBDead)
Evan Chengf4769612007-06-07 08:13:00 +0000673 BBI.BB->removeSuccessor(FalseBBI.BB);
Evan Chenga13aa952007-05-23 07:23:16 +0000674 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
675 std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000676
Evan Chenga13aa952007-05-23 07:23:16 +0000677 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000678 if (IterIfcvt)
679 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000680 else
681 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000682 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000683 TrueBBI.Kind = ICDead;
Evan Chengf5305f92007-06-05 00:07:37 +0000684 if (FalseBBDead)
685 FalseBBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000686
687 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000688 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000689}
690
Evan Chengd6ddc302007-05-16 21:54:37 +0000691/// IfConvertDiamond - If convert a diamond sub-CFG.
692///
Evan Cheng4e654852007-05-16 02:00:57 +0000693bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chengb6665f62007-06-04 06:47:22 +0000694 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000695 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000696
Evan Chenga6b4f432007-05-21 22:22:58 +0000697 SmallVector<MachineInstr*, 2> Dups;
Evan Chengb6665f62007-06-04 06:47:22 +0000698 if (!BBI.TailBB) {
699 // No common merge block. Check if the terminators (e.g. return) are
700 // the same or predicable.
701 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
702 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
703 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
704 if (TT->isIdenticalTo(FT))
705 Dups.push_back(TT); // Will erase these later.
706 else if (!TT->isPredicable() && !FT->isPredicable())
707 return false; // Can't if-convert. Abort!
708 ++TT;
709 ++FT;
Evan Chengcf6cc112007-05-18 18:14:37 +0000710 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000711
Evan Chengb6665f62007-06-04 06:47:22 +0000712 // One of the two pathes have more terminators, make sure they are
713 // all predicable.
714 while (TT != BBI.TrueBB->end()) {
715 if (!TT->isPredicable()) {
716 return false; // Can't if-convert. Abort!
Evan Cheng4e654852007-05-16 02:00:57 +0000717 }
Evan Chengb6665f62007-06-04 06:47:22 +0000718 ++TT;
719 }
720 while (FT != BBI.FalseBB->end()) {
721 if (!FT->isPredicable()) {
722 return false; // Can't if-convert. Abort!
723 }
724 ++FT;
Evan Cheng4e654852007-05-16 02:00:57 +0000725 }
Evan Cheng4e654852007-05-16 02:00:57 +0000726 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000727
Evan Chenga6b4f432007-05-21 22:22:58 +0000728 // Remove the duplicated instructions from the 'true' block.
729 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
730 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000731 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000732 }
733
Evan Chenga6b4f432007-05-21 22:22:58 +0000734 // Merge the 'true' and 'false' blocks by copying the instructions
735 // from the 'false' block to the 'true' block. That is, unless the true
736 // block would clobber the predicate, in that case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +0000737 BBInfo *BBI1 = &TrueBBI;
738 BBInfo *BBI2 = &FalseBBI;
Evan Chengb6665f62007-06-04 06:47:22 +0000739 std::vector<MachineOperand> RevCond(BBI.BrCond);
740 TII->ReverseBranchCondition(RevCond);
Evan Cheng993fc952007-06-05 23:46:14 +0000741 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
742 std::vector<MachineOperand> *Cond2 = &RevCond;
Evan Cheng993fc952007-06-05 23:46:14 +0000743 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
744 // Either the block fallthrough to another block or it ends with a
745 // return. If it's the former, add a branch to its successor.
746 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
Evan Chenge7052132007-06-06 00:57:55 +0000747 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
748
749 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
750 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
751 NeedBr1 && !NeedBr2)) {
752 std::swap(BBI1, BBI2);
753 std::swap(Cond1, Cond2);
754 std::swap(NeedBr1, NeedBr2);
755 }
Evan Cheng993fc952007-06-05 23:46:14 +0000756
757 // Predicate the 'true' block after removing its branch.
758 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
759 PredicateBlock(*BBI1, *Cond1);
760
761 // Add an early exit branch if needed.
762 if (NeedBr1)
763 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
764
765 // Predicate the 'false' block.
766 PredicateBlock(*BBI2, *Cond2, true);
767
768 // Add an unconditional branch from 'false' to to 'false' successor if it
769 // will not be the fallthrough block.
Evan Chengd4de6d92007-06-07 02:12:15 +0000770 if (NeedBr2 && !NeedBr1) {
771 // If BBI2 isn't going to be merged in, then the existing fallthrough
772 // or branch is fine.
773 if (!isNextBlock(BBI.BB, *BBI2->BB->succ_begin())) {
774 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
775 BBI2->hasFallThrough = false;
776 }
777 }
Evan Cheng993fc952007-06-05 23:46:14 +0000778
779 // Keep them as two separate blocks if there is an early exit.
780 if (!NeedBr1)
781 MergeBlocks(*BBI1, *BBI2);
Evan Cheng993fc952007-06-05 23:46:14 +0000782
Evan Chenga6b4f432007-05-21 22:22:58 +0000783 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000784 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000785
Evan Cheng993fc952007-06-05 23:46:14 +0000786 // Merge the combined block into the entry of the diamond.
787 MergeBlocks(BBI, *BBI1);
Evan Chengd4de6d92007-06-07 02:12:15 +0000788 std::copy(Cond1->begin(), Cond1->end(),
789 std::back_inserter(BBI.Predicate));
790 if (!NeedBr1)
791 std::copy(Cond2->begin(), Cond2->end(),
792 std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000793
Evan Chenge7052132007-06-06 00:57:55 +0000794 // 'True' and 'false' aren't combined, see if we need to add a unconditional
795 // branch to the 'false' block.
Evan Chengd4de6d92007-06-07 02:12:15 +0000796 if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB)) {
797 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
798 BBI1->hasFallThrough = false;
799 }
Evan Chenge7052132007-06-06 00:57:55 +0000800
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000801 // If the if-converted block fallthrough or unconditionally branch into the
802 // tail block, and the tail block does not have other predecessors, then
Evan Chenga6b4f432007-05-21 22:22:58 +0000803 // fold the tail block in as well.
Evan Cheng993fc952007-06-05 23:46:14 +0000804 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000805 if (BBI.TailBB &&
Evan Chengf15d44c2007-05-31 20:53:33 +0000806 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000807 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000808 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
809 MergeBlocks(*CvtBBI, TailBBI);
810 TailBBI.Kind = ICDead;
811 }
812
Evan Cheng993fc952007-06-05 23:46:14 +0000813 // Update block info.
Evan Cheng7a655472007-06-06 10:16:17 +0000814 BBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000815 TrueBBI.Kind = ICDead;
816 FalseBBI.Kind = ICDead;
817
818 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000819 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000820}
821
Evan Cheng4e654852007-05-16 02:00:57 +0000822/// PredicateBlock - Predicate every instruction in the block with the specified
823/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000824void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000825 std::vector<MachineOperand> &Cond,
826 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000827 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000828 I != E; ++I) {
Evan Chengb6665f62007-06-04 06:47:22 +0000829 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000830 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000831 if (TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +0000832 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000833 if (!TII->PredicateInstruction(I, Cond)) {
Evan Chengfe57a7e2007-06-01 00:55:26 +0000834 cerr << "Unable to predicate " << *I << "!\n";
Evan Chengd6ddc302007-05-16 21:54:37 +0000835 abort();
836 }
Evan Cheng4e654852007-05-16 02:00:57 +0000837 }
Evan Chenga13aa952007-05-23 07:23:16 +0000838
839 BBI.NonPredSize = 0;
Evan Chengb6665f62007-06-04 06:47:22 +0000840 NumIfConvBBs++;
841}
842
Evan Chengd4de6d92007-06-07 02:12:15 +0000843static MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
844 MachineFunction::iterator I = BB;
845 MachineFunction::iterator E = BB->getParent()->end();
846 if (++I == E)
847 return NULL;
848 return I;
Evan Cheng4e654852007-05-16 02:00:57 +0000849}
850
Evan Cheng86cbfea2007-05-18 00:20:58 +0000851/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000852///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000853void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
854 ToBBI.BB->splice(ToBBI.BB->end(),
855 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000856
Evan Chengb6665f62007-06-04 06:47:22 +0000857 // Redirect all branches to FromBB to ToBB.
Evan Chenga1a9f402007-06-05 22:03:53 +0000858 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
859 FromBBI.BB->pred_end());
Evan Chengd4de6d92007-06-07 02:12:15 +0000860 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
861 MachineBasicBlock *Pred = Preds[i];
862 if (Pred == ToBBI.BB)
863 continue;
864 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
865 }
866
867 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
868 FromBBI.BB->succ_end());
869 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough
870 ? getNextBlock(FromBBI.BB) : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +0000871
Evan Chengd4de6d92007-06-07 02:12:15 +0000872 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
873 MachineBasicBlock *Succ = Succs[i];
874 if (Succ == FallThrough)
875 continue;
876 FromBBI.BB->removeSuccessor(Succ);
877 if (!ToBBI.BB->isSuccessor(Succ))
878 ToBBI.BB->addSuccessor(Succ);
879 }
880
Evan Chenga13aa952007-05-23 07:23:16 +0000881 ToBBI.NonPredSize += FromBBI.NonPredSize;
882 FromBBI.NonPredSize = 0;
Evan Cheng7a655472007-06-06 10:16:17 +0000883
884 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
Evan Chengd4de6d92007-06-07 02:12:15 +0000885 ToBBI.hasFallThrough = FromBBI.hasFallThrough;
Evan Cheng4e654852007-05-16 02:00:57 +0000886}