isBlockPredicable() always ignore terminal instructions; add comments.
[oota-llvm.git] / lib / CodeGen / IfConversion.cpp
1 //===-- 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"
22 using namespace llvm;
23
24 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
25
26 namespace {
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);
71     bool isBlockPredicable(MachineBasicBlock *BB) const;
72     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
80 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
81
82 bool 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
113 static 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
124 void 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;
136   // Can't do it if 'true' block is already marked as to be if-converted.
137   AnalyzeBlock(BBI.TBB);
138   BBInfo &TBBI = BBAnalysis[BBI.TBB->getNumber()];
139   if (TBBI.Kind != ICNotClassfied)
140     return;
141
142   // No false branch. This BB must end with a conditional branch and a
143   // fallthrough.
144   if (!BBI.FBB)
145     BBI.FBB = findFalseBlock(BB, BBI.TBB);  
146   assert(BBI.FBB && "Expected to find the fallthrough block!");
147
148   // Can't do it if 'false' block is already marked as to be if-converted.
149   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
184 /// InitialFunctionAnalysis - Analyze all blocks and find entries for all
185 /// if-conversion candidates.
186 void 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
197 /// IfConvertTriangle - If convert a triangle sub-CFG.
198 ///
199 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
200   if (isBlockPredicable(BBI.TBB)) {
201     // 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
223 /// IfConvertDiamond - If convert a diamond sub-CFG.
224 ///
225 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
226   if (isBlockPredicable(BBI.TBB) && isBlockPredicable(BBI.FBB)) {
227     std::vector<MachineInstr*> Dups;
228     if (!BBI.CMBB) {
229       // No common merge block. Check if the terminators (e.g. return) are
230       // the same or predicable.
231       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.
236         else if (!TT->isPredicable() && !FT->isPredicable())
237           return false; // Can't if-convert. Abort!
238         ++TT;
239         ++FT;
240       }
241       // One of the two pathes have more terminators, make sure they are all
242       // predicable.
243       while (TT != BBI.TBB->end())
244         if (!TT->isPredicable())
245           return false; // Can't if-convert. Abort!
246       while (FT != BBI.FBB->end())
247         if (!FT->isPredicable())
248           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
282 /// isBlockPredicable - Returns true if the block is predicable. In most
283 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
284 /// It assume all the terminator instructions can be converted or deleted.
285 bool IfConverter::isBlockPredicable(MachineBasicBlock *BB) const {
286   for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
287        I != E; ++I) {
288     if (TII->isTerminatorInstr(I->getOpcode()))
289       continue;
290     if (!I->isPredicable())
291       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.
298 void 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;
305     if (!TII->PredicateInstruction(&*I, Cond)) {
306       cerr << "Unable to predication " << *I << "!\n";
307       abort();
308     }
309   }
310 }
311
312 /// MergeBlocks - Move all instructions from FBB to the end of TBB.
313 ///
314 void IfConverter::MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB) {
315   TBB->splice(TBB->end(), FBB, FBB->begin(), FBB->end());
316 }