blob: 9efceb08e56b530d0875aff22e443c4e32fe1362 [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"
22#include "llvm/Support/Debug.h"
Evan Cheng36489bb2007-05-18 19:26:33 +000023#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng4e654852007-05-16 02:00:57 +000024#include "llvm/ADT/Statistic.h"
25using namespace llvm;
26
27STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
28
29namespace {
30 class IfConverter : public MachineFunctionPass {
31 enum BBICKind {
Evan Chenga13aa952007-05-23 07:23:16 +000032 ICNotAnalyzed, // BB has not been analyzed.
33 ICReAnalyze, // BB must be re-analyzed.
Evan Cheng4e654852007-05-16 02:00:57 +000034 ICNotClassfied, // BB data valid, but not classified.
Evan Chenga6b4f432007-05-21 22:22:58 +000035 ICEarlyExit, // BB is entry of an early-exit sub-CFG.
Evan Chengb5a06902007-06-01 20:29:21 +000036 ICEarlyExitFalse,// Same as ICEarlyExit, but on the false path.
Evan Chenga6b4f432007-05-21 22:22:58 +000037 ICTriangle, // BB is entry of a triangle sub-CFG.
38 ICDiamond, // BB is entry of a diamond sub-CFG.
39 ICChild, // BB is part of the sub-CFG that'll be predicated.
40 ICDead // BB has been converted and merged, it's now dead.
Evan Cheng4e654852007-05-16 02:00:57 +000041 };
42
43 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
44 /// if-conversion feasibility analysis. This includes results from
45 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000046 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000047 /// diamond shape), its size, whether it's predicable, and whether any
48 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000049 ///
50 /// Kind - Type of block. See BBICKind.
51 /// NonPredSize - Number of non-predicated instructions.
52 /// isPredicable - Is it predicable. (FIXME: Remove.)
53 /// hasEarlyExit - Ends with a return, indirect jump or br to jumptable.
54 /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
55 /// the predicate (e.g. has cmp, call, etc.)
56 /// BB - Corresponding MachineBasicBlock.
57 /// TrueBB / FalseBB- See AnalyzeBranch().
58 /// BrCond - Conditions for end of block conditional branches.
59 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +000060 struct BBInfo {
61 BBICKind Kind;
Evan Chenga13aa952007-05-23 07:23:16 +000062 unsigned NonPredSize;
Evan Chengcf6cc112007-05-18 18:14:37 +000063 bool isPredicable;
Evan Chenga6b4f432007-05-21 22:22:58 +000064 bool hasEarlyExit;
Evan Chenga13aa952007-05-23 07:23:16 +000065 bool ModifyPredicate;
Evan Cheng86cbfea2007-05-18 00:20:58 +000066 MachineBasicBlock *BB;
67 MachineBasicBlock *TrueBB;
68 MachineBasicBlock *FalseBB;
69 MachineBasicBlock *TailBB;
Evan Chenga13aa952007-05-23 07:23:16 +000070 std::vector<MachineOperand> BrCond;
71 std::vector<MachineOperand> Predicate;
72 BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0), isPredicable(false),
73 hasEarlyExit(false), ModifyPredicate(false),
Evan Chenga6b4f432007-05-21 22:22:58 +000074 BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
Evan Cheng4e654852007-05-16 02:00:57 +000075 };
76
Evan Cheng82582102007-05-30 19:49:19 +000077 /// Roots - Basic blocks that do not have successors. These are the starting
78 /// points of Graph traversal.
79 std::vector<MachineBasicBlock*> Roots;
80
Evan Cheng4e654852007-05-16 02:00:57 +000081 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
82 /// basic block number.
83 std::vector<BBInfo> BBAnalysis;
84
Evan Cheng86cbfea2007-05-18 00:20:58 +000085 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +000086 const TargetInstrInfo *TII;
87 bool MadeChange;
88 public:
89 static char ID;
90 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
91
92 virtual bool runOnMachineFunction(MachineFunction &MF);
93 virtual const char *getPassName() const { return "If converter"; }
94
95 private:
Evan Chengcf6cc112007-05-18 18:14:37 +000096 void StructuralAnalysis(MachineBasicBlock *BB);
Evan Chenga13aa952007-05-23 07:23:16 +000097 void FeasibilityAnalysis(BBInfo &BBI,
98 std::vector<MachineOperand> &Cond);
Evan Cheng82582102007-05-30 19:49:19 +000099 bool AttemptRestructuring(BBInfo &BBI);
100 bool AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000101 std::vector<BBInfo*> &Candidates);
Evan Cheng82582102007-05-30 19:49:19 +0000102 void ReTryPreds(MachineBasicBlock *BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000103 bool IfConvertEarlyExit(BBInfo &BBI);
Evan Cheng4e654852007-05-16 02:00:57 +0000104 bool IfConvertTriangle(BBInfo &BBI);
Evan Chengcf6cc112007-05-18 18:14:37 +0000105 bool IfConvertDiamond(BBInfo &BBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000106 void PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000107 std::vector<MachineOperand> &Cond,
108 bool IgnoreTerm = false);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000109 void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
Evan Cheng5f702182007-06-01 00:12:12 +0000110
111 // IfcvtCandidateCmp - Used to sort if-conversion candidates.
112 static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
113 // Favor diamond over triangle, etc.
114 return (unsigned)C1->Kind < (unsigned)C2->Kind;
115 }
Evan Cheng4e654852007-05-16 02:00:57 +0000116 };
117 char IfConverter::ID = 0;
118}
119
120FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
121
122bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000123 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000124 TII = MF.getTarget().getInstrInfo();
125 if (!TII) return false;
126
Evan Cheng5f702182007-06-01 00:12:12 +0000127 DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
128
Evan Cheng4e654852007-05-16 02:00:57 +0000129 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000130 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000131
Evan Cheng82582102007-05-30 19:49:19 +0000132 // Look for root nodes, i.e. blocks without successors.
133 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
134 if (I->succ_size() == 0)
135 Roots.push_back(I);
136
Evan Cheng7f8ff8a2007-05-18 19:32:08 +0000137 std::vector<BBInfo*> Candidates;
Evan Cheng47d25022007-05-18 01:55:58 +0000138 MadeChange = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000139 while (true) {
140 bool Change = false;
141
142 // Do an intial analysis for each basic block and finding all the potential
143 // candidates to perform if-convesion.
Evan Cheng82582102007-05-30 19:49:19 +0000144 Change |= AnalyzeBlocks(MF, Candidates);
Evan Chenga13aa952007-05-23 07:23:16 +0000145 while (!Candidates.empty()) {
146 BBInfo &BBI = *Candidates.back();
147 Candidates.pop_back();
148 switch (BBI.Kind) {
149 default: assert(false && "Unexpected!");
150 break;
Evan Cheng5f702182007-06-01 00:12:12 +0000151 case ICReAnalyze:
152 // One or more of 'childrean' have been modified, abort!
153 break;
Evan Chenga13aa952007-05-23 07:23:16 +0000154 case ICEarlyExit:
Evan Chengb5a06902007-06-01 20:29:21 +0000155 case ICEarlyExitFalse:
Evan Cheng5f702182007-06-01 00:12:12 +0000156 DOUT << "Ifcvt (Early exit): BB#" << BBI.BB->getNumber() << "\n";
Evan Chenga13aa952007-05-23 07:23:16 +0000157 Change |= IfConvertEarlyExit(BBI);
158 break;
159 case ICTriangle:
Evan Cheng5f702182007-06-01 00:12:12 +0000160 DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << "\n";
Evan Chenga13aa952007-05-23 07:23:16 +0000161 Change |= IfConvertTriangle(BBI);
162 break;
163 case ICDiamond:
Evan Cheng5f702182007-06-01 00:12:12 +0000164 DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << "\n";
Evan Chenga13aa952007-05-23 07:23:16 +0000165 Change |= IfConvertDiamond(BBI);
166 break;
167 }
Evan Cheng4e654852007-05-16 02:00:57 +0000168 }
Evan Chenga13aa952007-05-23 07:23:16 +0000169
170 MadeChange |= Change;
171 if (!Change)
172 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000173 }
Evan Cheng47d25022007-05-18 01:55:58 +0000174
Evan Cheng82582102007-05-30 19:49:19 +0000175 Roots.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000176 BBAnalysis.clear();
177
Evan Cheng4e654852007-05-16 02:00:57 +0000178 return MadeChange;
179}
180
181static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000182 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000183 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
184 E = BB->succ_end(); SI != E; ++SI) {
185 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000186 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000187 return SuccBB;
188 }
189 return NULL;
190}
191
Evan Chengcf6cc112007-05-18 18:14:37 +0000192/// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
193/// the specified block. Record its successors and whether it looks like an
194/// if-conversion candidate.
195void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000196 BBInfo &BBI = BBAnalysis[BB->getNumber()];
197
Evan Chenga13aa952007-05-23 07:23:16 +0000198 if (BBI.Kind != ICReAnalyze) {
199 if (BBI.Kind != ICNotAnalyzed)
200 return; // Already analyzed.
201 BBI.BB = BB;
202 BBI.NonPredSize = std::distance(BB->begin(), BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000203 }
Evan Cheng86cbfea2007-05-18 00:20:58 +0000204
Evan Cheng4bec8ae2007-05-25 00:59:01 +0000205 // Look for 'root' of a simple (non-nested) triangle or diamond.
206 BBI.Kind = ICNotClassfied;
207 bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB,
208 BBI.BrCond);
209 // Does it end with a return, indirect jump, or jumptable branch?
210 BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
211 if (!CanAnalyze || !BBI.TrueBB || BBI.BrCond.size() == 0)
212 return;
213
Evan Cheng86cbfea2007-05-18 00:20:58 +0000214 // Not a candidate if 'true' block is going to be if-converted.
Evan Chengcf6cc112007-05-18 18:14:37 +0000215 StructuralAnalysis(BBI.TrueBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000216 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengd6ddc302007-05-16 21:54:37 +0000217
Evan Cheng47d25022007-05-18 01:55:58 +0000218 // TODO: Only handle very simple cases for now.
Evan Chenga13aa952007-05-23 07:23:16 +0000219 if (TrueBBI.FalseBB || TrueBBI.BrCond.size())
Evan Cheng47d25022007-05-18 01:55:58 +0000220 return;
221
Evan Chengd6ddc302007-05-16 21:54:37 +0000222 // No false branch. This BB must end with a conditional branch and a
223 // fallthrough.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000224 if (!BBI.FalseBB)
225 BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
226 assert(BBI.FalseBB && "Expected to find the fallthrough block!");
Evan Chengc5d05ef2007-05-16 05:11:10 +0000227
Evan Cheng86cbfea2007-05-18 00:20:58 +0000228 // Not a candidate if 'false' block is going to be if-converted.
Evan Chengcf6cc112007-05-18 18:14:37 +0000229 StructuralAnalysis(BBI.FalseBB);
Evan Cheng86cbfea2007-05-18 00:20:58 +0000230 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng4e654852007-05-16 02:00:57 +0000231
232 // TODO: Only handle very simple cases for now.
Evan Chenga13aa952007-05-23 07:23:16 +0000233 if (FalseBBI.FalseBB || FalseBBI.BrCond.size())
Evan Cheng4e654852007-05-16 02:00:57 +0000234 return;
235
Evan Chenga6b4f432007-05-21 22:22:58 +0000236 unsigned TrueNumPreds = BBI.TrueBB->pred_size();
237 unsigned FalseNumPreds = BBI.FalseBB->pred_size();
238 if ((TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
239 !(FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
240 BBI.Kind = ICEarlyExit;
241 TrueBBI.Kind = ICChild;
242 } else if (!(TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
243 (FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
Evan Chengb5a06902007-06-01 20:29:21 +0000244 BBI.Kind = ICEarlyExitFalse;
Evan Chenga6b4f432007-05-21 22:22:58 +0000245 FalseBBI.Kind = ICChild;
246 } else if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000247 // Triangle:
248 // EBB
249 // | \_
250 // | |
251 // | TBB
252 // | /
253 // FBB
Evan Chenga6b4f432007-05-21 22:22:58 +0000254 BBI.Kind = ICTriangle;
255 TrueBBI.Kind = FalseBBI.Kind = ICChild;
256 } else if (TrueBBI.TrueBB == FalseBBI.TrueBB &&
257 TrueNumPreds <= 1 && FalseNumPreds <= 1) {
Evan Cheng4e654852007-05-16 02:00:57 +0000258 // Diamond:
259 // EBB
260 // / \_
261 // | |
262 // TBB FBB
263 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000264 // TailBB
Evan Cheng4e654852007-05-16 02:00:57 +0000265 // Note MBB can be empty in case both TBB and FBB are return blocks.
Evan Chenga6b4f432007-05-21 22:22:58 +0000266 BBI.Kind = ICDiamond;
267 TrueBBI.Kind = FalseBBI.Kind = ICChild;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000268 BBI.TailBB = TrueBBI.TrueBB;
Evan Cheng4e654852007-05-16 02:00:57 +0000269 }
270 return;
271}
272
Evan Chengcf6cc112007-05-18 18:14:37 +0000273/// FeasibilityAnalysis - Determine if the block is predicable. In most
274/// cases, that means all the instructions in the block has M_PREDICABLE flag.
275/// Also checks if the block contains any instruction which can clobber a
276/// predicate (e.g. condition code register). If so, the block is not
277/// predicable unless it's the last instruction. Note, this function assumes
278/// all the terminator instructions can be converted or deleted so it ignore
279/// them.
Evan Chenga13aa952007-05-23 07:23:16 +0000280void IfConverter::FeasibilityAnalysis(BBInfo &BBI,
281 std::vector<MachineOperand> &Cond) {
282 if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
Evan Chengcf6cc112007-05-18 18:14:37 +0000283 return;
284
285 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
286 I != E; ++I) {
287 // TODO: check if instruction clobbers predicate.
Evan Chengcf6cc112007-05-18 18:14:37 +0000288 if (!I->isPredicable())
289 return;
290 }
291
Evan Chenga13aa952007-05-23 07:23:16 +0000292 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
293 return;
294
Evan Chengcf6cc112007-05-18 18:14:37 +0000295 BBI.isPredicable = true;
296}
297
Evan Cheng82582102007-05-30 19:49:19 +0000298/// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
299/// expose more if-conversion opportunities. e.g.
300///
301/// cmp
302/// b le BB1
303/// / \____
304/// / |
305/// cmp |
306/// b eq BB1 |
307/// / \____ |
308/// / \ |
309/// BB1
310/// ==>
311///
312/// cmp
313/// b eq BB1
314/// / \____
315/// / |
316/// cmp |
317/// b le BB1 |
318/// / \____ |
319/// / \ |
320/// BB1
321bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
322 return false;
323}
324
325/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
326/// candidates. It returns true if any CFG restructuring is done to expose more
327/// if-conversion opportunities.
328bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenga13aa952007-05-23 07:23:16 +0000329 std::vector<BBInfo*> &Candidates) {
Evan Cheng82582102007-05-30 19:49:19 +0000330 bool Change = false;
Evan Cheng36489bb2007-05-18 19:26:33 +0000331 std::set<MachineBasicBlock*> Visited;
Evan Cheng82582102007-05-30 19:49:19 +0000332 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
333 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
334 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
335 MachineBasicBlock *BB = *I;
336 StructuralAnalysis(BB);
337 BBInfo &BBI = BBAnalysis[BB->getNumber()];
338 switch (BBI.Kind) {
339 case ICEarlyExit:
Evan Chengb5a06902007-06-01 20:29:21 +0000340 case ICEarlyExitFalse:
Evan Cheng82582102007-05-30 19:49:19 +0000341 case ICTriangle:
342 case ICDiamond:
343 Candidates.push_back(&BBI);
344 break;
345 default:
346 Change |= AttemptRestructuring(BBI);
347 break;
348 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000349 }
Evan Cheng4e654852007-05-16 02:00:57 +0000350 }
Evan Cheng82582102007-05-30 19:49:19 +0000351
Evan Cheng5f702182007-06-01 00:12:12 +0000352 // Sort to favor more complex ifcvt scheme.
353 std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
354
Evan Cheng82582102007-05-30 19:49:19 +0000355 return Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000356}
357
Evan Cheng86cbfea2007-05-18 00:20:58 +0000358/// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
359///
360static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
361 std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
362 FromBB->pred_end());
363 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
364 MachineBasicBlock *Pred = Preds[i];
365 Pred->removeSuccessor(FromBB);
366 if (!Pred->isSuccessor(ToBB))
367 Pred->addSuccessor(ToBB);
368 }
369}
370
371/// TransferSuccs - Transfer all the successors of FromBB to ToBB.
372///
373static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
374 std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
375 FromBB->succ_end());
376 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
377 MachineBasicBlock *Succ = Succs[i];
378 FromBB->removeSuccessor(Succ);
379 if (!ToBB->isSuccessor(Succ))
380 ToBB->addSuccessor(Succ);
381 }
382}
383
Evan Chenga6b4f432007-05-21 22:22:58 +0000384/// isNextBlock - Returns true if ToBB the next basic block after BB.
385///
386static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
387 MachineFunction::iterator Fallthrough = BB;
388 return MachineFunction::iterator(ToBB) == ++Fallthrough;
389}
390
Evan Cheng82582102007-05-30 19:49:19 +0000391/// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
Evan Chenga13aa952007-05-23 07:23:16 +0000392/// to determine if it can be if-converted.
Evan Cheng82582102007-05-30 19:49:19 +0000393void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000394 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
395 E = BB->pred_end(); PI != E; ++PI) {
396 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
397 PBBI.Kind = ICReAnalyze;
398 }
399}
400
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000401/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
402///
403static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
404 const TargetInstrInfo *TII) {
405 std::vector<MachineOperand> NoCond;
406 TII->InsertBranch(*BB, ToBB, NULL, NoCond);
407}
408
Evan Chenga6b4f432007-05-21 22:22:58 +0000409/// IfConvertEarlyExit - If convert a early exit sub-CFG.
410///
411bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
Evan Chengb5a06902007-06-01 20:29:21 +0000412 bool ReverseCond = BBI.Kind == ICEarlyExitFalse;
413
Evan Chenga13aa952007-05-23 07:23:16 +0000414 BBI.Kind = ICNotClassfied;
415
Evan Chenga6b4f432007-05-21 22:22:58 +0000416 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
417 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
418 BBInfo *CvtBBI = &TrueBBI;
419 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000420
Evan Chenga13aa952007-05-23 07:23:16 +0000421 std::vector<MachineOperand> NewCond(BBI.BrCond);
Evan Chengb5a06902007-06-01 20:29:21 +0000422 if (ReverseCond) {
423 std::swap(CvtBBI, NextBBI);
Evan Chenga6b4f432007-05-21 22:22:58 +0000424 TII->ReverseBranchCondition(NewCond);
Evan Chengb5a06902007-06-01 20:29:21 +0000425 }
Evan Chenga13aa952007-05-23 07:23:16 +0000426 FeasibilityAnalysis(*CvtBBI, NewCond);
427 if (!CvtBBI->isPredicable)
428 return false;
429
430 PredicateBlock(*CvtBBI, NewCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000431
432 // Merge converted block into entry block. Also convert the end of the
433 // block conditional branch (to the non-converted block) into an
434 // unconditional one.
Evan Chenga13aa952007-05-23 07:23:16 +0000435 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000436 MergeBlocks(BBI, *CvtBBI);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000437 if (!isNextBlock(BBI.BB, NextBBI->BB))
438 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Chenga13aa952007-05-23 07:23:16 +0000439 std::copy(NewCond.begin(), NewCond.end(), std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000440
Evan Chenga13aa952007-05-23 07:23:16 +0000441 // Update block info. BB can be iteratively if-converted.
442 BBI.Kind = ICNotAnalyzed;
443 BBI.TrueBB = BBI.FalseBB = NULL;
444 BBI.BrCond.clear();
445 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Cheng82582102007-05-30 19:49:19 +0000446 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000447 CvtBBI->Kind = ICDead;
448
449 // FIXME: Must maintain LiveIns.
450 NumIfConvBBs++;
451 return true;
452}
453
Evan Chengd6ddc302007-05-16 21:54:37 +0000454/// IfConvertTriangle - If convert a triangle sub-CFG.
455///
Evan Cheng4e654852007-05-16 02:00:57 +0000456bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000457 BBI.Kind = ICNotClassfied;
Evan Chengcf6cc112007-05-18 18:14:37 +0000458
Evan Chenga13aa952007-05-23 07:23:16 +0000459 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
460 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
461 if (!TrueBBI.isPredicable)
Evan Chenga6b4f432007-05-21 22:22:58 +0000462 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000463
Evan Cheng8c529382007-06-01 07:41:07 +0000464 // FIXME: Consider duplicating if BB is small.
465 if (BBI.TrueBB->pred_size() > 1)
466 return false;
467
Evan Chenga6b4f432007-05-21 22:22:58 +0000468 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000469 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
470 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000471
Evan Cheng8c529382007-06-01 07:41:07 +0000472 // If 'true' block has a 'false' successor, add a early exit branch to it.
473 if (TrueBBI.FalseBB) {
474 std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
475 if (TII->ReverseBranchCondition(RevCond))
476 assert(false && "Unable to reverse branch condition!");
477 TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
478 }
479
480 // Join the 'true' and 'false' blocks if the 'false' block has no other
481 // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
Evan Chenga6b4f432007-05-21 22:22:58 +0000482 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Cheng8c529382007-06-01 07:41:07 +0000483 if (FalseBBI.BB->pred_size() == 2)
484 MergeBlocks(TrueBBI, FalseBBI);
485 else
486 InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000487
488 // Now merge the entry of the triangle with the true block.
Evan Chenga13aa952007-05-23 07:23:16 +0000489 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000490 MergeBlocks(BBI, TrueBBI);
Evan Chenga13aa952007-05-23 07:23:16 +0000491 std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
492 std::back_inserter(BBI.Predicate));
Evan Chenga6b4f432007-05-21 22:22:58 +0000493
Evan Chenga13aa952007-05-23 07:23:16 +0000494 // Update block info. BB can be iteratively if-converted.
495 BBI.Kind = ICNotClassfied;
496 BBI.TrueBB = BBI.FalseBB = NULL;
497 BBI.BrCond.clear();
498 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Cheng82582102007-05-30 19:49:19 +0000499 ReTryPreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000500 TrueBBI.Kind = ICDead;
501
502 // FIXME: Must maintain LiveIns.
503 NumIfConvBBs++;
504 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000505}
506
Evan Chengd6ddc302007-05-16 21:54:37 +0000507/// IfConvertDiamond - If convert a diamond sub-CFG.
508///
Evan Cheng4e654852007-05-16 02:00:57 +0000509bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chenga13aa952007-05-23 07:23:16 +0000510 BBI.Kind = ICNotClassfied;
511
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000512 bool TrueNeedBr;
513 bool FalseNeedBr;
Evan Chengcf6cc112007-05-18 18:14:37 +0000514 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
515 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenga13aa952007-05-23 07:23:16 +0000516 FeasibilityAnalysis(TrueBBI, BBI.BrCond);
517 std::vector<MachineOperand> RevCond(BBI.BrCond);
518 TII->ReverseBranchCondition(RevCond);
519 FeasibilityAnalysis(FalseBBI, RevCond);
Evan Chengcf6cc112007-05-18 18:14:37 +0000520
Evan Chenga6b4f432007-05-21 22:22:58 +0000521 SmallVector<MachineInstr*, 2> Dups;
522 bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
523 if (Proceed) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000524 // Check the 'true' and 'false' blocks if either isn't ended with a branch.
525 // Either the block fallthrough to another block or it ends with a
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000526 // return. If it's the former, add a branch to its successor.
527 TrueNeedBr = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
528 FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
529 if (TrueNeedBr && TrueBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000530 TrueBBI.isPredicable = false;
531 Proceed = false;
532 }
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000533 if (FalseNeedBr && FalseBBI.ModifyPredicate) {
Evan Chengcf6cc112007-05-18 18:14:37 +0000534 FalseBBI.isPredicable = false;
535 Proceed = false;
536 }
Evan Chengcf6cc112007-05-18 18:14:37 +0000537
Evan Chenga6b4f432007-05-21 22:22:58 +0000538 if (Proceed) {
539 if (!BBI.TailBB) {
540 // No common merge block. Check if the terminators (e.g. return) are
541 // the same or predicable.
542 MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
543 MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
544 while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
545 if (TT->isIdenticalTo(FT))
546 Dups.push_back(TT); // Will erase these later.
547 else if (!TT->isPredicable() && !FT->isPredicable()) {
548 Proceed = false;
549 break; // Can't if-convert. Abort!
550 }
551 ++TT;
552 ++FT;
553 }
554
555 // One of the two pathes have more terminators, make sure they are
556 // all predicable.
557 while (Proceed && TT != BBI.TrueBB->end())
558 if (!TT->isPredicable()) {
559 Proceed = false;
560 break; // Can't if-convert. Abort!
561 }
562 while (Proceed && FT != BBI.FalseBB->end())
563 if (!FT->isPredicable()) {
564 Proceed = false;
565 break; // Can't if-convert. Abort!
566 }
Evan Cheng4e654852007-05-16 02:00:57 +0000567 }
Evan Cheng4e654852007-05-16 02:00:57 +0000568 }
Evan Cheng4e654852007-05-16 02:00:57 +0000569 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000570
Evan Chenga13aa952007-05-23 07:23:16 +0000571 if (!Proceed)
Evan Chenga6b4f432007-05-21 22:22:58 +0000572 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +0000573
574 // Remove the duplicated instructions from the 'true' block.
575 for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
576 Dups[i]->eraseFromParent();
Evan Chenga13aa952007-05-23 07:23:16 +0000577 --TrueBBI.NonPredSize;
Evan Chenga6b4f432007-05-21 22:22:58 +0000578 }
579
580 // Predicate the 'true' block after removing its branch.
Evan Chenga13aa952007-05-23 07:23:16 +0000581 TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
582 PredicateBlock(TrueBBI, BBI.BrCond);
Evan Chenga6b4f432007-05-21 22:22:58 +0000583
Evan Chenga6b4f432007-05-21 22:22:58 +0000584 // Predicate the 'false' block.
Evan Chenga13aa952007-05-23 07:23:16 +0000585 PredicateBlock(FalseBBI, RevCond, true);
Evan Chenga6b4f432007-05-21 22:22:58 +0000586
Evan Chenga6b4f432007-05-21 22:22:58 +0000587 // Merge the 'true' and 'false' blocks by copying the instructions
588 // from the 'false' block to the 'true' block. That is, unless the true
589 // block would clobber the predicate, in that case, do the opposite.
590 BBInfo *CvtBBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000591 if (!TrueBBI.ModifyPredicate) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000592 // Add a conditional branch from 'true' to 'true' successor if needed.
593 if (TrueNeedBr)
594 TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
595 BBI.BrCond);
596 // Add an unconditional branch from 'false' to to 'false' successor if it
597 // will not be the fallthrough block.
598 if (FalseNeedBr &&
599 !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
600 InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000601 MergeBlocks(TrueBBI, FalseBBI);
602 CvtBBI = &TrueBBI;
603 } else {
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000604 // Add a conditional branch from 'false' to 'false' successor if needed.
605 if (FalseNeedBr)
606 TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
607 RevCond);
608 // Add an unconditional branch from 'true' to to 'true' successor if it
609 // will not be the fallthrough block.
610 if (TrueNeedBr &&
611 !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
612 InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000613 MergeBlocks(FalseBBI, TrueBBI);
614 CvtBBI = &FalseBBI;
615 }
616
617 // Remove the conditional branch from entry to the blocks.
Evan Chenga13aa952007-05-23 07:23:16 +0000618 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000619
Evan Chenga13aa952007-05-23 07:23:16 +0000620 bool OkToIfcvt = true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000621 // Merge the combined block into the entry of the diamond if the entry
622 // block is its only predecessor. Otherwise, insert an unconditional
623 // branch from entry to the if-converted block.
624 if (CvtBBI->BB->pred_size() == 1) {
Evan Chenga6b4f432007-05-21 22:22:58 +0000625 MergeBlocks(BBI, *CvtBBI);
626 CvtBBI = &BBI;
Evan Chenga13aa952007-05-23 07:23:16 +0000627 OkToIfcvt = false;
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000628 } else
629 InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
Evan Chenga6b4f432007-05-21 22:22:58 +0000630
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000631 // If the if-converted block fallthrough or unconditionally branch into the
632 // tail block, and the tail block does not have other predecessors, then
Evan Chenga6b4f432007-05-21 22:22:58 +0000633 // fold the tail block in as well.
Evan Cheng58fbb9f2007-05-29 23:37:20 +0000634 if (BBI.TailBB &&
Evan Chengf15d44c2007-05-31 20:53:33 +0000635 BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
Evan Chenga13aa952007-05-23 07:23:16 +0000636 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Chenga6b4f432007-05-21 22:22:58 +0000637 BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
638 MergeBlocks(*CvtBBI, TailBBI);
639 TailBBI.Kind = ICDead;
640 }
641
Evan Chenga13aa952007-05-23 07:23:16 +0000642 // Update block info. BB may be iteratively if-converted.
643 if (OkToIfcvt) {
644 BBI.Kind = ICNotClassfied;
645 BBI.TrueBB = BBI.FalseBB = NULL;
646 BBI.BrCond.clear();
647 TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Evan Cheng82582102007-05-30 19:49:19 +0000648 ReTryPreds(BBI.BB);
Evan Chenga13aa952007-05-23 07:23:16 +0000649 }
Evan Chenga6b4f432007-05-21 22:22:58 +0000650 TrueBBI.Kind = ICDead;
651 FalseBBI.Kind = ICDead;
652
653 // FIXME: Must maintain LiveIns.
654 NumIfConvBBs += 2;
655 return true;
Evan Cheng4e654852007-05-16 02:00:57 +0000656}
657
Evan Cheng4e654852007-05-16 02:00:57 +0000658/// PredicateBlock - Predicate every instruction in the block with the specified
659/// condition. If IgnoreTerm is true, skip over all terminator instructions.
Evan Chenga13aa952007-05-23 07:23:16 +0000660void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng4e654852007-05-16 02:00:57 +0000661 std::vector<MachineOperand> &Cond,
662 bool IgnoreTerm) {
Evan Chenga13aa952007-05-23 07:23:16 +0000663 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
Evan Cheng4e654852007-05-16 02:00:57 +0000664 I != E; ++I) {
Evan Chenga13aa952007-05-23 07:23:16 +0000665 MachineInstr *MI = I;
666 if (IgnoreTerm && TII->isTerminatorInstr(MI->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000667 continue;
Evan Chenga13aa952007-05-23 07:23:16 +0000668 if (TII->isPredicated(MI))
669 continue;
670 if (!TII->PredicateInstruction(MI, Cond)) {
Evan Chengfe57a7e2007-06-01 00:55:26 +0000671 cerr << "Unable to predicate " << *I << "!\n";
Evan Chengd6ddc302007-05-16 21:54:37 +0000672 abort();
673 }
Evan Cheng4e654852007-05-16 02:00:57 +0000674 }
Evan Chenga13aa952007-05-23 07:23:16 +0000675
676 BBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000677}
678
Evan Cheng86cbfea2007-05-18 00:20:58 +0000679/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Evan Cheng4e654852007-05-16 02:00:57 +0000680///
Evan Cheng86cbfea2007-05-18 00:20:58 +0000681void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
682 ToBBI.BB->splice(ToBBI.BB->end(),
683 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +0000684
685 // If FromBBI is previously a successor, remove it from ToBBI's successor
686 // list and update its TrueBB / FalseBB field if needed.
687 if (ToBBI.BB->isSuccessor(FromBBI.BB))
688 ToBBI.BB->removeSuccessor(FromBBI.BB);
689
690 // Transfer preds / succs and update size.
Evan Cheng86cbfea2007-05-18 00:20:58 +0000691 TransferPreds(ToBBI.BB, FromBBI.BB);
692 TransferSuccs(ToBBI.BB, FromBBI.BB);
Evan Chenga13aa952007-05-23 07:23:16 +0000693 ToBBI.NonPredSize += FromBBI.NonPredSize;
694 FromBBI.NonPredSize = 0;
Evan Cheng4e654852007-05-16 02:00:57 +0000695}