Fix some subtle bugs: bug during succeessor copying; incorrectly updating states...
[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 "ifcvt"
15 #include "llvm/Function.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
26
27 STATISTIC(NumSimple,    "Number of simple if-conversions performed");
28 STATISTIC(NumSimpleRev, "Number of simple (reversed) if-conversions performed");
29 STATISTIC(NumTriangle,  "Number of triangle if-conversions performed");
30 STATISTIC(NumDiamonds,  "Number of diamond if-conversions performed");
31 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
32
33 namespace {
34   class IfConverter : public MachineFunctionPass {
35     enum BBICKind {
36       ICNotAnalyzed,   // BB has not been analyzed.
37       ICReAnalyze,     // BB must be re-analyzed.
38       ICNotClassfied,  // BB data valid, but not classified.
39       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
40       ICSimpleFalse,   // Same as ICSimple, but on the false path.
41       ICTriangle,      // BB is entry of a triangle sub-CFG.
42       ICDiamond,       // BB is entry of a diamond sub-CFG.
43       ICChild,         // BB is part of the sub-CFG that'll be predicated.
44       ICDead           // BB has been converted and merged, it's now dead.
45     };
46
47     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
48     /// if-conversion feasibility analysis. This includes results from
49     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
50     /// classification, and common tail block of its successors (if it's a
51     /// diamond shape), its size, whether it's predicable, and whether any
52     /// instruction can clobber the 'would-be' predicate.
53     ///
54     /// Kind            - Type of block. See BBICKind.
55     /// NonPredSize     - Number of non-predicated instructions.
56     /// IsAnalyzable    - True if AnalyzeBranch() returns false.
57     /// ModifyPredicate - FIXME: Not used right now. True if BB would modify
58     ///                   the predicate (e.g. has cmp, call, etc.)
59     /// BB              - Corresponding MachineBasicBlock.
60     /// TrueBB / FalseBB- See AnalyzeBranch().
61     /// BrCond          - Conditions for end of block conditional branches.
62     /// Predicate       - Predicate used in the BB.
63     struct BBInfo {
64       BBICKind Kind;
65       unsigned NonPredSize;
66       bool IsAnalyzable;
67       bool ModifyPredicate;
68       MachineBasicBlock *BB;
69       MachineBasicBlock *TrueBB;
70       MachineBasicBlock *FalseBB;
71       MachineBasicBlock *TailBB;
72       std::vector<MachineOperand> BrCond;
73       std::vector<MachineOperand> Predicate;
74       BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
75                  IsAnalyzable(false), ModifyPredicate(false),
76                  BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
77     };
78
79     /// Roots - Basic blocks that do not have successors. These are the starting
80     /// points of Graph traversal.
81     std::vector<MachineBasicBlock*> Roots;
82
83     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
84     /// basic block number.
85     std::vector<BBInfo> BBAnalysis;
86
87     const TargetLowering *TLI;
88     const TargetInstrInfo *TII;
89     bool MadeChange;
90   public:
91     static char ID;
92     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
93
94     virtual bool runOnMachineFunction(MachineFunction &MF);
95     virtual const char *getPassName() const { return "If converter"; }
96
97   private:
98     bool ReverseBranchCondition(BBInfo &BBI);
99     void StructuralAnalysis(MachineBasicBlock *BB);
100     bool FeasibilityAnalysis(BBInfo &BBI,
101                              std::vector<MachineOperand> &Cond,
102                              bool IgnoreTerm = false);
103     bool AttemptRestructuring(BBInfo &BBI);
104     bool AnalyzeBlocks(MachineFunction &MF,
105                        std::vector<BBInfo*> &Candidates);
106     void ReTryPreds(MachineBasicBlock *BB);
107     bool IfConvertSimple(BBInfo &BBI);
108     bool IfConvertTriangle(BBInfo &BBI);
109     bool IfConvertDiamond(BBInfo &BBI);
110     void PredicateBlock(BBInfo &BBI,
111                         std::vector<MachineOperand> &Cond,
112                         bool IgnoreTerm = false);
113     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
114
115     // IfcvtCandidateCmp - Used to sort if-conversion candidates.
116     static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
117       // Favor diamond over triangle, etc.
118       return (unsigned)C1->Kind < (unsigned)C2->Kind;
119     }
120   };
121   char IfConverter::ID = 0;
122 }
123
124 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
125
126 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
127   TLI = MF.getTarget().getTargetLowering();
128   TII = MF.getTarget().getInstrInfo();
129   if (!TII) return false;
130
131   DOUT << "\nIfcvt: function \'" << MF.getFunction()->getName() << "\'\n";
132
133   MF.RenumberBlocks();
134   BBAnalysis.resize(MF.getNumBlockIDs());
135
136   // Look for root nodes, i.e. blocks without successors.
137   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
138     if (I->succ_size() == 0)
139       Roots.push_back(I);
140
141   std::vector<BBInfo*> Candidates;
142   MadeChange = false;
143   while (true) {
144     // Do an intial analysis for each basic block and finding all the potential
145     // candidates to perform if-convesion.
146     bool Change = AnalyzeBlocks(MF, Candidates);
147     while (!Candidates.empty()) {
148       BBInfo &BBI = *Candidates.back();
149       Candidates.pop_back();
150
151       bool RetVal = false;
152       switch (BBI.Kind) {
153       default: assert(false && "Unexpected!");
154         break;
155       case ICReAnalyze:
156         // One or more of 'children' have been modified, abort!
157       case ICDead:
158         // Block has been already been if-converted, abort!
159         break;
160       case ICSimple:
161       case ICSimpleFalse:
162         DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
163              << "): BB#" << BBI.BB->getNumber() << " ";
164         RetVal = IfConvertSimple(BBI);
165         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
166         if (RetVal)
167           if (BBI.Kind == ICSimple) NumSimple++;
168           else                      NumSimpleRev++;
169        break;
170       case ICTriangle:
171         DOUT << "Ifcvt (Triangle): BB#" << BBI.BB->getNumber() << " ";
172         RetVal = IfConvertTriangle(BBI);
173         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
174         if (RetVal) NumTriangle++;
175         break;
176       case ICDiamond:
177         DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " ";
178         RetVal = IfConvertDiamond(BBI);
179         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
180         if (RetVal) NumDiamonds++;
181         break;
182       }
183       Change |= RetVal;
184     }
185
186     if (!Change)
187       break;
188     MadeChange |= Change;
189   }
190
191   Roots.clear();
192   BBAnalysis.clear();
193
194   return MadeChange;
195 }
196
197 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
198                                          MachineBasicBlock *TrueBB) {
199   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
200          E = BB->succ_end(); SI != E; ++SI) {
201     MachineBasicBlock *SuccBB = *SI;
202     if (SuccBB != TrueBB)
203       return SuccBB;
204   }
205   return NULL;
206 }
207
208 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
209   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
210     TII->RemoveBranch(*BBI.BB);
211     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
212     std::swap(BBI.TrueBB, BBI.FalseBB);
213     return true;
214   }
215   return false;
216 }
217
218 /// StructuralAnalysis - Analyze the structure of the sub-CFG starting from
219 /// the specified block. Record its successors and whether it looks like an
220 /// if-conversion candidate.
221 void IfConverter::StructuralAnalysis(MachineBasicBlock *BB) {
222   BBInfo &BBI = BBAnalysis[BB->getNumber()];
223
224   if (BBI.Kind == ICReAnalyze) {
225     BBI.BrCond.clear();
226     BBI.TrueBB = BBI.FalseBB = NULL;
227   } else {
228     if (BBI.Kind != ICNotAnalyzed)
229       return;  // Already analyzed.
230     BBI.BB = BB;
231     BBI.NonPredSize = std::distance(BB->begin(), BB->end());
232   }
233
234   // Look for 'root' of a simple (non-nested) triangle or diamond.
235   BBI.Kind = ICNotClassfied;
236   BBI.IsAnalyzable =
237     !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
238   if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
239     return;
240
241   StructuralAnalysis(BBI.TrueBB);
242   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
243
244   // No false branch. This BB must end with a conditional branch and a
245   // fallthrough.
246   if (!BBI.FalseBB)
247     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
248   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
249
250   StructuralAnalysis(BBI.FalseBB);
251   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
252   
253   // Look for more opportunities to if-convert a triangle. Try to restructure
254   // the CFG to form a triangle with the 'false' path.
255   std::vector<MachineOperand> RevCond(BBI.BrCond);
256   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
257   if (FalseBBI.FalseBB) {
258     if (TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB)
259       return;
260     std::vector<MachineOperand> Cond(BBI.BrCond);
261     if (CanRevCond &&
262         FalseBBI.TrueBB && FalseBBI.BB->pred_size() == 1 &&
263         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
264       std::vector<MachineOperand> FalseCond(FalseBBI.BrCond);
265       if (FalseBBI.TrueBB == BBI.TrueBB &&
266           TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
267         // Reverse 'true' and 'false' paths.
268         ReverseBranchCondition(BBI);
269         BBI.Kind = ICTriangle;
270         FalseBBI.Kind = ICChild;
271       } else if (FalseBBI.FalseBB == BBI.TrueBB &&
272                  !TII->ReverseBranchCondition(FalseCond) &&
273                  TII->SubsumesPredicate(FalseCond, BBI.BrCond)) {
274         // Reverse 'false' block's 'true' and 'false' paths and then
275         // reverse 'true' and 'false' paths.
276         ReverseBranchCondition(FalseBBI);
277         ReverseBranchCondition(BBI);
278         BBI.Kind = ICTriangle;
279         FalseBBI.Kind = ICChild;
280       }
281     }
282   } else if (TrueBBI.TrueBB == FalseBBI.TrueBB && CanRevCond &&
283              TrueBBI.BB->pred_size() == 1 &&
284              TrueBBI.BB->pred_size() == 1 &&
285              // Check the 'true' and 'false' blocks if either isn't ended with
286              // a branch. If the block does not fallthrough to another block
287              // then we need to add a branch to its successor.
288              !(TrueBBI.ModifyPredicate &&
289                !TrueBBI.TrueBB && TrueBBI.BB->succ_size()) &&
290              !(FalseBBI.ModifyPredicate &&
291                !FalseBBI.TrueBB && FalseBBI.BB->succ_size()) &&
292              FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
293              FeasibilityAnalysis(FalseBBI, RevCond)) {
294     // Diamond:
295     //   EBB
296     //   / \_
297     //  |   |
298     // TBB FBB
299     //   \ /
300     //  TailBB
301     // Note MBB can be empty in case both TBB and FBB are return blocks.
302     BBI.Kind = ICDiamond;
303     TrueBBI.Kind = FalseBBI.Kind = ICChild;
304     BBI.TailBB = TrueBBI.TrueBB;
305   } else {
306     // FIXME: Consider duplicating if BB is small.
307     bool TryTriangle = TrueBBI.TrueBB && TrueBBI.TrueBB == BBI.FalseBB &&
308                        BBI.TrueBB->pred_size() == 1;
309     bool TrySimple = TrueBBI.BrCond.size() == 0 && BBI.TrueBB->pred_size() == 1;
310     if ((TryTriangle || TrySimple) &&
311         FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
312       if (TryTriangle) {
313         // Triangle:
314         //   EBB
315         //   | \_
316         //   |  |
317         //   | TBB
318         //   |  /
319         //   FBB
320         BBI.Kind = ICTriangle;
321         TrueBBI.Kind = ICChild;
322       } else {
323         // Simple (split, no rejoin):
324         //   EBB
325         //   | \_
326         //   |  |
327         //   | TBB---> exit
328         //   |    
329         //   FBB
330         BBI.Kind = ICSimple;
331         TrueBBI.Kind = ICChild;
332       }
333     } else if (FalseBBI.BrCond.size() == 0 && BBI.FalseBB->pred_size() == 1) {
334       // Try 'simple' on the other path...
335       std::vector<MachineOperand> RevCond(BBI.BrCond);
336       if (TII->ReverseBranchCondition(RevCond))
337         assert(false && "Unable to reverse branch condition!");
338       if (FeasibilityAnalysis(FalseBBI, RevCond)) {
339         BBI.Kind = ICSimpleFalse;
340         FalseBBI.Kind = ICChild;
341       }
342     }
343   }
344   return;
345 }
346
347 /// FeasibilityAnalysis - Determine if the block is predicable. In most
348 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
349 /// Also checks if the block contains any instruction which can clobber a
350 /// predicate (e.g. condition code register). If so, the block is not
351 /// predicable unless it's the last instruction. If IgnoreTerm is true then
352 /// all the terminator instructions are skipped.
353 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
354                                       std::vector<MachineOperand> &Cond,
355                                       bool IgnoreTerm) {
356   // If the block is dead, or it is going to be the entry block of a sub-CFG
357   // that will be if-converted, then it cannot be predicated.
358   if (BBI.Kind != ICNotAnalyzed &&
359       BBI.Kind != ICNotClassfied &&
360       BBI.Kind != ICChild)
361     return false;
362
363   // Check predication threshold.
364   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
365     return false;
366
367   // If it is already predicated, check if its predicate subsumes the new
368   // predicate.
369   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Cond))
370     return false;
371
372   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
373        I != E; ++I) {
374     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
375       continue;
376     // TODO: check if instruction clobbers predicate.
377     if (!I->isPredicable())
378       return false;
379   }
380
381   return true;
382 }
383
384 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
385 /// expose more if-conversion opportunities. e.g.
386 ///
387 ///                cmp
388 ///                b le BB1
389 ///                /  \____
390 ///               /        |
391 ///             cmp        |
392 ///             b eq BB1   |
393 ///              /  \____  |
394 ///             /        \ |
395 ///                      BB1
396 ///  ==>
397 ///
398 ///                cmp
399 ///                b eq BB1
400 ///                /  \____
401 ///               /        |
402 ///             cmp        |
403 ///             b le BB1   |
404 ///              /  \____  |
405 ///             /        \ |
406 ///                      BB1
407 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
408   return false;
409 }
410
411 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
412 /// candidates. It returns true if any CFG restructuring is done to expose more
413 /// if-conversion opportunities.
414 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
415                                 std::vector<BBInfo*> &Candidates) {
416   bool Change = false;
417   std::set<MachineBasicBlock*> Visited;
418   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
419     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
420            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
421       MachineBasicBlock *BB = *I;
422       StructuralAnalysis(BB);
423       BBInfo &BBI = BBAnalysis[BB->getNumber()];
424       switch (BBI.Kind) {
425         case ICSimple:
426         case ICSimpleFalse:
427         case ICTriangle:
428         case ICDiamond:
429           Candidates.push_back(&BBI);
430           break;
431         default:
432           Change |= AttemptRestructuring(BBI);
433           break;
434       }
435     }
436   }
437
438   // Sort to favor more complex ifcvt scheme.
439   std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
440
441   return Change;
442 }
443
444 /// isNextBlock - Returns true either if ToBB the next block after BB or
445 /// that all the intervening blocks are empty.
446 static bool isNextBlock(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
447   MachineFunction *MF = BB->getParent();
448   MachineFunction::iterator I = BB;
449   while (++I != MF->end() && I != MachineFunction::iterator(ToBB))
450     if (!I->empty())
451       return false;
452   return true;
453 }
454
455 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
456 /// to determine if it can be if-converted.
457 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
458   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
459          E = BB->pred_end(); PI != E; ++PI) {
460     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
461     PBBI.Kind = ICReAnalyze;
462   }
463 }
464
465 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
466 ///
467 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
468                                const TargetInstrInfo *TII) {
469   std::vector<MachineOperand> NoCond;
470   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
471 }
472
473 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
474 ///
475 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
476   bool ReverseCond = BBI.Kind == ICSimpleFalse;
477
478   BBI.Kind = ICNotClassfied;
479
480   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
481   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
482   BBInfo *CvtBBI = &TrueBBI;
483   BBInfo *NextBBI = &FalseBBI;
484
485   std::vector<MachineOperand> Cond(BBI.BrCond);
486   if (ReverseCond) {
487     std::swap(CvtBBI, NextBBI);
488     TII->ReverseBranchCondition(Cond);
489   }
490
491   PredicateBlock(*CvtBBI, Cond);
492   // If the 'true' block ends without a branch, add a conditional branch
493   // to its successor unless that happens to be the 'false' block.
494   if (CvtBBI->IsAnalyzable && CvtBBI->TrueBB == NULL) {
495     assert(CvtBBI->BB->succ_size() == 1 && "Unexpected!");
496     MachineBasicBlock *SuccBB = *CvtBBI->BB->succ_begin();
497     if (SuccBB != NextBBI->BB)
498       TII->InsertBranch(*CvtBBI->BB, SuccBB, NULL, Cond);
499   }
500
501   // Merge converted block into entry block. Also add an unconditional branch
502   // to the 'false' branch.
503   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
504   MergeBlocks(BBI, *CvtBBI);
505   if (!isNextBlock(BBI.BB, NextBBI->BB))
506     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
507   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
508
509   // Update block info. BB can be iteratively if-converted.
510   BBI.Kind = ICReAnalyze;
511   ReTryPreds(BBI.BB);
512   CvtBBI->Kind = ICDead;
513
514   // FIXME: Must maintain LiveIns.
515   return true;
516 }
517
518 /// IfConvertTriangle - If convert a triangle sub-CFG.
519 ///
520 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
521   BBI.Kind = ICNotClassfied;
522
523   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
524
525   // Predicate the 'true' block after removing its branch.
526   TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
527   PredicateBlock(TrueBBI, BBI.BrCond);
528
529   // If 'true' block has a 'false' successor, add an exit branch to it.
530   if (TrueBBI.FalseBB) {
531     std::vector<MachineOperand> RevCond(TrueBBI.BrCond);
532     if (TII->ReverseBranchCondition(RevCond))
533       assert(false && "Unable to reverse branch condition!");
534     TII->InsertBranch(*BBI.TrueBB, TrueBBI.FalseBB, NULL, RevCond);
535   }
536
537   // Join the 'true' and 'false' blocks if the 'false' block has no other
538   // predecessors. Otherwise, add a unconditional branch from 'true' to 'false'.
539   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
540   bool FalseBBDead = false;
541   if (FalseBBI.BB->pred_size() == 2) {
542     MergeBlocks(TrueBBI, FalseBBI);
543     FalseBBDead = true;
544   } else if (!isNextBlock(TrueBBI.BB, FalseBBI.BB))
545     InsertUncondBranch(TrueBBI.BB, FalseBBI.BB, TII);
546
547   // Now merge the entry of the triangle with the true block.
548   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
549   MergeBlocks(BBI, TrueBBI);
550   std::copy(BBI.BrCond.begin(), BBI.BrCond.end(),
551             std::back_inserter(BBI.Predicate));
552
553   // Update block info. BB can be iteratively if-converted.
554   BBI.Kind = ICReAnalyze;
555   ReTryPreds(BBI.BB);
556   TrueBBI.Kind = ICDead;
557   if (FalseBBDead)
558     FalseBBI.Kind = ICDead;
559
560   // FIXME: Must maintain LiveIns.
561   return true;
562 }
563
564 /// IfConvertDiamond - If convert a diamond sub-CFG.
565 ///
566 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
567   BBI.Kind = ICNotClassfied;
568
569   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
570   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
571
572   SmallVector<MachineInstr*, 2> Dups;
573   if (!BBI.TailBB) {
574     // No common merge block. Check if the terminators (e.g. return) are
575     // the same or predicable.
576     MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
577     MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
578     while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
579       if (TT->isIdenticalTo(FT))
580         Dups.push_back(TT);  // Will erase these later.
581       else if (!TT->isPredicable() && !FT->isPredicable())
582         return false; // Can't if-convert. Abort!
583       ++TT;
584       ++FT;
585     }
586
587     // One of the two pathes have more terminators, make sure they are
588     // all predicable.
589     while (TT != BBI.TrueBB->end()) {
590       if (!TT->isPredicable()) {
591         return false; // Can't if-convert. Abort!
592       }
593       ++TT;
594     }
595     while (FT != BBI.FalseBB->end()) {
596       if (!FT->isPredicable()) {
597         return false; // Can't if-convert. Abort!
598       }
599       ++FT;
600     }
601   }
602
603   // Remove the duplicated instructions from the 'true' block.
604   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
605     Dups[i]->eraseFromParent();
606     --TrueBBI.NonPredSize;
607   }
608     
609   // Check the 'true' and 'false' blocks if either isn't ended with a branch.
610   // Either the block fallthrough to another block or it ends with a
611   // return. If it's the former, add a branch to its successor.
612   bool TrueNeedBr  = !TrueBBI.TrueBB && BBI.TrueBB->succ_size();
613   bool FalseNeedBr = !FalseBBI.TrueBB && BBI.FalseBB->succ_size(); 
614
615   // Merge the 'true' and 'false' blocks by copying the instructions
616   // from the 'false' block to the 'true' block. That is, unless the true
617   // block would clobber the predicate, in that case, do the opposite.
618   std::vector<MachineOperand> RevCond(BBI.BrCond);
619   TII->ReverseBranchCondition(RevCond);
620   BBInfo *CvtBBI;
621   if (!TrueBBI.ModifyPredicate) {
622     // Predicate the 'true' block after removing its branch.
623     TrueBBI.NonPredSize -= TII->RemoveBranch(*BBI.TrueBB);
624     PredicateBlock(TrueBBI, BBI.BrCond);
625
626     // Predicate the 'false' block.
627     PredicateBlock(FalseBBI, RevCond, true);
628
629     if (TrueNeedBr)
630       TII->InsertBranch(*BBI.TrueBB, *BBI.TrueBB->succ_begin(), NULL,
631                         BBI.BrCond);
632     // Add an unconditional branch from 'false' to to 'false' successor if it
633     // will not be the fallthrough block.
634     if (FalseNeedBr &&
635         !isNextBlock(BBI.BB, *BBI.FalseBB->succ_begin()))
636       InsertUncondBranch(BBI.FalseBB, *BBI.FalseBB->succ_begin(), TII);
637     MergeBlocks(TrueBBI, FalseBBI);
638     CvtBBI = &TrueBBI;
639   } else {
640     // Predicate the 'false' block after removing its branch.
641     FalseBBI.NonPredSize -= TII->RemoveBranch(*BBI.FalseBB);
642     PredicateBlock(FalseBBI, RevCond);
643
644     // Predicate the 'false' block.
645     PredicateBlock(TrueBBI, BBI.BrCond, true);
646
647     // Add a conditional branch from 'false' to 'false' successor if needed.
648     if (FalseNeedBr)
649       TII->InsertBranch(*BBI.FalseBB, *BBI.FalseBB->succ_begin(), NULL,
650                         RevCond);
651     // Add an unconditional branch from 'true' to to 'true' successor if it
652     // will not be the fallthrough block.
653     if (TrueNeedBr &&
654         !isNextBlock(BBI.BB, *BBI.TrueBB->succ_begin()))
655       InsertUncondBranch(BBI.TrueBB, *BBI.TrueBB->succ_begin(), TII);
656     MergeBlocks(FalseBBI, TrueBBI);
657     CvtBBI = &FalseBBI;
658   }
659
660   // Remove the conditional branch from entry to the blocks.
661   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
662
663   bool OkToIfcvt = true;
664   // Merge the combined block into the entry of the diamond if the entry
665   // block is its only predecessor. Otherwise, insert an unconditional
666   // branch from entry to the if-converted block.
667   if (CvtBBI->BB->pred_size() == 1) {
668     MergeBlocks(BBI, *CvtBBI);
669     CvtBBI = &BBI;
670     OkToIfcvt = false;
671   } else if (!isNextBlock(BBI.BB, CvtBBI->BB))
672     InsertUncondBranch(BBI.BB, CvtBBI->BB, TII);
673
674   // If the if-converted block fallthrough or unconditionally branch into the
675   // tail block, and the tail block does not have other predecessors, then
676   // fold the tail block in as well.
677   if (BBI.TailBB &&
678       BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
679     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
680     BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
681     MergeBlocks(*CvtBBI, TailBBI);
682     TailBBI.Kind = ICDead;
683   }
684
685   // Update block info. BB may be iteratively if-converted.
686   if (OkToIfcvt) {
687     BBI.Kind = ICReAnalyze;
688     ReTryPreds(BBI.BB);
689   }
690   TrueBBI.Kind = ICDead;
691   FalseBBI.Kind = ICDead;
692
693   // FIXME: Must maintain LiveIns.
694   return true;
695 }
696
697 /// PredicateBlock - Predicate every instruction in the block with the specified
698 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
699 void IfConverter::PredicateBlock(BBInfo &BBI,
700                                  std::vector<MachineOperand> &Cond,
701                                  bool IgnoreTerm) {
702   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
703        I != E; ++I) {
704     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
705       continue;
706     if (TII->isPredicated(I))
707       continue;
708     if (!TII->PredicateInstruction(I, Cond)) {
709       cerr << "Unable to predicate " << *I << "!\n";
710       abort();
711     }
712   }
713
714   BBI.NonPredSize = 0;
715   NumIfConvBBs++;
716 }
717
718 /// TransferPreds - Transfer all the predecessors of FromBB to ToBB.
719 ///
720 static void TransferPreds(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
721   for (MachineBasicBlock::pred_iterator I = FromBB->pred_begin(),
722          E = FromBB->pred_end(); I != E; ++I) {
723     MachineBasicBlock *Pred = *I;
724     Pred->removeSuccessor(FromBB);
725     if (!Pred->isSuccessor(ToBB))
726       Pred->addSuccessor(ToBB);
727   }
728 }
729
730 /// TransferSuccs - Transfer all the successors of FromBB to ToBB.
731 ///
732 static void TransferSuccs(MachineBasicBlock *ToBB, MachineBasicBlock *FromBB) {
733   for (MachineBasicBlock::succ_iterator I = FromBB->succ_begin(),
734          E = FromBB->succ_end(); I != E; ++I) {
735     MachineBasicBlock *Succ = *I;
736     FromBB->removeSuccessor(Succ);
737     if (!ToBB->isSuccessor(Succ))
738       ToBB->addSuccessor(Succ);
739   }
740 }
741
742 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
743 ///
744 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
745   ToBBI.BB->splice(ToBBI.BB->end(),
746                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
747
748   // If FromBBI is previously a successor, remove it from ToBBI's successor
749   // list and update its TrueBB / FalseBB field if needed.
750   if (ToBBI.BB->isSuccessor(FromBBI.BB))
751     ToBBI.BB->removeSuccessor(FromBBI.BB);
752
753   // Redirect all branches to FromBB to ToBB.
754   for (MachineBasicBlock::pred_iterator I = FromBBI.BB->pred_begin(),
755          E = FromBBI.BB->pred_end(); I != E; ++I)
756     (*I)->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
757
758   // Transfer preds / succs and update size.
759   TransferPreds(ToBBI.BB, FromBBI.BB);
760   TransferSuccs(ToBBI.BB, FromBBI.BB);
761   ToBBI.NonPredSize += FromBBI.NonPredSize;
762   FromBBI.NonPredSize = 0;
763 }