blob: 37c729d341cd42ba12e9d5288f5632b044f5bae3 [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
14#define DEBUG_TYPE "ifconversion"
15#include "llvm/CodeGen/Passes.h"
16#include "llvm/CodeGen/MachineModuleInfo.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/Target/TargetInstrInfo.h"
19#include "llvm/Target/TargetMachine.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/ADT/Statistic.h"
22using namespace llvm;
23
24STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
25
26namespace {
27 class IfConverter : public MachineFunctionPass {
28 enum BBICKind {
29 ICInvalid, // BB data invalid.
30 ICNotClassfied, // BB data valid, but not classified.
31 ICTriangle, // BB is part of a triangle sub-CFG.
32 ICDiamond, // BB is part of a diamond sub-CFG.
33 ICTriangleEntry, // BB is entry of a triangle sub-CFG.
34 ICDiamondEntry // BB is entry of a diamond sub-CFG.
35 };
36
37 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
38 /// if-conversion feasibility analysis. This includes results from
39 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
40 /// classification, and common merge block of its successors (if it's a
41 /// diamond shape).
42 struct BBInfo {
43 BBICKind Kind;
44 MachineBasicBlock *EBB;
45 MachineBasicBlock *TBB;
46 MachineBasicBlock *FBB;
47 MachineBasicBlock *CMBB;
48 std::vector<MachineOperand> Cond;
49 BBInfo() : Kind(ICInvalid), EBB(0), TBB(0), FBB(0), CMBB(0) {}
50 };
51
52 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
53 /// basic block number.
54 std::vector<BBInfo> BBAnalysis;
55
56 const TargetInstrInfo *TII;
57 bool MadeChange;
58 public:
59 static char ID;
60 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
61
62 virtual bool runOnMachineFunction(MachineFunction &MF);
63 virtual const char *getPassName() const { return "If converter"; }
64
65 private:
66 void AnalyzeBlock(MachineBasicBlock *BB);
67 void InitialFunctionAnalysis(MachineFunction &MF,
68 std::vector<int> &Candidates);
69 bool IfConvertDiamond(BBInfo &BBI);
70 bool IfConvertTriangle(BBInfo &BBI);
Evan Chengd6ddc302007-05-16 21:54:37 +000071 bool isBlockPredicable(MachineBasicBlock *BB) const;
Evan Cheng4e654852007-05-16 02:00:57 +000072 void PredicateBlock(MachineBasicBlock *BB,
73 std::vector<MachineOperand> &Cond,
74 bool IgnoreTerm = false);
75 void MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB);
76 };
77 char IfConverter::ID = 0;
78}
79
80FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
81
82bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
83 TII = MF.getTarget().getInstrInfo();
84 if (!TII) return false;
85
86 MadeChange = false;
87
88 MF.RenumberBlocks();
89 unsigned NumBBs = MF.getNumBlockIDs();
90 BBAnalysis.resize(NumBBs);
91
92 std::vector<int> Candidates;
93 // Do an intial analysis for each basic block and finding all the potential
94 // candidates to perform if-convesion.
95 InitialFunctionAnalysis(MF, Candidates);
96
97 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
98 BBInfo &BBI = BBAnalysis[i];
99 switch (BBI.Kind) {
100 default: assert(false && "Unexpected!");
101 break;
102 case ICTriangleEntry:
103 MadeChange |= IfConvertTriangle(BBI);
104 break;
105 case ICDiamondEntry:
106 MadeChange |= IfConvertDiamond(BBI);
107 break;
108 }
109 }
110 return MadeChange;
111}
112
113static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
114 MachineBasicBlock *TBB) {
115 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
116 E = BB->succ_end(); SI != E; ++SI) {
117 MachineBasicBlock *SuccBB = *SI;
118 if (SuccBB != TBB)
119 return SuccBB;
120 }
121 return NULL;
122}
123
124void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
125 BBInfo &BBI = BBAnalysis[BB->getNumber()];
126
127 if (BBI.Kind != ICInvalid)
128 return; // Always analyzed.
129 BBI.EBB = BB;
130
131 // Look for 'root' of a simple (non-nested) triangle or diamond.
132 BBI.Kind = ICNotClassfied;
133 if (TII->AnalyzeBranch(*BB, BBI.TBB, BBI.FBB, BBI.Cond)
134 || !BBI.TBB || BBI.Cond.size() == 0)
135 return;
Evan Chengd6ddc302007-05-16 21:54:37 +0000136 // Can't do it if 'true' block is already marked as to be if-converted.
Evan Cheng4e654852007-05-16 02:00:57 +0000137 AnalyzeBlock(BBI.TBB);
138 BBInfo &TBBI = BBAnalysis[BBI.TBB->getNumber()];
139 if (TBBI.Kind != ICNotClassfied)
140 return;
Evan Chengd6ddc302007-05-16 21:54:37 +0000141
142 // No false branch. This BB must end with a conditional branch and a
143 // fallthrough.
Evan Cheng4e654852007-05-16 02:00:57 +0000144 if (!BBI.FBB)
145 BBI.FBB = findFalseBlock(BB, BBI.TBB);
Evan Chengc5d05ef2007-05-16 05:11:10 +0000146 assert(BBI.FBB && "Expected to find the fallthrough block!");
147
Evan Chengd6ddc302007-05-16 21:54:37 +0000148 // Can't do it if 'false' block is already marked as to be if-converted.
Evan Cheng4e654852007-05-16 02:00:57 +0000149 AnalyzeBlock(BBI.FBB);
150 BBInfo &FBBI = BBAnalysis[BBI.FBB->getNumber()];
151 if (FBBI.Kind != ICNotClassfied)
152 return;
153
154 // TODO: Only handle very simple cases for now.
155 if (TBBI.FBB || FBBI.FBB || TBBI.Cond.size() > 1 || FBBI.Cond.size() > 1)
156 return;
157
158 if (TBBI.TBB && TBBI.TBB == BBI.FBB) {
159 // Triangle:
160 // EBB
161 // | \_
162 // | |
163 // | TBB
164 // | /
165 // FBB
166 BBI.Kind = ICTriangleEntry;
167 TBBI.Kind = FBBI.Kind = ICTriangle;
168 } else if (TBBI.TBB == FBBI.TBB) {
169 // Diamond:
170 // EBB
171 // / \_
172 // | |
173 // TBB FBB
174 // \ /
175 // MBB
176 // Note MBB can be empty in case both TBB and FBB are return blocks.
177 BBI.Kind = ICDiamondEntry;
178 TBBI.Kind = FBBI.Kind = ICDiamond;
179 BBI.CMBB = TBBI.TBB;
180 }
181 return;
182}
183
Evan Chengd6ddc302007-05-16 21:54:37 +0000184/// InitialFunctionAnalysis - Analyze all blocks and find entries for all
185/// if-conversion candidates.
Evan Cheng4e654852007-05-16 02:00:57 +0000186void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
187 std::vector<int> &Candidates) {
188 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
189 MachineBasicBlock *BB = I;
190 AnalyzeBlock(BB);
191 BBInfo &BBI = BBAnalysis[BB->getNumber()];
192 if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
193 Candidates.push_back(BB->getNumber());
194 }
195}
196
Evan Chengd6ddc302007-05-16 21:54:37 +0000197/// IfConvertTriangle - If convert a triangle sub-CFG.
198///
Evan Cheng4e654852007-05-16 02:00:57 +0000199bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
Evan Chengd6ddc302007-05-16 21:54:37 +0000200 if (isBlockPredicable(BBI.TBB)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000201 // Predicate the 'true' block after removing its branch.
202 TII->RemoveBranch(*BBI.TBB);
203 PredicateBlock(BBI.TBB, BBI.Cond);
204
205 // Join the 'true' and 'false' blocks by copying the instructions
206 // from the 'false' block to the 'true' block.
207 MergeBlocks(BBI.TBB, BBI.FBB);
208
209 // Adjust entry block, it should have but a single unconditional
210 // branch.
211 BBI.EBB->removeSuccessor(BBI.FBB);
212 TII->RemoveBranch(*BBI.EBB);
213 std::vector<MachineOperand> NoCond;
214 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
215
216 // FIXME: Must maintain LiveIns.
217 NumIfConvBBs++;
218 return true;
219 }
220 return false;
221}
222
Evan Chengd6ddc302007-05-16 21:54:37 +0000223/// IfConvertDiamond - If convert a diamond sub-CFG.
224///
Evan Cheng4e654852007-05-16 02:00:57 +0000225bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
Evan Chengd6ddc302007-05-16 21:54:37 +0000226 if (isBlockPredicable(BBI.TBB) && isBlockPredicable(BBI.FBB)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000227 std::vector<MachineInstr*> Dups;
228 if (!BBI.CMBB) {
229 // No common merge block. Check if the terminators (e.g. return) are
Evan Chengc3a289c2007-05-16 20:56:08 +0000230 // the same or predicable.
Evan Cheng4e654852007-05-16 02:00:57 +0000231 MachineBasicBlock::iterator TT = BBI.TBB->getFirstTerminator();
232 MachineBasicBlock::iterator FT = BBI.FBB->getFirstTerminator();
233 while (TT != BBI.TBB->end() && FT != BBI.FBB->end()) {
234 if (TT->isIdenticalTo(FT))
235 Dups.push_back(TT); // Will erase these later.
Evan Chengc3a289c2007-05-16 20:56:08 +0000236 else if (!TT->isPredicable() && !FT->isPredicable())
Evan Cheng4e654852007-05-16 02:00:57 +0000237 return false; // Can't if-convert. Abort!
238 ++TT;
239 ++FT;
240 }
Evan Chengd6ddc302007-05-16 21:54:37 +0000241 // One of the two pathes have more terminators, make sure they are all
242 // predicable.
Evan Cheng4e654852007-05-16 02:00:57 +0000243 while (TT != BBI.TBB->end())
Evan Chengc3a289c2007-05-16 20:56:08 +0000244 if (!TT->isPredicable())
Evan Cheng4e654852007-05-16 02:00:57 +0000245 return false; // Can't if-convert. Abort!
246 while (FT != BBI.FBB->end())
Evan Chengc3a289c2007-05-16 20:56:08 +0000247 if (!FT->isPredicable())
Evan Cheng4e654852007-05-16 02:00:57 +0000248 return false; // Can't if-convert. Abort!
249 }
250
251 // Remove the duplicated instructions from the 'true' block.
252 for (unsigned i = 0, e = Dups.size(); i != e; ++i)
253 Dups[i]->eraseFromParent();
254
255 // Predicate the 'true' block after removing its branch.
256 TII->RemoveBranch(*BBI.TBB);
257 PredicateBlock(BBI.TBB, BBI.Cond);
258
259 // Predicate the 'false' block.
260 std::vector<MachineOperand> NewCond(BBI.Cond);
261 TII->ReverseBranchCondition(NewCond);
262 PredicateBlock(BBI.FBB, NewCond, true);
263
264 // Join the 'true' and 'false' blocks by copying the instructions
265 // from the 'false' block to the 'true' block.
266 MergeBlocks(BBI.TBB, BBI.FBB);
267
268 // Adjust entry block, it should have but a single unconditional
269 // branch .
270 BBI.EBB->removeSuccessor(BBI.FBB);
271 TII->RemoveBranch(*BBI.EBB);
272 std::vector<MachineOperand> NoCond;
273 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
274
275 // FIXME: Must maintain LiveIns.
276 NumIfConvBBs += 2;
277 return true;
278 }
279 return false;
280}
281
Evan Chengc3a289c2007-05-16 20:56:08 +0000282/// isBlockPredicable - Returns true if the block is predicable. In most
283/// cases, that means all the instructions in the block has M_PREDICABLE flag.
Evan Chengd6ddc302007-05-16 21:54:37 +0000284/// It assume all the terminator instructions can be converted or deleted.
285bool IfConverter::isBlockPredicable(MachineBasicBlock *BB) const {
Evan Cheng4e654852007-05-16 02:00:57 +0000286 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
287 I != E; ++I) {
Evan Chengd6ddc302007-05-16 21:54:37 +0000288 if (TII->isTerminatorInstr(I->getOpcode()))
Evan Cheng4e654852007-05-16 02:00:57 +0000289 continue;
Evan Chengc3a289c2007-05-16 20:56:08 +0000290 if (!I->isPredicable())
Evan Cheng4e654852007-05-16 02:00:57 +0000291 return false;
292 }
293 return true;
294}
295
296/// PredicateBlock - Predicate every instruction in the block with the specified
297/// condition. If IgnoreTerm is true, skip over all terminator instructions.
298void IfConverter::PredicateBlock(MachineBasicBlock *BB,
299 std::vector<MachineOperand> &Cond,
300 bool IgnoreTerm) {
301 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
302 I != E; ++I) {
303 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
304 continue;
Evan Chengd6ddc302007-05-16 21:54:37 +0000305 if (!TII->PredicateInstruction(&*I, Cond)) {
306 cerr << "Unable to predication " << *I << "!\n";
307 abort();
308 }
Evan Cheng4e654852007-05-16 02:00:57 +0000309 }
310}
311
312/// MergeBlocks - Move all instructions from FBB to the end of TBB.
313///
314void IfConverter::MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB) {
315 TBB->splice(TBB->end(), FBB, FBB->begin(), FBB->end());
316}