c5e4ef7c9d2c752febbd1af1688d916603163a56
[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/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"
24 using namespace llvm;
25
26 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
27
28 namespace {
29   class IfConverter : public MachineFunctionPass {
30     enum BBICKind {
31       ICNotAnalyzed,   // BB has not been analyzed.
32       ICReAnalyze,     // BB must be re-analyzed.
33       ICNotClassfied,  // BB data valid, but not classified.
34       ICEarlyExit,     // BB is entry of an early-exit sub-CFG.
35       ICTriangle,      // BB is entry of a triangle sub-CFG.
36       ICDiamond,       // BB is entry of a diamond sub-CFG.
37       ICChild,         // BB is part of the sub-CFG that'll be predicated.
38       ICDead           // BB has been converted and merged, it's now dead.
39     };
40
41     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
42     /// if-conversion feasibility analysis. This includes results from
43     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
44     /// classification, and common tail block of its successors (if it's a
45     /// diamond shape), its size, whether it's predicable, and whether any
46     /// instruction can clobber the 'would-be' predicate.
47     ///
48     /// Kind            - Type of block. See BBICKind.
49     /// NonPredSize     - Number of non-predicated instructions.
50     /// isPredicable    - Is it predicable. (FIXME: Remove.)
51     /// hasEarlyExit    - Ends with a return, indirect jump or br to jumptable.
52     /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
53     ///                   the predicate (e.g. has cmp, call, etc.)
54     /// BB              - Corresponding MachineBasicBlock.
55     /// TrueBB / FalseBB- See AnalyzeBranch().
56     /// BrCond          - Conditions for end of block conditional branches.
57     /// Predicate       - Predicate used in the BB.
58     struct BBInfo {
59       BBICKind Kind;
60       unsigned NonPredSize;
61       bool isPredicable;
62       bool hasEarlyExit;
63       bool ModifyPredicate;
64       MachineBasicBlock *BB;
65       MachineBasicBlock *TrueBB;
66       MachineBasicBlock *FalseBB;
67       MachineBasicBlock *TailBB;
68       std::vector<MachineOperand> BrCond;
69       std::vector<MachineOperand> Predicate;
70       BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0), isPredicable(false),
71                  hasEarlyExit(false), ModifyPredicate(false),
72                  BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
73     };
74
75     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
76     /// basic block number.
77     std::vector<BBInfo> BBAnalysis;
78
79     const TargetLowering *TLI;
80     const TargetInstrInfo *TII;
81     bool MadeChange;
82   public:
83     static char ID;
84     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
85
86     virtual bool runOnMachineFunction(MachineFunction &MF);
87     virtual const char *getPassName() const { return "If converter"; }
88
89   private:
90     void StructuralAnalysis(MachineBasicBlock *BB);
91     void FeasibilityAnalysis(BBInfo &BBI,
92                              std::vector<MachineOperand> &Cond);
93     void AnalyzeBlocks(MachineFunction &MF,
94                        std::vector<BBInfo*> &Candidates);
95     void InvalidatePreds(MachineBasicBlock *BB);
96     bool IfConvertEarlyExit(BBInfo &BBI);
97     bool IfConvertTriangle(BBInfo &BBI);
98     bool IfConvertDiamond(BBInfo &BBI);
99     void PredicateBlock(BBInfo &BBI,
100                         std::vector<MachineOperand> &Cond,
101                         bool IgnoreTerm = false);
102     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
103   };
104   char IfConverter::ID = 0;
105 }
106
107 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
108
109 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
110   TLI = MF.getTarget().getTargetLowering();
111   TII = MF.getTarget().getInstrInfo();
112   if (!TII) return false;
113
114   MF.RenumberBlocks();
115   unsigned NumBBs = MF.getNumBlockIDs();
116   BBAnalysis.resize(NumBBs);
117
118   std::vector<BBInfo*> Candidates;
119   MadeChange = false;
120   while (true) {
121     bool Change = false;
122
123     // Do an intial analysis for each basic block and finding all the potential
124     // candidates to perform if-convesion.
125     AnalyzeBlocks(MF, Candidates);
126     while (!Candidates.empty()) {
127       BBInfo &BBI = *Candidates.back();
128       Candidates.pop_back();
129       switch (BBI.Kind) {
130       default: assert(false && "Unexpected!");
131         break;
132       case ICEarlyExit:
133         Change |= IfConvertEarlyExit(BBI);
134         break;
135       case ICTriangle:
136         Change |= IfConvertTriangle(BBI);
137         break;
138       case ICDiamond:
139         Change |= IfConvertDiamond(BBI);
140         break;
141       }
142     }
143
144     MadeChange |= Change;
145     if (!Change)
146       break;
147   }
148
149   BBAnalysis.clear();
150
151   return MadeChange;
152 }
153
154 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
155                                          MachineBasicBlock *TrueBB) {
156   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
157          E = BB->succ_end(); SI != E; ++SI) {
158     MachineBasicBlock *SuccBB = *SI;
159     if (SuccBB != TrueBB)
160       return SuccBB;
161   }
162   return NULL;
163 }
164
165 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
166 /// the specified block. Record its successors and whether it looks like an
167 /// if-conversion candidate.
168 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
169   BBInfo &BBI = BBAnalysis[BB->getNumber()];
170
171   if (BBI.Kind != ICReAnalyze) {
172     if (BBI.Kind != ICNotAnalyzed)
173       return;  // Already analyzed.
174     BBI.BB = BB;
175     BBI.NonPredSize = std::distance(BB->begin(), BB->end());
176
177     // Look for 'root' of a simple (non-nested) triangle or diamond.
178     BBI.Kind = ICNotClassfied;
179     bool CanAnalyze = !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB,
180                                           BBI.BrCond);
181     // Does it end with a return, indirect jump, or jumptable branch?
182     BBI.hasEarlyExit = TII->BlockHasNoFallThrough(*BB) && !BBI.TrueBB;
183     if (!CanAnalyze || !BBI.TrueBB || BBI.BrCond.size() == 0)
184       return;
185   }
186
187   // Not a candidate if 'true' block is going to be if-converted.
188   StructuralAnalysis(BBI.TrueBB);
189   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
190   if (TrueBBI.Kind != ICNotClassfied)
191     return;
192
193   // TODO: Only handle very simple cases for now.
194   if (TrueBBI.FalseBB || TrueBBI.BrCond.size())
195     return;
196
197   // No false branch. This BB must end with a conditional branch and a
198   // fallthrough.
199   if (!BBI.FalseBB)
200     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
201   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
202
203   // Not a candidate if 'false' block is going to be if-converted.
204   StructuralAnalysis(BBI.FalseBB);
205   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
206   if (FalseBBI.Kind != ICNotClassfied)
207     return;
208
209   // TODO: Only handle very simple cases for now.
210   if (FalseBBI.FalseBB || FalseBBI.BrCond.size())
211     return;
212
213   unsigned TrueNumPreds  = BBI.TrueBB->pred_size();
214   unsigned FalseNumPreds = BBI.FalseBB->pred_size();
215   if ((TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
216       !(FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
217     BBI.Kind = ICEarlyExit;
218     TrueBBI.Kind = ICChild;
219   } else if (!(TrueBBI.hasEarlyExit && TrueNumPreds <= 1) &&
220              (FalseBBI.hasEarlyExit && FalseNumPreds <=1)) {
221     BBI.Kind = ICEarlyExit;
222     FalseBBI.Kind = ICChild;
223   } else if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB) {
224     // Triangle:
225     //   EBB
226     //   | \_
227     //   |  |
228     //   | TBB
229     //   |  /
230     //   FBB
231     BBI.Kind = ICTriangle;
232     TrueBBI.Kind = FalseBBI.Kind = ICChild;
233   } else if (TrueBBI.TrueBB == FalseBBI.TrueBB &&
234              TrueNumPreds <= 1 && FalseNumPreds <= 1) {
235     // Diamond:
236     //   EBB
237     //   / \_
238     //  |   |
239     // TBB FBB
240     //   \ /
241     //  TailBB
242     // Note MBB can be empty in case both TBB and FBB are return blocks.
243     BBI.Kind = ICDiamond;
244     TrueBBI.Kind = FalseBBI.Kind = ICChild;
245     BBI.TailBB = TrueBBI.TrueBB;
246   }
247   return;
248 }
249
250 /// FeasibilityAnalysis - Determine if the block is predicable. In most
251 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
252 /// Also checks if the block contains any instruction which can clobber a
253 /// predicate (e.g. condition code register). If so, the block is not
254 /// predicable unless it's the last instruction. Note, this function assumes
255 /// all the terminator instructions can be converted or deleted so it ignore
256 /// them.
257 void IfConverter::FeasibilityAnalysis(BBInfo &BBI,
258                                       std::vector<MachineOperand> &Cond) {
259   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
260     return;
261
262   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
263        I != E; ++I) {
264     // TODO: check if instruction clobbers predicate.
265     if (TII->isTerminatorInstr(I->getOpcode()))
266       break;
267     if (!I->isPredicable())
268       return;
269   }
270
271   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
272     return;
273
274   BBI.isPredicable = true;
275 }
276
277 /// AnalyzeBlocks - Analyze all blocks and find entries for all
278 /// if-conversion candidates.
279 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
280                                 std::vector<BBInfo*> &Candidates) {
281   std::set<MachineBasicBlock*> Visited;
282   MachineBasicBlock *Entry = MF.begin();
283   for (df_ext_iterator<MachineBasicBlock*> DFI = df_ext_begin(Entry, Visited),
284          E = df_ext_end(Entry, Visited); DFI != E; ++DFI) {
285     MachineBasicBlock *BB = *DFI;
286     StructuralAnalysis(BB);
287     BBInfo &BBI = BBAnalysis[BB->getNumber()];
288     switch (BBI.Kind) {
289     default: break;
290     case ICEarlyExit:
291     case ICTriangle:
292     case ICDiamond:
293       Candidates.push_back(&BBI);
294       break;
295     }
296   }
297 }
298
299 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
300 ///
301 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
302    std::vector<MachineBasicBlock*> Preds(FromBB->pred_begin(),
303                                          FromBB->pred_end());
304     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
305       MachineBasicBlock *Pred = Preds[i];
306       Pred->removeSuccessor(FromBB);
307       if (!Pred->isSuccessor(ToBB))
308         Pred->addSuccessor(ToBB);
309     }
310 }
311
312 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
313 ///
314 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
315    std::vector<MachineBasicBlock*> Succs(FromBB->succ_begin(),
316                                          FromBB->succ_end());
317     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
318       MachineBasicBlock *Succ = Succs[i];
319       FromBB->removeSuccessor(Succ);
320       if (!ToBB->isSuccessor(Succ))
321         ToBB->addSuccessor(Succ);
322     }
323 }
324
325 /// isNextBlock - Returns true if ToBB the next basic block after BB.
326 ///
327 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
328   MachineFunction::iterator Fallthrough = BB;
329   return MachineFunction::iterator(ToBB) == ++Fallthrough;
330 }
331
332 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
333 /// to determine if it can be if-converted.
334 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
335   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
336          E = BB->pred_end(); PI != E; ++PI) {
337     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
338     PBBI.Kind = ICReAnalyze;
339   }
340 }
341
342 /// IfConvertEarlyExit - If convert a early exit sub-CFG.
343 ///
344 bool IfConverter::IfConvertEarlyExit(BBInfo &BBI) {
345   BBI.Kind = ICNotClassfied;
346
347   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
348   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
349   BBInfo *CvtBBI = &TrueBBI;
350   BBInfo *NextBBI = &FalseBBI;
351
352   bool ReserveCond = false;
353   if (TrueBBI.Kind != ICChild) {
354     std::swap(CvtBBI, NextBBI);
355     ReserveCond = true;
356   }
357
358   std::vector<MachineOperand> NewCond(BBI.BrCond);
359   if (ReserveCond)
360     TII->ReverseBranchCondition(NewCond);
361   FeasibilityAnalysis(*CvtBBI, NewCond);
362   if (!CvtBBI->isPredicable)
363     return false;
364
365   PredicateBlock(*CvtBBI, NewCond);
366
367   // Merge converted block into entry block. Also convert the end of the
368   // block conditional branch (to the non-converted block) into an
369   // unconditional one.
370   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
371   MergeBlocks(BBI, *CvtBBI);
372   if (!isNextBlock(BBI.BB, NextBBI->BB)) {
373     std::vector<MachineOperand> NoCond;
374     TII->InsertBranch(*BBI.BB, NextBBI->BB, NULL, NoCond);
375   }
376   std::copy(NewCond.begin(), NewCond.end(), std::back_inserter(BBI.Predicate));
377
378   // Update block info. BB can be iteratively if-converted.
379   BBI.Kind = ICNotAnalyzed;
380   BBI.TrueBB = BBI.FalseBB = NULL;
381   BBI.BrCond.clear();
382   TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
383   InvalidatePreds(BBI.BB);
384   CvtBBI->Kind = ICDead;
385
386   // FIXME: Must maintain LiveIns.
387   NumIfConvBBs++;
388   return true;
389 }
390
391 /// IfConvertTriangle - If convert a triangle sub-CFG.
392 ///
393 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
394   BBI.Kind = ICNotClassfied;
395
396   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
397   FeasibilityAnalysis(TrueBBI, BBI.BrCond);
398   if (!TrueBBI.isPredicable)
399     return false;
400
401   // Predicate the 'true' block after removing its branch.
402   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
403   PredicateBlock(TrueBBI, BBI.BrCond);
404
405   // Join the 'true' and 'false' blocks by copying the instructions
406   // from the 'false' block to the 'true' block.
407   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
408   MergeBlocks(TrueBBI, FalseBBI);
409
410   // Now merge the entry of the triangle with the true block.
411   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
412   MergeBlocks(BBI, TrueBBI);
413   std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
414             std::back_inserter(BBI.Predicate));
415
416   // Update block info. BB can be iteratively if-converted.
417   BBI.Kind = ICNotClassfied;
418   BBI.TrueBB = BBI.FalseBB = NULL;
419   BBI.BrCond.clear();
420   TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
421   TrueBBI.Kind = ICDead;
422
423   // FIXME: Must maintain LiveIns.
424   NumIfConvBBs++;
425   return true;
426 }
427
428 /// IfConvertDiamond - If convert a diamond sub-CFG.
429 ///
430 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
431   BBI.Kind = ICNotClassfied;
432
433   bool TrueNeedCBr;
434   bool FalseNeedCBr;
435   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
436   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
437   FeasibilityAnalysis(TrueBBI, BBI.BrCond);
438   std::vector<MachineOperand> RevCond(BBI.BrCond);
439   TII->ReverseBranchCondition(RevCond);
440   FeasibilityAnalysis(FalseBBI, RevCond);
441
442   SmallVector<MachineInstr*, 2> Dups;
443   bool Proceed = TrueBBI.isPredicable && FalseBBI.isPredicable;
444   if (Proceed) {
445     // Check the 'true' and 'false' blocks if either isn't ended with a branch.
446     // Either the block fallthrough to another block or it ends with a
447     // return. If it's the former, add a conditional branch to its successor.
448     TrueNeedCBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
449     FalseNeedCBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size();
450     if (TrueNeedCBr && TrueBBI.ModifyPredicate) {
451       TrueBBI.isPredicable = false;
452       Proceed = false;
453     }
454     if (FalseNeedCBr && FalseBBI.ModifyPredicate) {
455       FalseBBI.isPredicable = false;
456       Proceed = false;
457     }
458
459     if (Proceed) {
460       if (!BBI.TailBB) {
461         // No common merge block. Check if the terminators (e.g. return) are
462         // the same or predicable.
463         MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
464         MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
465         while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
466           if (TT->isIdenticalTo(FT))
467             Dups.push_back(TT);  // Will erase these later.
468           else if (!TT->isPredicable() && !FT->isPredicable()) {
469             Proceed = false;
470             break; // Can't if-convert. Abort!
471           }
472           ++TT;
473           ++FT;
474         }
475
476         // One of the two pathes have more terminators, make sure they are
477         // all predicable.
478         while (Proceed && TT != BBI.TrueBB->end())
479           if (!TT->isPredicable()) {
480             Proceed = false;
481             break; // Can't if-convert. Abort!
482           }
483         while (Proceed && FT != BBI.FalseBB->end())
484           if (!FT->isPredicable()) {
485             Proceed = false;
486             break; // Can't if-convert. Abort!
487           }
488       }
489     }
490   }
491
492   if (!Proceed)
493     return false;
494
495   // Remove the duplicated instructions from the 'true' block.
496   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
497     Dups[i]->eraseFromParent();
498     --TrueBBI.NonPredSize;
499   }
500     
501   // Predicate the 'true' block after removing its branch.
502   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
503   PredicateBlock(TrueBBI, BBI.BrCond);
504
505   // Add a conditional branch to 'true' successor if needed.
506   if (TrueNeedCBr && TrueBBI.ModifyPredicate &&
507       isNextBlock(BBI.TrueBB, *BBI.TrueBB->succ_begin()))
508     TrueNeedCBr = false;
509   if (TrueNeedCBr)
510     TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL, BBI.BrCond);
511
512   // Predicate the 'false' block.
513   PredicateBlock(FalseBBI, RevCond, true);
514
515   // Add a conditional branch to 'false' successor if needed.
516   if (FalseNeedCBr && !TrueBBI.ModifyPredicate &&
517       isNextBlock(BBI.FalseBB, *BBI.FalseBB->succ_begin()))
518     FalseNeedCBr = false;
519   if (FalseNeedCBr)
520     TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
521                       RevCond);
522
523   // Merge the 'true' and 'false' blocks by copying the instructions
524   // from the 'false' block to the 'true' block. That is, unless the true
525   // block would clobber the predicate, in that case, do the opposite.
526   BBInfo *CvtBBI;
527   if (!TrueBBI.ModifyPredicate) {
528     MergeBlocks(TrueBBI, FalseBBI);
529     CvtBBI = &TrueBBI;
530   } else {
531     MergeBlocks(FalseBBI, TrueBBI);
532     CvtBBI = &FalseBBI;
533   }
534
535   // Remove the conditional branch from entry to the blocks.
536   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
537
538   bool OkToIfcvt = true;
539   // Merge the combined block into the entry of the diamond if the entry
540   // block is its only predecessor. Otherwise, insert an unconditional
541   // branch from entry to the if-converted block.
542   if (CvtBBI->BB->pred_size() == 1) {
543     MergeBlocks(BBI, *CvtBBI);
544     CvtBBI = &BBI;
545     OkToIfcvt = false;
546   } else {
547     std::vector<MachineOperand> NoCond;
548     TII->InsertBranch(*BBI.BB, CvtBBI->BB, NULL, NoCond);
549   }
550
551   // If the if-converted block fallthrough into the tail block, then
552   // fold the tail block in as well.
553   if (BBI.TailBB && CvtBBI->BB->succ_size() == 1) {
554     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
555     BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
556     MergeBlocks(*CvtBBI, TailBBI);
557     TailBBI.Kind = ICDead;
558   }
559
560   // Update block info. BB may be iteratively if-converted.
561   if (OkToIfcvt) {
562     BBI.Kind = ICNotClassfied;
563     BBI.TrueBB = BBI.FalseBB = NULL;
564     BBI.BrCond.clear();
565     TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
566     InvalidatePreds(BBI.BB);
567   }
568   TrueBBI.Kind = ICDead;
569   FalseBBI.Kind = ICDead;
570
571   // FIXME: Must maintain LiveIns.
572   NumIfConvBBs += 2;
573   return true;
574 }
575
576 /// PredicateBlock - Predicate every instruction in the block with the specified
577 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
578 void IfConverter::PredicateBlock(BBInfo &BBI,
579                                  std::vector<MachineOperand> &Cond,
580                                  bool IgnoreTerm) {
581   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
582        I != E; ++I) {
583     MachineInstr *MI = I;
584     if (IgnoreTerm && TII->isTerminatorInstr(MI->getOpcode()))
585       continue;
586     if (TII->isPredicated(MI))
587       continue;
588     if (!TII->PredicateInstruction(MI, Cond)) {
589       cerr << "Unable to predication " << *I << "!\n";
590       abort();
591     }
592   }
593
594   BBI.NonPredSize = 0;
595 }
596
597 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
598 ///
599 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
600   ToBBI.BB->splice(ToBBI.BB->end(),
601                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
602
603   // If FromBBI is previously a successor, remove it from ToBBI's successor
604   // list and update its TrueBB / FalseBB field if needed.
605   if (ToBBI.BB->isSuccessor(FromBBI.BB))
606     ToBBI.BB->removeSuccessor(FromBBI.BB);
607
608   // Transfer preds / succs and update size.
609   TransferPreds(ToBBI.BB, FromBBI.BB);
610   TransferSuccs(ToBBI.BB, FromBBI.BB);
611   ToBBI.NonPredSize += FromBBI.NonPredSize;
612   FromBBI.NonPredSize = 0;
613 }