1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level if-conversion pass.
12 //===----------------------------------------------------------------------===//
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"
24 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
27 class IfConverter : public MachineFunctionPass {
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.
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
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) {}
52 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
53 /// basic block number.
54 std::vector<BBInfo> BBAnalysis;
56 const TargetInstrInfo *TII;
60 IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
62 virtual bool runOnMachineFunction(MachineFunction &MF);
63 virtual const char *getPassName() const { return "If converter"; }
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 isBlockPredicatable(MachineBasicBlock *BB,
72 bool IgnoreTerm = false) const;
73 void PredicateBlock(MachineBasicBlock *BB,
74 std::vector<MachineOperand> &Cond,
75 bool IgnoreTerm = false);
76 void MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB);
78 char IfConverter::ID = 0;
81 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
83 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
84 TII = MF.getTarget().getInstrInfo();
85 if (!TII) return false;
90 unsigned NumBBs = MF.getNumBlockIDs();
91 BBAnalysis.resize(NumBBs);
93 std::vector<int> Candidates;
94 // Do an intial analysis for each basic block and finding all the potential
95 // candidates to perform if-convesion.
96 InitialFunctionAnalysis(MF, Candidates);
98 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
99 BBInfo &BBI = BBAnalysis[i];
101 default: assert(false && "Unexpected!");
103 case ICTriangleEntry:
104 MadeChange |= IfConvertTriangle(BBI);
107 MadeChange |= IfConvertDiamond(BBI);
114 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
115 MachineBasicBlock *TBB) {
116 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
117 E = BB->succ_end(); SI != E; ++SI) {
118 MachineBasicBlock *SuccBB = *SI;
125 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
126 BBInfo &BBI = BBAnalysis[BB->getNumber()];
128 if (BBI.Kind != ICInvalid)
129 return; // Always analyzed.
132 // Look for 'root' of a simple (non-nested) triangle or diamond.
133 BBI.Kind = ICNotClassfied;
134 if (TII->AnalyzeBranch(*BB, BBI.TBB, BBI.FBB, BBI.Cond)
135 || !BBI.TBB || BBI.Cond.size() == 0)
137 AnalyzeBlock(BBI.TBB);
138 BBInfo &TBBI = BBAnalysis[BBI.TBB->getNumber()];
139 if (TBBI.Kind != ICNotClassfied)
143 BBI.FBB = findFalseBlock(BB, BBI.TBB);
144 assert(BBI.FBB && "Expected to find the fallthrough block!");
146 AnalyzeBlock(BBI.FBB);
147 BBInfo &FBBI = BBAnalysis[BBI.FBB->getNumber()];
148 if (FBBI.Kind != ICNotClassfied)
151 // TODO: Only handle very simple cases for now.
152 if (TBBI.FBB || FBBI.FBB || TBBI.Cond.size() > 1 || FBBI.Cond.size() > 1)
155 if (TBBI.TBB && TBBI.TBB == BBI.FBB) {
163 BBI.Kind = ICTriangleEntry;
164 TBBI.Kind = FBBI.Kind = ICTriangle;
165 } else if (TBBI.TBB == FBBI.TBB) {
173 // Note MBB can be empty in case both TBB and FBB are return blocks.
174 BBI.Kind = ICDiamondEntry;
175 TBBI.Kind = FBBI.Kind = ICDiamond;
181 void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
182 std::vector<int> &Candidates) {
183 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
184 MachineBasicBlock *BB = I;
186 BBInfo &BBI = BBAnalysis[BB->getNumber()];
187 if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
188 Candidates.push_back(BB->getNumber());
192 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
193 if (isBlockPredicatable(BBI.TBB, true)) {
194 // Predicate the 'true' block after removing its branch.
195 TII->RemoveBranch(*BBI.TBB);
196 PredicateBlock(BBI.TBB, BBI.Cond);
198 // Join the 'true' and 'false' blocks by copying the instructions
199 // from the 'false' block to the 'true' block.
200 MergeBlocks(BBI.TBB, BBI.FBB);
202 // Adjust entry block, it should have but a single unconditional
204 BBI.EBB->removeSuccessor(BBI.FBB);
205 TII->RemoveBranch(*BBI.EBB);
206 std::vector<MachineOperand> NoCond;
207 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
209 // FIXME: Must maintain LiveIns.
216 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
217 if (isBlockPredicatable(BBI.TBB, true) &&
218 isBlockPredicatable(BBI.FBB, true)) {
219 std::vector<MachineInstr*> Dups;
221 // No common merge block. Check if the terminators (e.g. return) are
222 // the same or predicatable.
223 MachineBasicBlock::iterator TT = BBI.TBB->getFirstTerminator();
224 MachineBasicBlock::iterator FT = BBI.FBB->getFirstTerminator();
225 while (TT != BBI.TBB->end() && FT != BBI.FBB->end()) {
226 if (TT->isIdenticalTo(FT))
227 Dups.push_back(TT); // Will erase these later.
228 else if (!TII->isPredicatable(TT) && !TII->isPredicatable(FT))
229 return false; // Can't if-convert. Abort!
234 while (TT != BBI.TBB->end())
235 if (!TII->isPredicatable(TT))
236 return false; // Can't if-convert. Abort!
237 while (FT != BBI.FBB->end())
238 if (!TII->isPredicatable(FT))
239 return false; // Can't if-convert. Abort!
242 // Remove the duplicated instructions from the 'true' block.
243 for (unsigned i = 0, e = Dups.size(); i != e; ++i)
244 Dups[i]->eraseFromParent();
246 // Predicate the 'true' block after removing its branch.
247 TII->RemoveBranch(*BBI.TBB);
248 PredicateBlock(BBI.TBB, BBI.Cond);
250 // Predicate the 'false' block.
251 std::vector<MachineOperand> NewCond(BBI.Cond);
252 TII->ReverseBranchCondition(NewCond);
253 PredicateBlock(BBI.FBB, NewCond, true);
255 // Join the 'true' and 'false' blocks by copying the instructions
256 // from the 'false' block to the 'true' block.
257 MergeBlocks(BBI.TBB, BBI.FBB);
259 // Adjust entry block, it should have but a single unconditional
261 BBI.EBB->removeSuccessor(BBI.FBB);
262 TII->RemoveBranch(*BBI.EBB);
263 std::vector<MachineOperand> NoCond;
264 TII->InsertBranch(*BBI.EBB, BBI.TBB, NULL, NoCond);
266 // FIXME: Must maintain LiveIns.
273 /// isBlockPredicatable - Returns true if the block is predicatable. In most
274 /// cases, that means all the instructions in the block has M_PREDICATED flag.
275 /// If IgnoreTerm is true, assume all the terminator instructions can be
276 /// converted or deleted.
277 bool IfConverter::isBlockPredicatable(MachineBasicBlock *BB,
278 bool IgnoreTerm) const {
279 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
281 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
283 if (!TII->isPredicatable(I))
289 /// PredicateBlock - Predicate every instruction in the block with the specified
290 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
291 void IfConverter::PredicateBlock(MachineBasicBlock *BB,
292 std::vector<MachineOperand> &Cond,
294 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
296 if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
298 TII->PredicateInstruction(&*I, Cond);
302 /// MergeBlocks - Move all instructions from FBB to the end of TBB.
304 void IfConverter::MergeBlocks(MachineBasicBlock *TBB, MachineBasicBlock *FBB) {
305 TBB->splice(TBB->end(), FBB, FBB->begin(), FBB->end());