IfConversion.cpp revision 36489bbbacb2adf0d639faa2d1bc2bbde9936396
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/TargetLowering.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/ADT/DepthFirstIterator.h"
23#include "llvm/ADT/Statistic.h"
24using namespace llvm;
25
26STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
27
28namespace {
29  class IfConverter : public MachineFunctionPass {
30    enum BBICKind {
31      ICInvalid,       // BB data invalid.
32      ICNotClassfied,  // BB data valid, but not classified.
33      ICTriangle,      // BB is part of a triangle sub-CFG.
34      ICDiamond,       // BB is part of a diamond sub-CFG.
35      ICTriangleEntry, // BB is entry of a triangle sub-CFG.
36      ICDiamondEntry   // BB is entry of a diamond sub-CFG.
37    };
38
39    /// BBInfo - One per MachineBasicBlock, this is used to cache the result
40    /// if-conversion feasibility analysis. This includes results from
41    /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
42    /// classification, and common tail block of its successors (if it's a
43    /// diamond shape), its size, whether it's predicable, and whether any
44    /// instruction can clobber the 'would-be' predicate.
45    struct BBInfo {
46      BBICKind Kind;
47      unsigned Size;
48      bool isPredicable;
49      bool ClobbersPred;
50      MachineBasicBlock *BB;
51      MachineBasicBlock *TrueBB;
52      MachineBasicBlock *FalseBB;
53      MachineBasicBlock *TailBB;
54      std::vector<MachineOperand> Cond;
55      BBInfo() : Kind(ICInvalid), Size(0), isPredicable(false),
56                 ClobbersPred(false), BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
57    };
58
59    /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
60    /// basic block number.
61    std::vector<BBInfo> BBAnalysis;
62
63    const TargetLowering *TLI;
64    const TargetInstrInfo *TII;
65    bool MadeChange;
66  public:
67    static char ID;
68    IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
69
70    virtual bool runOnMachineFunction(MachineFunction &MF);
71    virtual const char *getPassName() const { return "If converter"; }
72
73  private:
74    void StructuralAnalysis(MachineBasicBlock *BB);
75    void FeasibilityAnalysis(BBInfo &BBI);
76    void InitialFunctionAnalysis(MachineFunction &MF,
77                                 std::vector<int> &Candidates);
78    bool IfConvertTriangle(BBInfo &BBI);
79    bool IfConvertDiamond(BBInfo &BBI);
80    void PredicateBlock(MachineBasicBlock *BB,
81                        std::vector<MachineOperand> &Cond,
82                        bool IgnoreTerm = false);
83    void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
84  };
85  char IfConverter::ID = 0;
86}
87
88FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
89
90bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
91  TLI = MF.getTarget().getTargetLowering();
92  TII = MF.getTarget().getInstrInfo();
93  if (!TII) return false;
94
95  MF.RenumberBlocks();
96  unsigned NumBBs = MF.getNumBlockIDs();
97  BBAnalysis.resize(NumBBs);
98
99  std::vector<int> Candidates;
100  // Do an intial analysis for each basic block and finding all the potential
101  // candidates to perform if-convesion.
102  InitialFunctionAnalysis(MF, Candidates);
103
104  MadeChange = false;
105  for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
106    BBInfo &BBI = BBAnalysis[Candidates[i]];
107    switch (BBI.Kind) {
108    default: assert(false && "Unexpected!");
109      break;
110    case ICTriangleEntry:
111      MadeChange |= IfConvertTriangle(BBI);
112      break;
113    case ICDiamondEntry:
114      MadeChange |= IfConvertDiamond(BBI);
115      break;
116    }
117  }
118
119  BBAnalysis.clear();
120
121  return MadeChange;
122}
123
124static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
125                                         MachineBasicBlock *TrueBB) {
126  for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
127         E = BB->succ_end(); SI != E; ++SI) {
128    MachineBasicBlock *SuccBB = *SI;
129    if (SuccBB != TrueBB)
130      return SuccBB;
131  }
132  return NULL;
133}
134
135/// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
136/// the specified block. Record its successors and whether it looks like an
137/// if-conversion candidate.
138void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
139  BBInfo &BBI = BBAnalysis[BB->getNumber()];
140
141  if (BBI.Kind != ICInvalid)
142    return;  // Always analyzed.
143  BBI.BB = BB;
144  BBI.Size = std::distance(BB->begin(), BB->end());
145
146  // Look for 'root' of a simple (non-nested) triangle or diamond.
147  BBI.Kind = ICNotClassfied;
148  if (TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.Cond)
149      || !BBI.TrueBB || BBI.Cond.size() == 0)
150    return;
151
152  // Not a candidate if 'true' block has another predecessor.
153  // FIXME: Use or'd predicate or predicated cmp.
154  if (BBI.TrueBB->pred_size() > 1)
155    return;
156
157  // Not a candidate if 'true' block is going to be if-converted.
158  StructuralAnalysis(BBI.TrueBB);
159  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
160  if (TrueBBI.Kind != ICNotClassfied)
161    return;
162
163  // TODO: Only handle very simple cases for now.
164  if (TrueBBI.FalseBB || TrueBBI.Cond.size())
165    return;
166
167  // No false branch. This BB must end with a conditional branch and a
168  // fallthrough.
169  if (!BBI.FalseBB)
170    BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);
171  assert(BBI.FalseBB && "Expected to find the fallthrough block!");
172
173  // Not a candidate if 'false' block has another predecessor.
174  // FIXME: Invert condition and swap 'true' / 'false' blocks?
175  if (BBI.FalseBB->pred_size() > 1)
176    return;
177
178  // Not a candidate if 'false' block is going to be if-converted.
179  StructuralAnalysis(BBI.FalseBB);
180  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
181  if (FalseBBI.Kind != ICNotClassfied)
182    return;
183
184  // TODO: Only handle very simple cases for now.
185  if (FalseBBI.FalseBB || FalseBBI.Cond.size())
186    return;
187
188  if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
189    // Triangle:
190    //   EBB
191    //   | \_
192    //   |  |
193    //   | TBB
194    //   |  /
195    //   FBB
196    BBI.Kind = ICTriangleEntry;
197    TrueBBI.Kind = FalseBBI.Kind = ICTriangle;
198  } else if (TrueBBI.TrueBB == FalseBBI.TrueBB) {
199    // Diamond:
200    //   EBB
201    //   / \_
202    //  |   |
203    // TBB FBB
204    //   \ /
205    //  TailBB
206    // Note MBB can be empty in case both TBB and FBB are return blocks.
207    BBI.Kind = ICDiamondEntry;
208    TrueBBI.Kind = FalseBBI.Kind = ICDiamond;
209    BBI.TailBB = TrueBBI.TrueBB;
210  }
211  return;
212}
213
214/// FeasibilityAnalysis - Determine if the block is predicable. In most
215/// cases, that means all the instructions in the block has M_PREDICABLE flag.
216/// Also checks if the block contains any instruction which can clobber a
217/// predicate (e.g. condition code register). If so, the block is not
218/// predicable unless it's the last instruction. Note, this function assumes
219/// all the terminator instructions can be converted or deleted so it ignore
220/// them.
221void IfConverter::FeasibilityAnalysis(BBInfo &BBI) {
222  if (BBI.Size == 0 || BBI.Size > TLI->getIfCvtBlockSizeLimit())
223    return;
224
225  for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
226       I != E; ++I) {
227    // TODO: check if instruction clobbers predicate.
228    if (TII->isTerminatorInstr(I->getOpcode()))
229      break;
230    if (!I->isPredicable())
231      return;
232  }
233
234  BBI.isPredicable = true;
235}
236
237/// InitialFunctionAnalysis - Analyze all blocks and find entries for all
238/// if-conversion candidates.
239void IfConverter::InitialFunctionAnalysis(MachineFunction &MF,
240                                          std::vector<int> &Candidates) {
241  std::set<MachineBasicBlock*> Visited;
242  MachineBasicBlock *Entry = MF.begin();
243  for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
244         E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
245    MachineBasicBlock *BB = *DFI;
246    StructuralAnalysis(BB);
247    BBInfo &BBI = BBAnalysis[BB->getNumber()];
248    if (BBI.Kind == ICTriangleEntry || BBI.Kind == ICDiamondEntry)
249      Candidates.push_back(BB->getNumber());
250  }
251}
252
253/// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
254///
255static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
256   std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
257                                         FromBB->pred_end());
258    for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
259      MachineBasicBlock *Pred = Preds[i];
260      Pred->removeSuccessor(FromBB);
261      if (!Pred->isSuccessor(ToBB))
262        Pred->addSuccessor(ToBB);
263    }
264}
265
266/// TransferSuccs - Transfer all the successors of FromBB to ToBB.
267///
268static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
269   std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
270                                         FromBB->succ_end());
271    for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
272      MachineBasicBlock *Succ = Succs[i];
273      FromBB->removeSuccessor(Succ);
274      if (!ToBB->isSuccessor(Succ))
275        ToBB->addSuccessor(Succ);
276    }
277}
278
279/// IfConvertTriangle - If convert a triangle sub-CFG.
280///
281bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
282  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
283  FeasibilityAnalysis(TrueBBI);
284
285  if (TrueBBI.isPredicable) {
286    BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
287
288    // Predicate the 'true' block after removing its branch.
289    TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
290    PredicateBlock(BBI.TrueBB, BBI.Cond);
291
292    // Join the 'true' and 'false' blocks by copying the instructions
293    // from the 'false' block to the 'true' block.
294    BBI.TrueBB->removeSuccessor(BBI.FalseBB);
295    MergeBlocks(TrueBBI, FalseBBI);
296
297    // Now merge the entry of the triangle with the true block.
298    BBI.Size -= TII->RemoveBranch(*BBI.BB);
299    MergeBlocks(BBI, TrueBBI);
300
301    // Update block info.
302    TrueBBI.Kind = ICInvalid;
303    FalseBBI.Kind = ICInvalid;
304
305    // FIXME: Must maintain LiveIns.
306    NumIfConvBBs++;
307    return true;
308  }
309  return false;
310}
311
312/// IfConvertDiamond - If convert a diamond sub-CFG.
313///
314bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
315  BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
316  BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
317  FeasibilityAnalysis(TrueBBI);
318  FeasibilityAnalysis(FalseBBI);
319
320  if (TrueBBI.isPredicable && FalseBBI.isPredicable) {
321    // Check the 'true' and 'false' blocks if either isn't ended with a branch.
322    // Either the block fallthrough to another block or it ends with a
323    // return. If it's the former, add a conditional branch to its successor.
324    bool Proceed = true;
325    bool TrueNeedCBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
326    bool FalseNeedCBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
327    if (TrueNeedCBr && TrueBBI.ClobbersPred) {
328      TrueBBI.isPredicable = false;
329      Proceed = false;
330    }
331    if (FalseNeedCBr && FalseBBI.ClobbersPred) {
332      FalseBBI.isPredicable = false;
333      Proceed = false;
334    }
335    if (!Proceed)
336      return false;
337
338    std::vector<MachineInstr*> Dups;
339    if (!BBI.TailBB) {
340      // No common merge block. Check if the terminators (e.g. return) are
341      // the same or predicable.
342      MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
343      MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
344      while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
345        if (TT->isIdenticalTo(FT))
346          Dups.push_back(TT);  // Will erase these later.
347        else if (!TT->isPredicable() && !FT->isPredicable())
348          return false; // Can't if-convert. Abort!
349        ++TT;
350        ++FT;
351      }
352      // One of the two pathes have more terminators, make sure they are all
353      // predicable.
354      while (TT != BBI.TrueBB->end())
355        if (!TT->isPredicable())
356          return false; // Can't if-convert. Abort!
357      while (FT != BBI.FalseBB->end())
358        if (!FT->isPredicable())
359          return false; // Can't if-convert. Abort!
360    }
361
362    // Remove the duplicated instructions from the 'true' block.
363    for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
364      Dups[i]->eraseFromParent();
365      --TrueBBI.Size;
366    }
367
368    // Predicate the 'true' block after removing its branch.
369    TrueBBI.Size -= TII->RemoveBranch(*BBI.TrueBB);
370    PredicateBlock(BBI.TrueBB, BBI.Cond);
371
372    // Add a conditional branch to 'true' successor if needed.
373    if (TrueNeedCBr)
374      TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.Cond);
375
376    // Predicate the 'false' block.
377    std::vector<MachineOperand> NewCond(BBI.Cond);
378    TII->ReverseBranchCondition(NewCond);
379    PredicateBlock(BBI.FalseBB, NewCond, true);
380
381    // Add a conditional branch to 'false' successor if needed.
382    if (FalseNeedCBr)
383      TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,NewCond);
384
385    // Merge the 'true' and 'false' blocks by copying the instructions
386    // from the 'false' block to the 'true' block. That is, unless the true
387    // block would clobber the predicate, in that case, do the opposite.
388    BBInfo *CvtBBI;
389    if (!TrueBBI.ClobbersPred) {
390      MergeBlocks(TrueBBI, FalseBBI);
391      CvtBBI = &TrueBBI;
392    } else {
393      MergeBlocks(FalseBBI, TrueBBI);
394      CvtBBI = &FalseBBI;
395    }
396
397    // Remove the conditional branch from entry to the blocks.
398    BBI.Size -= TII->RemoveBranch(*BBI.BB);
399
400    // Merge the combined block into the entry of the diamond if the entry
401    // block is its only predecessor. Otherwise, insert an unconditional
402    // branch from entry to the if-converted block.
403    if (CvtBBI->BB->pred_size() == 1) {
404      BBI.BB->removeSuccessor(CvtBBI->BB);
405      MergeBlocks(BBI, *CvtBBI);
406      CvtBBI = &BBI;
407    } else {
408      std::vector<MachineOperand> NoCond;
409      TII->InsertBranch(*BBI.BB, CvtBBI->BB, NULL, NoCond);
410    }
411
412    // If the if-converted block fallthrough into the tail block, then
413    // fold the tail block in as well.
414    if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
415      CvtBBI->Size -= TII->RemoveBranch(*CvtBBI->BB);
416      CvtBBI->BB->removeSuccessor(BBI.TailBB);
417      BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
418      MergeBlocks(*CvtBBI, TailBBI);
419      TailBBI.Kind = ICInvalid;
420    }
421
422    // Update block info.
423    TrueBBI.Kind = ICInvalid;
424    FalseBBI.Kind = ICInvalid;
425
426    // FIXME: Must maintain LiveIns.
427    NumIfConvBBs += 2;
428    return true;
429  }
430  return false;
431}
432
433/// PredicateBlock - Predicate every instruction in the block with the specified
434/// condition. If IgnoreTerm is true, skip over all terminator instructions.
435void IfConverter::PredicateBlock(MachineBasicBlock *BB,
436                                 std::vector<MachineOperand> &Cond,
437                                 bool IgnoreTerm) {
438  for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
439       I != E; ++I) {
440    if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
441      continue;
442    if (!TII->PredicateInstruction(&*I, Cond)) {
443      cerr << "Unable to predication " << *I << "!\n";
444      abort();
445    }
446  }
447}
448
449/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
450///
451void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
452  ToBBI.BB->splice(ToBBI.BB->end(),
453                   FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
454  TransferPreds(ToBBI.BB, FromBBI.BB);
455  TransferSuccs(ToBBI.BB, FromBBI.BB);
456  ToBBI.Size += FromBBI.Size;
457  FromBBI.Size = 0;
458}
459