blob: 05be5d59c7648488f406219c88fe9c0d5654929c [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 Chenga6b4f432007-05-21 22:22:58 +0000613
Evan Chenga13aa952007-05-23 07:23:16 +0000614 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000615 if (IterIfcvt)
616 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000617 else
618 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000619 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000620 CvtBBI->Kind = ICDead;
621
622 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000623 return true;
624}
625
Evan Chengd6ddc302007-05-16 21:54:37 +0000626/// IfConvertTriangle - If convert a triangle sub-CFG.
627///
Evan Cheng4e654852007-05-16 02:00:57 +0000628bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000629 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng8c529382007-06-01 07:41:07 +0000630
Evan Chenga6b4f432007-05-21 22:22:58 +0000631 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000632 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
633 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000634
Evan Chengb6665f62007-06-04 06:47:22 +0000635 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +0000636 bool HasEarlyExit = TrueBBI.FalseBB != NULL;
637 if (HasEarlyExit) {
Evan Cheng8c529382007-06-01 07:41:07 +0000638 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
639 if (TII->ReverseBranchCondition(RevCond))
640 assert(false && "Unable to reverse branch condition!");
641 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
642 }
643
Evan Chengac5f1422007-06-08 09:36:04 +0000644 // Now merge the entry of the triangle with the true block.
645 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
646 MergeBlocks(BBI, TrueBBI);
647
648 // Merge in the 'false' block if the 'false' block has no other
649 // predecessors. Otherwise, add a unconditional branch from to 'false'.
Evan Chenga6b4f432007-05-21 22:22:58 +0000650 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengf5305f92007-06-05 00:07:37 +0000651 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000652 bool IterIfcvt = true;
Evan Chengac5f1422007-06-08 09:36:04 +0000653 bool isFallThrough = isNextBlock(BBI.BB, FalseBBI.BB);
Evan Chengf4769612007-06-07 08:13:00 +0000654 if (!isFallThrough) {
655 // Only merge them if the true block does not fallthrough to the false
656 // block. By not merging them, we make it possible to iteratively
657 // ifcvt the blocks.
Evan Chengac5f1422007-06-08 09:36:04 +0000658 if (!HasEarlyExit && FalseBBI.BB->pred_size() == 1) {
659 MergeBlocks(BBI, FalseBBI);
Evan Chengf4769612007-06-07 08:13:00 +0000660 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +0000661 } else {
Evan Chengac5f1422007-06-08 09:36:04 +0000662 InsertUncondBranch(BBI.BB, FalseBBI.BB, TII);
Evan Chengf4769612007-06-07 08:13:00 +0000663 TrueBBI.hasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +0000664 }
Evan Chengac5f1422007-06-08 09:36:04 +0000665 // Mixed predicated and unpredicated code. This cannot be iteratively
666 // predicated.
667 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000668 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000669
Evan Cheng27af5c42007-06-07 22:31:28 +0000670 // Remove entry to false edge if false block is merged in as well.
Evan Chengac5f1422007-06-08 09:36:04 +0000671 if (FalseBBDead)
Evan Chengf4769612007-06-07 08:13:00 +0000672 BBI.BB->removeSuccessor(FalseBBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000673
Evan Chenga13aa952007-05-23 07:23:16 +0000674 // Update block info. BB can be iteratively if-converted.
Evan Cheng3d6f60e2007-06-06 02:08:52 +0000675 if (IterIfcvt)
676 BBI.Kind = ICReAnalyze;
Evan Cheng7a655472007-06-06 10:16:17 +0000677 else
678 BBI.Kind = ICDead;
Evan Cheng82582102007-05-30 19:49:19 +0000679 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000680 TrueBBI.Kind = ICDead;
Evan Chengf5305f92007-06-05 00:07:37 +0000681 if (FalseBBDead)
682 FalseBBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000683
684 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000685 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000686}
687
Evan Chengd6ddc302007-05-16 21:54:37 +0000688/// IfConvertDiamond - If convert a diamond sub-CFG.
689///
Evan Cheng4e654852007-05-16 02:00:57 +0000690bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chengb6665f62007-06-04 06:47:22 +0000691 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000692 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +0000693
Evan Chenga6b4f432007-05-21 22:22:58 +0000694 SmallVector<MachineInstr*, 2> Dups;
Evan Chengb6665f62007-06-04 06:47:22 +0000695 if (!BBI.TailBB) {
696 // No common merge block. Check if the terminators (e.g. return) are
697 // the same or predicable.
698 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
699 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
700 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
701 if (TT->isIdenticalTo(FT))
702 Dups.push_back(TT); // Will erase these later.
703 else if (!TT->isPredicable() && !FT->isPredicable())
704 return false; // Can't if-convert. Abort!
705 ++TT;
706 ++FT;
Evan Chengcf6cc112007-05-18 18:14:37 +0000707 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000708
Evan Chengb6665f62007-06-04 06:47:22 +0000709 // One of the two pathes have more terminators, make sure they are
710 // all predicable.
711 while (TT != BBI.TrueBB->end()) {
712 if (!TT->isPredicable()) {
713 return false; // Can't if-convert. Abort!
Evan Cheng4e654852007-05-16 02:00:57 +0000714 }
Evan Chengb6665f62007-06-04 06:47:22 +0000715 ++TT;
716 }
717 while (FT != BBI.FalseBB->end()) {
718 if (!FT->isPredicable()) {
719 return false; // Can't if-convert. Abort!
720 }
721 ++FT;
Evan Cheng4e654852007-05-16 02:00:57 +0000722 }
Evan Cheng4e654852007-05-16 02:00:57 +0000723 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000724
Evan Chenga6b4f432007-05-21 22:22:58 +0000725 // Remove the duplicated instructions from the 'true' block.
726 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
727 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000728 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000729 }
730
Evan Chenga6b4f432007-05-21 22:22:58 +0000731 // Merge the 'true' and 'false' blocks by copying the instructions
732 // from the 'false' block to the 'true' block. That is, unless the true
733 // block would clobber the predicate, in that case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +0000734 BBInfo *BBI1 = &TrueBBI;
735 BBInfo *BBI2 = &FalseBBI;
Evan Chengb6665f62007-06-04 06:47:22 +0000736 std::vector<MachineOperand> RevCond(BBI.BrCond);
737 TII->ReverseBranchCondition(RevCond);
Evan Cheng993fc952007-06-05 23:46:14 +0000738 std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
739 std::vector<MachineOperand> *Cond2 = &RevCond;
Evan Cheng993fc952007-06-05 23:46:14 +0000740 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
741 // Either the block fallthrough to another block or it ends with a
742 // return. If it's the former, add a branch to its successor.
743 bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
Evan Chenge7052132007-06-06 00:57:55 +0000744 bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size();
745
746 if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
747 (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
748 NeedBr1 && !NeedBr2)) {
749 std::swap(BBI1, BBI2);
750 std::swap(Cond1, Cond2);
751 std::swap(NeedBr1, NeedBr2);
752 }
Evan Cheng993fc952007-06-05 23:46:14 +0000753
754 // Predicate the 'true' block after removing its branch.
755 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
756 PredicateBlock(*BBI1, *Cond1);
757
758 // Add an early exit branch if needed.
759 if (NeedBr1)
760 TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
761
762 // Predicate the 'false' block.
763 PredicateBlock(*BBI2, *Cond2, true);
764
765 // Add an unconditional branch from 'false' to to 'false' successor if it
766 // will not be the fallthrough block.
Evan Chengd4de6d92007-06-07 02:12:15 +0000767 if (NeedBr2 && !NeedBr1) {
768 // If BBI2 isn't going to be merged in, then the existing fallthrough
769 // or branch is fine.
770 if (!isNextBlock(BBI.BB, *BBI2->BB->succ_begin())) {
771 InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
772 BBI2->hasFallThrough = false;
773 }
774 }
Evan Cheng993fc952007-06-05 23:46:14 +0000775
776 // Keep them as two separate blocks if there is an early exit.
777 if (!NeedBr1)
778 MergeBlocks(*BBI1, *BBI2);
Evan Cheng993fc952007-06-05 23:46:14 +0000779
Evan Chenga6b4f432007-05-21 22:22:58 +0000780 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000781 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000782
Evan Cheng993fc952007-06-05 23:46:14 +0000783 // Merge the combined block into the entry of the diamond.
784 MergeBlocks(BBI, *BBI1);
Evan Chenga6b4f432007-05-21 22:22:58 +0000785
Evan Chenge7052132007-06-06 00:57:55 +0000786 // 'True' and 'false' aren't combined, see if we need to add a unconditional
787 // branch to the 'false' block.
Evan Chengd4de6d92007-06-07 02:12:15 +0000788 if (NeedBr1 && !isNextBlock(BBI.BB, BBI2->BB)) {
789 InsertUncondBranch(BBI.BB, BBI2->BB, TII);
790 BBI1->hasFallThrough = false;
791 }
Evan Chenge7052132007-06-06 00:57:55 +0000792
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000793 // If the if-converted block fallthrough or unconditionally branch into the
794 // tail block, and the tail block does not have other predecessors, then
Evan Chenga6b4f432007-05-21 22:22:58 +0000795 // fold the tail block in as well.
Evan Cheng993fc952007-06-05 23:46:14 +0000796 BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000797 if (BBI.TailBB &&
Evan Chengf15d44c2007-05-31 20:53:33 +0000798 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000799 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000800 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
801 MergeBlocks(*CvtBBI, TailBBI);
802 TailBBI.Kind = ICDead;
803 }
804
Evan Cheng993fc952007-06-05 23:46:14 +0000805 // Update block info.
Evan Cheng7a655472007-06-06 10:16:17 +0000806 BBI.Kind = ICDead;
Evan Chenga6b4f432007-05-21 22:22:58 +0000807 TrueBBI.Kind = ICDead;
808 FalseBBI.Kind = ICDead;
809
810 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +0000811 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000812}
813
Evan Cheng4e654852007-05-16 02:00:57 +0000814/// PredicateBlock - Predicate every instruction in the block with the specified
815/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000816void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000817 std::vector<MachineOperand> &Cond,
818 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000819 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000820 I != E; ++I) {
Evan Chengb6665f62007-06-04 06:47:22 +0000821 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000822 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000823 if (TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +0000824 continue;
Evan Chengb6665f62007-06-04 06:47:22 +0000825 if (!TII->PredicateInstruction(I, Cond)) {
Evan Chengfe57a7e2007-06-01 00:55:26 +0000826 cerr << "Unable to predicate " << *I << "!\n";
Evan Chengd6ddc302007-05-16 21:54:37 +0000827 abort();
828 }
Evan Cheng4e654852007-05-16 02:00:57 +0000829 }
Evan Chenga13aa952007-05-23 07:23:16 +0000830
831 BBI.NonPredSize = 0;
Evan Cheng2acdbcc2007-06-08 19:17:12 +0000832 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
833
Evan Chengb6665f62007-06-04 06:47:22 +0000834 NumIfConvBBs++;
835}
836
Evan Chengd4de6d92007-06-07 02:12:15 +0000837static MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
838 MachineFunction::iterator I = BB;
839 MachineFunction::iterator E = BB->getParent()->end();
840 if (++I == E)
841 return NULL;
842 return I;
Evan Cheng4e654852007-05-16 02:00:57 +0000843}
844
Evan Cheng86cbfea2007-05-18 00:20:58 +0000845/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000846///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000847void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
848 ToBBI.BB->splice(ToBBI.BB->end(),
849 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000850
Evan Chengb6665f62007-06-04 06:47:22 +0000851 // Redirect all branches to FromBB to ToBB.
Evan Chenga1a9f402007-06-05 22:03:53 +0000852 std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
853 FromBBI.BB->pred_end());
Evan Chengd4de6d92007-06-07 02:12:15 +0000854 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
855 MachineBasicBlock *Pred = Preds[i];
856 if (Pred == ToBBI.BB)
857 continue;
858 Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
859 }
860
861 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
862 FromBBI.BB->succ_end());
863 MachineBasicBlock *FallThrough = FromBBI.hasFallThrough
864 ? getNextBlock(FromBBI.BB) : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +0000865
Evan Chengd4de6d92007-06-07 02:12:15 +0000866 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
867 MachineBasicBlock *Succ = Succs[i];
868 if (Succ == FallThrough)
869 continue;
870 FromBBI.BB->removeSuccessor(Succ);
871 if (!ToBBI.BB->isSuccessor(Succ))
872 ToBBI.BB->addSuccessor(Succ);
873 }
874
Evan Chenga13aa952007-05-23 07:23:16 +0000875 ToBBI.NonPredSize += FromBBI.NonPredSize;
876 FromBBI.NonPredSize = 0;
Evan Cheng7a655472007-06-06 10:16:17 +0000877
878 ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
Evan Chengd4de6d92007-06-07 02:12:15 +0000879 ToBBI.hasFallThrough = FromBBI.hasFallThrough;
Evan Cheng2acdbcc2007-06-08 19:17:12 +0000880
881 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
882 std::back_inserter(ToBBI.Predicate));
883 FromBBI.Predicate.clear();
Evan Cheng4e654852007-05-16 02:00:57 +0000884}