3969a52cc5ba9758ff70368bed4c3e0810297b6c
[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/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
26 using namespace llvm;
27
28 namespace {
29   // Hidden options for help debugging.
30   cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
31   cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
32   cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
33   cl::opt<bool> DisableSimple("disable-ifcvt-simple", 
34                               cl::init(false), cl::Hidden);
35   cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false", 
36                                cl::init(false), cl::Hidden);
37   cl::opt<bool> DisableTriangle("disable-ifcvt-triangle", 
38                                 cl::init(false), cl::Hidden);
39   cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false", 
40                                  cl::init(false), cl::Hidden);
41   cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev", 
42                                   cl::init(false), cl::Hidden);
43   cl::opt<bool> DisableDiamond("disable-ifcvt-diamond", 
44                                cl::init(false), cl::Hidden);
45 }
46
47 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
48 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
49 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
50 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
51 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
52 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
53 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
54
55 namespace {
56   class IfConverter : public MachineFunctionPass {
57     enum BBICKind {
58       ICNotAnalyzed,   // BB has not been analyzed.
59       ICReAnalyze,     // BB must be re-analyzed.
60       ICNotClassfied,  // BB data valid, but not classified.
61       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
62       ICSimpleFalse,   // Same as ICSimple, but on the false path.
63       ICTriangle,      // BB is entry of a triangle sub-CFG.
64       ICTriangleFalse, // Same as ICTriangle, but on the false path.
65       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
66       ICDiamond,       // BB is entry of a diamond sub-CFG.
67       ICChild,         // BB is part of the sub-CFG that'll be predicated.
68       ICDead           // BB cannot be if-converted again.
69     };
70
71     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
72     /// if-conversion feasibility analysis. This includes results from
73     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
74     /// classification, and common tail block of its successors (if it's a
75     /// diamond shape), its size, whether it's predicable, and whether any
76     /// instruction can clobber the 'would-be' predicate.
77     ///
78     /// Kind            - Type of block. See BBICKind.
79     /// NonPredSize     - Number of non-predicated instructions.
80     /// IsAnalyzable    - True if AnalyzeBranch() returns false.
81     /// ModifyPredicate - True if BB would modify the predicate (e.g. has
82     ///                   cmp, call, etc.)
83     /// BB              - Corresponding MachineBasicBlock.
84     /// TrueBB / FalseBB- See AnalyzeBranch().
85     /// BrCond          - Conditions for end of block conditional branches.
86     /// Predicate       - Predicate used in the BB.
87     struct BBInfo {
88       BBICKind Kind;
89       unsigned NonPredSize;
90       bool IsAnalyzable;
91       bool HasFallThrough;
92       bool ModifyPredicate;
93       MachineBasicBlock *BB;
94       MachineBasicBlock *TrueBB;
95       MachineBasicBlock *FalseBB;
96       MachineBasicBlock *TailBB;
97       std::vector<MachineOperand> BrCond;
98       std::vector<MachineOperand> Predicate;
99       BBInfo() : Kind(ICNotAnalyzed), NonPredSize(0),
100                  IsAnalyzable(false), HasFallThrough(false),
101                  ModifyPredicate(false),
102                  BB(0), TrueBB(0), FalseBB(0), TailBB(0) {}
103     };
104
105     /// Roots - Basic blocks that do not have successors. These are the starting
106     /// points of Graph traversal.
107     std::vector<MachineBasicBlock*> Roots;
108
109     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
110     /// basic block number.
111     std::vector<BBInfo> BBAnalysis;
112
113     const TargetLowering *TLI;
114     const TargetInstrInfo *TII;
115     bool MadeChange;
116   public:
117     static char ID;
118     IfConverter() : MachineFunctionPass((intptr_t)&ID) {}
119
120     virtual bool runOnMachineFunction(MachineFunction &MF);
121     virtual const char *getPassName() const { return "If converter"; }
122
123   private:
124     bool ReverseBranchCondition(BBInfo &BBI);
125     bool ValidSimple(BBInfo &TrueBBI) const;
126     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
127                        bool FalseBranch = false) const;
128     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const;
129     void ScanInstructions(BBInfo &BBI);
130     void AnalyzeBlock(MachineBasicBlock *BB);
131     bool FeasibilityAnalysis(BBInfo &BBI, std::vector<MachineOperand> &Cond,
132                              bool isTriangle = false, bool RevBranch = false);
133     bool AttemptRestructuring(BBInfo &BBI);
134     bool AnalyzeBlocks(MachineFunction &MF,
135                        std::vector<BBInfo*> &Candidates);
136     void ReTryPreds(MachineBasicBlock *BB);
137     void RemoveExtraEdges(BBInfo &BBI);
138     bool IfConvertSimple(BBInfo &BBI);
139     bool IfConvertTriangle(BBInfo &BBI);
140     bool IfConvertDiamond(BBInfo &BBI);
141     void PredicateBlock(BBInfo &BBI,
142                         std::vector<MachineOperand> &Cond,
143                         bool IgnoreTerm = false);
144     void MergeBlocks(BBInfo &TrueBBI, BBInfo &FalseBBI);
145
146     // blockAlwaysFallThrough - Block ends without a terminator.
147     bool blockAlwaysFallThrough(BBInfo &BBI) const {
148       return BBI.IsAnalyzable && BBI.TrueBB == NULL;
149     }
150
151     // IfcvtCandidateCmp - Used to sort if-conversion candidates.
152     static bool IfcvtCandidateCmp(BBInfo* C1, BBInfo* C2){
153       // Favor diamond over triangle, etc.
154       return (unsigned)C1->Kind < (unsigned)C2->Kind;
155     }
156   };
157   char IfConverter::ID = 0;
158 }
159
160 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
161
162 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
163   TLI = MF.getTarget().getTargetLowering();
164   TII = MF.getTarget().getInstrInfo();
165   if (!TII) return false;
166
167   static int FnNum = -1;
168   DOUT << "\nIfcvt: function (" << ++FnNum <<  ") \'"
169        << MF.getFunction()->getName() << "\'";
170
171   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
172     DOUT << " skipped\n";
173     return false;
174   }
175   DOUT << "\n";
176
177   MF.RenumberBlocks();
178   BBAnalysis.resize(MF.getNumBlockIDs());
179
180   // Look for root nodes, i.e. blocks without successors.
181   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
182     if (I->succ_size() == 0)
183       Roots.push_back(I);
184
185   std::vector<BBInfo*> Candidates;
186   MadeChange = false;
187   while (IfCvtLimit == -1 || (int)NumIfConvBBs < IfCvtLimit) {
188     // Do an intial analysis for each basic block and finding all the potential
189     // candidates to perform if-convesion.
190     bool Change = AnalyzeBlocks(MF, Candidates);
191     while (!Candidates.empty()) {
192       BBInfo &BBI = *Candidates.back();
193       Candidates.pop_back();
194
195       bool RetVal = false;
196       switch (BBI.Kind) {
197       default: assert(false && "Unexpected!");
198         break;
199       case ICReAnalyze:
200         // One or more of 'children' have been modified, abort!
201       case ICDead:
202         // Block has been already been if-converted, abort!
203         break;
204       case ICSimple:
205       case ICSimpleFalse: {
206         bool isFalse = BBI.Kind == ICSimpleFalse;
207         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
208         DOUT << "Ifcvt (Simple" << (BBI.Kind == ICSimpleFalse ? " false" : "")
209              << "): BB#" << BBI.BB->getNumber() << " ("
210              << ((BBI.Kind == ICSimpleFalse)
211                  ? BBI.FalseBB->getNumber() : BBI.TrueBB->getNumber()) << ") ";
212         RetVal = IfConvertSimple(BBI);
213         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
214         if (RetVal)
215           if (isFalse) NumSimpleFalse++;
216           else         NumSimple++;
217        break;
218       }
219       case ICTriangle:
220       case ICTriangleFalse:
221       case ICTriangleFRev: {
222         bool isFalse = BBI.Kind == ICTriangleFalse;
223         bool isFalseRev = BBI.Kind == ICTriangleFRev;
224         if (DisableTriangle && !isFalse && !isFalseRev) break;
225         if (DisableTriangleF && isFalse) break;
226         if (DisableTriangleFR && isFalseRev) break;
227         DOUT << "Ifcvt (Triangle";
228         if (isFalse)
229           DOUT << " false";
230         if (isFalseRev)
231           DOUT << " false/rev";
232         DOUT << "): BB#" << BBI.BB->getNumber() << " (T:"
233              << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber()
234              << ") ";
235         RetVal = IfConvertTriangle(BBI);
236         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
237         if (RetVal) {
238           if (isFalseRev)   NumTriangleFRev++;
239           else if (isFalse) NumTriangleFalse++;
240           else              NumTriangle++;
241         }
242         break;
243       }
244       case ICDiamond:
245         if (DisableDiamond) break;
246         DOUT << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
247              << BBI.TrueBB->getNumber() << ",F:" << BBI.FalseBB->getNumber();
248         if (BBI.TailBB)
249           DOUT << "," << BBI.TailBB->getNumber() ;
250         DOUT << ") ";
251         RetVal = IfConvertDiamond(BBI);
252         DOUT << (RetVal ? "succeeded!" : "failed!") << "\n";
253         if (RetVal) NumDiamonds++;
254         break;
255       }
256       Change |= RetVal;
257
258       if (IfCvtLimit != -1 && (int)NumIfConvBBs >= IfCvtLimit)
259         break;
260     }
261
262     if (!Change)
263       break;
264     MadeChange |= Change;
265   }
266
267   Roots.clear();
268   BBAnalysis.clear();
269
270   return MadeChange;
271 }
272
273 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
274                                          MachineBasicBlock *TrueBB) {
275   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
276          E = BB->succ_end(); SI != E; ++SI) {
277     MachineBasicBlock *SuccBB = *SI;
278     if (SuccBB != TrueBB)
279       return SuccBB;
280   }
281   return NULL;
282 }
283
284 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
285   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
286     TII->RemoveBranch(*BBI.BB);
287     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond);
288     std::swap(BBI.TrueBB, BBI.FalseBB);
289     return true;
290   }
291   return false;
292 }
293
294 /// getNextBlock - Returns the next block in the function blocks ordering. If
295 /// it is the end, returns NULL.
296 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
297   MachineFunction::iterator I = BB;
298   MachineFunction::iterator E = BB->getParent()->end();
299   if (++I == E)
300     return NULL;
301   return I;
302 }
303
304 /// ValidSimple - Returns true if the 'true' block (along with its
305 /// predecessor) forms a valid simple shape for ifcvt.
306 bool IfConverter::ValidSimple(BBInfo &TrueBBI) const {
307   return !blockAlwaysFallThrough(TrueBBI) &&
308     TrueBBI.BrCond.size() == 0 && TrueBBI.BB->pred_size() == 1;
309 }
310
311 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
312 /// with their common predecessor) forms a valid triangle shape for ifcvt.
313 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
314                                 bool FalseBranch) const {
315   if (TrueBBI.BB->pred_size() != 1)
316     return false;
317
318   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
319   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
320     MachineFunction::iterator I = TrueBBI.BB;
321     if (++I == TrueBBI.BB->getParent()->end())
322       return false;
323     TExit = I;
324   }
325   return TExit && TExit == FalseBBI.BB;
326 }
327
328 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
329 /// with their common predecessor) forms a valid diamond shape for ifcvt.
330 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI) const {
331   MachineBasicBlock *TT = TrueBBI.TrueBB;
332   MachineBasicBlock *FT = FalseBBI.TrueBB;
333
334   if (!TT && blockAlwaysFallThrough(TrueBBI))
335     TT = getNextBlock(TrueBBI.BB);
336   if (!FT && blockAlwaysFallThrough(FalseBBI))
337     FT = getNextBlock(FalseBBI.BB);
338   if (TT != FT)
339     return false;
340   if (TT == NULL && (TrueBBI.IsAnalyzable || FalseBBI.IsAnalyzable))
341     return false;
342   // FIXME: Allow false block to have an early exit?
343   return (TrueBBI.BB->pred_size() == 1 &&
344           FalseBBI.BB->pred_size() == 1 &&
345           !TrueBBI.FalseBB && !FalseBBI.FalseBB);
346 }
347
348 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
349 /// the specified block. Record its successors and whether it looks like an
350 /// if-conversion candidate.
351 void IfConverter::AnalyzeBlock(MachineBasicBlock *BB) {
352   BBInfo &BBI = BBAnalysis[BB->getNumber()];
353
354   if (BBI.Kind == ICReAnalyze) {
355     BBI.BrCond.clear();
356     BBI.TrueBB = BBI.FalseBB = NULL;
357   } else {
358     if (BBI.Kind != ICNotAnalyzed)
359       return;  // Already analyzed.
360     BBI.BB = BB;
361     BBI.NonPredSize = std::distance(BB->begin(), BB->end());
362   }
363
364   // Look for 'root' of a simple (non-nested) triangle or diamond.
365   BBI.Kind = ICNotClassfied;
366   BBI.IsAnalyzable =
367     !TII->AnalyzeBranch(*BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
368   BBI.HasFallThrough = BBI.IsAnalyzable && BBI.FalseBB == NULL;
369   // Unanalyable or ends with fallthrough or unconditional branch.
370   if (!BBI.IsAnalyzable || BBI.BrCond.size() == 0)
371     return;
372   // Do not ifcvt if either path is a back edge to the entry block.
373   if (BBI.TrueBB == BB || BBI.FalseBB == BB)
374     return;
375
376   AnalyzeBlock(BBI.TrueBB);
377   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
378
379   // No false branch. This BB must end with a conditional branch and a
380   // fallthrough.
381   if (!BBI.FalseBB)
382     BBI.FalseBB = findFalseBlock(BB, BBI.TrueBB);  
383   assert(BBI.FalseBB && "Expected to find the fallthrough block!");
384
385   AnalyzeBlock(BBI.FalseBB);
386   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
387
388   // If both paths are dead, then forget about it.
389   if (TrueBBI.Kind == ICDead && FalseBBI.Kind == ICDead) {
390     BBI.Kind = ICDead;
391     return;
392   }
393
394   // Look for more opportunities to if-convert a triangle. Try to restructure
395   // the CFG to form a triangle with the 'false' path.
396   std::vector<MachineOperand> RevCond(BBI.BrCond);
397   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
398
399   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI) &&
400       !(TrueBBI.ModifyPredicate && FalseBBI.ModifyPredicate) &&
401       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
402       FeasibilityAnalysis(FalseBBI, RevCond)) {
403     // Diamond:
404     //   EBB
405     //   / \_
406     //  |   |
407     // TBB FBB
408     //   \ /
409     //  TailBB
410     // Note TailBB can be empty.
411     BBI.Kind = ICDiamond;
412     TrueBBI.Kind = FalseBBI.Kind = ICChild;
413     BBI.TailBB = TrueBBI.TrueBB;
414   } else {
415     // FIXME: Consider duplicating if BB is small.
416     if (ValidTriangle(TrueBBI, FalseBBI) &&
417         FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
418       // Triangle:
419       //   EBB
420       //   | \_
421       //   |  |
422       //   | TBB
423       //   |  /
424       //   FBB
425       BBI.Kind = ICTriangle;
426       TrueBBI.Kind = ICChild;
427     } else if (ValidSimple(TrueBBI) &&
428                FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
429       // Simple (split, no rejoin):
430       //   EBB
431       //   | \_
432       //   |  |
433       //   | TBB---> exit
434       //   |    
435       //   FBB
436       BBI.Kind = ICSimple;
437       TrueBBI.Kind = ICChild;
438     } else if (CanRevCond) {
439       // Try the other path...
440       if (ValidTriangle(FalseBBI, TrueBBI) &&
441           FeasibilityAnalysis(FalseBBI, RevCond, true)) {
442         BBI.Kind = ICTriangleFalse;
443         FalseBBI.Kind = ICChild;
444       } else if (ValidTriangle(FalseBBI, TrueBBI, true) &&
445                  FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
446         BBI.Kind = ICTriangleFRev;
447         FalseBBI.Kind = ICChild;
448       } else if (ValidSimple(FalseBBI) &&
449                  FeasibilityAnalysis(FalseBBI, RevCond)) {
450         BBI.Kind = ICSimpleFalse;
451         FalseBBI.Kind = ICChild;
452       }
453     }
454   }
455   return;
456 }
457
458 /// FeasibilityAnalysis - Determine if the block is predicable. In most
459 /// cases, that means all the instructions in the block has M_PREDICABLE flag.
460 /// Also checks if the block contains any instruction which can clobber a
461 /// predicate (e.g. condition code register). If so, the block is not
462 /// predicable unless it's the last instruction.
463 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
464                                       std::vector<MachineOperand> &Pred,
465                                       bool isTriangle, bool RevBranch) {
466   // If the block is dead, or it is going to be the entry block of a sub-CFG
467   // that will be if-converted, then it cannot be predicated.
468   if (BBI.Kind != ICNotAnalyzed &&
469       BBI.Kind != ICNotClassfied &&
470       BBI.Kind != ICChild)
471     return false;
472
473   // Check predication threshold.
474   if (BBI.NonPredSize == 0 || BBI.NonPredSize > TLI->getIfCvtBlockSizeLimit())
475     return false;
476
477   // If it is already predicated, check if its predicate subsumes the new
478   // predicate.
479   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
480     return false;
481
482   bool SeenPredMod = false;
483   bool SeenCondBr = false;
484   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
485        I != E; ++I) {
486     const TargetInstrDescriptor *TID = I->getInstrDescriptor();
487     if (SeenPredMod) {
488       // Predicate modification instruction should end the block (except for
489       // already predicated instructions and end of block branches).
490       if (!TII->isPredicated(I)) {
491         // This is the 'true' block of a triangle, i.e. its 'true' block is
492         // the same as the 'false' block of the entry. So false positive
493         // is ok.
494         if (isTriangle && !SeenCondBr && BBI.IsAnalyzable &&
495             (TID->Flags & M_BRANCH_FLAG) != 0 &&
496             (TID->Flags & M_BARRIER_FLAG) == 0) {
497           // This is the first conditional branch, test predicate subsumsion.
498           std::vector<MachineOperand> RevPred(Pred);
499           std::vector<MachineOperand> Cond(BBI.BrCond);
500           if (RevBranch) {
501             if (TII->ReverseBranchCondition(Cond))
502               return false;
503           }
504           if (TII->ReverseBranchCondition(RevPred) ||
505               !TII->SubsumesPredicate(Cond, RevPred))
506             return false;
507           SeenCondBr = true;
508           continue;  // Conditional branches is not predicable.
509         }
510         return false;
511       }
512     }
513
514     if (TID->Flags & M_CLOBBERS_PRED) {
515       BBI.ModifyPredicate = true;
516       SeenPredMod = true;
517     }
518
519     if (!I->isPredicable())
520       return false;
521   }
522
523   return true;
524 }
525
526 /// AttemptRestructuring - Restructure the sub-CFG rooted in the given block to
527 /// expose more if-conversion opportunities. e.g.
528 ///
529 ///                cmp
530 ///                b le BB1
531 ///                /  \____
532 ///               /        |
533 ///             cmp        |
534 ///             b eq BB1   |
535 ///              /  \____  |
536 ///             /        \ |
537 ///                      BB1
538 ///  ==>
539 ///
540 ///                cmp
541 ///                b eq BB1
542 ///                /  \____
543 ///               /        |
544 ///             cmp        |
545 ///             b le BB1   |
546 ///              /  \____  |
547 ///             /        \ |
548 ///                      BB1
549 bool IfConverter::AttemptRestructuring(BBInfo &BBI) {
550   return false;
551 }
552
553 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
554 /// candidates. It returns true if any CFG restructuring is done to expose more
555 /// if-conversion opportunities.
556 bool IfConverter::AnalyzeBlocks(MachineFunction &MF,
557                                 std::vector<BBInfo*> &Candidates) {
558   bool Change = false;
559   std::set<MachineBasicBlock*> Visited;
560   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
561     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
562            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
563       MachineBasicBlock *BB = *I;
564       AnalyzeBlock(BB);
565       BBInfo &BBI = BBAnalysis[BB->getNumber()];
566       switch (BBI.Kind) {
567         case ICSimple:
568         case ICSimpleFalse:
569         case ICTriangle:
570         case ICDiamond:
571           Candidates.push_back(&BBI);
572           break;
573         default:
574           Change |= AttemptRestructuring(BBI);
575           break;
576       }
577     }
578   }
579
580   // Sort to favor more complex ifcvt scheme.
581   std::stable_sort(Candidates.begin(), Candidates.end(), IfcvtCandidateCmp);
582
583   return Change;
584 }
585
586 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
587 /// that all the intervening blocks are empty (given BB can fall through to its
588 /// next block).
589 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
590   MachineFunction::iterator I = BB;
591   MachineFunction::iterator TI = ToBB;
592   MachineFunction::iterator E = BB->getParent()->end();
593   while (++I != TI)
594     if (I == E || !I->empty())
595       return false;
596   return true;
597 }
598
599 /// ReTryPreds - Invalidate predecessor BB info so it would be re-analyzed
600 /// to determine if it can be if-converted.
601 void IfConverter::ReTryPreds(MachineBasicBlock *BB) {
602   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
603          E = BB->pred_end(); PI != E; ++PI) {
604     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
605     if (PBBI.Kind == ICNotClassfied)
606       PBBI.Kind = ICReAnalyze;
607   }
608 }
609
610 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
611 ///
612 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
613                                const TargetInstrInfo *TII) {
614   std::vector<MachineOperand> NoCond;
615   TII->InsertBranch(*BB, ToBB, NULL, NoCond);
616 }
617
618 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
619 /// successors.
620 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
621   MachineBasicBlock *TBB = NULL, *FBB = NULL;
622   std::vector<MachineOperand> Cond;
623   bool isAnalyzable = !TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond);
624   bool CanFallthrough = isAnalyzable && (TBB == NULL || FBB == NULL);
625   if (BBI.TrueBB && BBI.BB->isSuccessor(BBI.TrueBB))
626     if (!(BBI.TrueBB == TBB || BBI.TrueBB == FBB ||
627           (CanFallthrough && getNextBlock(BBI.BB) == BBI.TrueBB)))
628       BBI.BB->removeSuccessor(BBI.TrueBB);
629   if (BBI.FalseBB && BBI.BB->isSuccessor(BBI.FalseBB))
630     if (!(BBI.FalseBB == TBB || BBI.FalseBB == FBB ||
631           (CanFallthrough && getNextBlock(BBI.BB) == BBI.FalseBB)))
632       BBI.BB->removeSuccessor(BBI.FalseBB);
633 }
634
635 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
636 ///
637 bool IfConverter::IfConvertSimple(BBInfo &BBI) {
638   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
639   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
640   BBInfo *CvtBBI = &TrueBBI;
641   BBInfo *NextBBI = &FalseBBI;
642
643   std::vector<MachineOperand> Cond(BBI.BrCond);
644   if (BBI.Kind == ICSimpleFalse) {
645     std::swap(CvtBBI, NextBBI);
646     TII->ReverseBranchCondition(Cond);
647   }
648
649   PredicateBlock(*CvtBBI, Cond);
650
651   // Merge converted block into entry block.
652   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
653   MergeBlocks(BBI, *CvtBBI);
654
655   bool IterIfcvt = true;
656   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
657     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
658     BBI.HasFallThrough = false;
659     // Now ifcvt'd block will look like this:
660     // BB:
661     // ...
662     // t, f = cmp
663     // if t op
664     // b BBf
665     //
666     // We cannot further ifcvt this block because the unconditional branch
667     // will have to be predicated on the new condition, that will not be
668     // available if cmp executes.
669     IterIfcvt = false;
670   }
671
672   RemoveExtraEdges(BBI);
673
674   // Update block info. BB can be iteratively if-converted.
675   if (IterIfcvt)
676     BBI.Kind = ICReAnalyze;
677   else
678     BBI.Kind = ICDead;
679   ReTryPreds(BBI.BB);
680   CvtBBI->Kind = ICDead;
681
682   // FIXME: Must maintain LiveIns.
683   return true;
684 }
685
686 /// IfConvertTriangle - If convert a triangle sub-CFG.
687 ///
688 bool IfConverter::IfConvertTriangle(BBInfo &BBI) {
689   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
690   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
691   BBInfo *CvtBBI = &TrueBBI;
692   BBInfo *NextBBI = &FalseBBI;
693
694   std::vector<MachineOperand> Cond(BBI.BrCond);
695   if (BBI.Kind == ICTriangleFalse || BBI.Kind == ICTriangleFRev) {
696     if (BBI.Kind == ICTriangleFRev) {
697       ReverseBranchCondition(*NextBBI);
698       // False BB has been changed, modify its predecessors (except for this
699       // one) so they don't get ifcvt'ed based on bad intel.
700       for (MachineBasicBlock::pred_iterator PI = NextBBI->BB->pred_begin(),
701              E = NextBBI->BB->pred_end(); PI != E; ++PI) {
702         MachineBasicBlock *PBB = *PI;
703         if (PBB == BBI.BB)
704           continue;
705         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
706         PBBI.Kind = ICReAnalyze;
707       }
708     }
709     std::swap(CvtBBI, NextBBI);
710     TII->ReverseBranchCondition(Cond);
711   }
712
713   // Predicate the 'true' block after removing its branch.
714   TrueBBI.NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
715   PredicateBlock(*CvtBBI, Cond);
716
717   // If 'true' block has a 'false' successor, add an exit branch to it.
718   bool HasEarlyExit = CvtBBI->FalseBB != NULL;
719   if (HasEarlyExit) {
720     std::vector<MachineOperand> RevCond(CvtBBI->BrCond);
721     if (TII->ReverseBranchCondition(RevCond))
722       assert(false && "Unable to reverse branch condition!");
723     TII->InsertBranch(*CvtBBI->BB, CvtBBI->FalseBB, NULL, RevCond);
724   }
725
726   // Now merge the entry of the triangle with the true block.
727   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
728   MergeBlocks(BBI, *CvtBBI);
729
730   // Merge in the 'false' block if the 'false' block has no other
731   // predecessors. Otherwise, add a unconditional branch from to 'false'.
732   bool FalseBBDead = false;
733   bool IterIfcvt = true;
734   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
735   if (!isFallThrough) {
736     // Only merge them if the true block does not fallthrough to the false
737     // block. By not merging them, we make it possible to iteratively
738     // ifcvt the blocks.
739     if (!HasEarlyExit && NextBBI->BB->pred_size() == 1) {
740       MergeBlocks(BBI, *NextBBI);
741       FalseBBDead = true;
742     } else {
743       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
744       BBI.HasFallThrough = false;
745     }
746     // Mixed predicated and unpredicated code. This cannot be iteratively
747     // predicated.
748     IterIfcvt = false;
749   }
750
751   RemoveExtraEdges(BBI);
752
753   // Update block info. BB can be iteratively if-converted.
754   if (IterIfcvt) 
755     BBI.Kind = ICReAnalyze;
756   else
757     BBI.Kind = ICDead;
758   ReTryPreds(BBI.BB);
759   CvtBBI->Kind = ICDead;
760   if (FalseBBDead)
761     NextBBI->Kind = ICDead;
762
763   // FIXME: Must maintain LiveIns.
764   return true;
765 }
766
767 /// IfConvertDiamond - If convert a diamond sub-CFG.
768 ///
769 bool IfConverter::IfConvertDiamond(BBInfo &BBI) {
770   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
771   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
772
773   SmallVector<MachineInstr*, 2> Dups;
774   if (!BBI.TailBB) {
775     // No common merge block. Check if the terminators (e.g. return) are
776     // the same or predicable.
777     MachineBasicBlock::iterator TT = BBI.TrueBB->getFirstTerminator();
778     MachineBasicBlock::iterator FT = BBI.FalseBB->getFirstTerminator();
779     while (TT != BBI.TrueBB->end() && FT != BBI.FalseBB->end()) {
780       if (TT->isIdenticalTo(FT))
781         Dups.push_back(TT);  // Will erase these later.
782       else if (!TT->isPredicable() && !FT->isPredicable())
783         return false; // Can't if-convert. Abort!
784       ++TT;
785       ++FT;
786     }
787
788     // One of the two pathes have more terminators, make sure they are
789     // all predicable.
790     while (TT != BBI.TrueBB->end()) {
791       if (!TT->isPredicable()) {
792         return false; // Can't if-convert. Abort!
793       }
794       ++TT;
795     }
796     while (FT != BBI.FalseBB->end()) {
797       if (!FT->isPredicable()) {
798         return false; // Can't if-convert. Abort!
799       }
800       ++FT;
801     }
802   }
803
804   // Remove the duplicated instructions from the 'true' block.
805   for (unsigned i = 0, e = Dups.size(); i != e; ++i) {
806     Dups[i]->eraseFromParent();
807     --TrueBBI.NonPredSize;
808   }
809     
810   // Merge the 'true' and 'false' blocks by copying the instructions
811   // from the 'false' block to the 'true' block. That is, unless the true
812   // block would clobber the predicate, in that case, do the opposite.
813   BBInfo *BBI1 = &TrueBBI;
814   BBInfo *BBI2 = &FalseBBI;
815   std::vector<MachineOperand> RevCond(BBI.BrCond);
816   TII->ReverseBranchCondition(RevCond);
817   std::vector<MachineOperand> *Cond1 = &BBI.BrCond;
818   std::vector<MachineOperand> *Cond2 = &RevCond;
819   // Check the 'true' and 'false' blocks if either isn't ended with a branch.
820   // Either the block fallthrough to another block or it ends with a
821   // return. If it's the former, add a branch to its successor.
822   bool NeedBr1 = !BBI1->TrueBB && BBI1->BB->succ_size();
823   bool NeedBr2 = !BBI2->TrueBB && BBI2->BB->succ_size(); 
824
825   if ((TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate) ||
826       (!TrueBBI.ModifyPredicate && !FalseBBI.ModifyPredicate &&
827        NeedBr1 && !NeedBr2)) {
828     std::swap(BBI1, BBI2);
829     std::swap(Cond1, Cond2);
830     std::swap(NeedBr1, NeedBr2);
831   }
832
833   // Predicate the 'true' block after removing its branch.
834   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
835   PredicateBlock(*BBI1, *Cond1);
836
837   // Add an early exit branch if needed.
838   if (NeedBr1)
839     TII->InsertBranch(*BBI1->BB, *BBI1->BB->succ_begin(), NULL, *Cond1);
840
841   // Predicate the 'false' block.
842   PredicateBlock(*BBI2, *Cond2, true);
843
844   // Add an unconditional branch from 'false' to to 'false' successor if it
845   // will not be the fallthrough block.
846   if (NeedBr2 && !NeedBr1) {
847     // If BBI2 isn't going to be merged in, then the existing fallthrough
848     // or branch is fine.
849     if (!canFallThroughTo(BBI.BB, *BBI2->BB->succ_begin())) {
850       InsertUncondBranch(BBI2->BB, *BBI2->BB->succ_begin(), TII);
851       BBI2->HasFallThrough = false;
852     }
853   }
854
855   // Keep them as two separate blocks if there is an early exit.
856   if (!NeedBr1)
857     MergeBlocks(*BBI1, *BBI2);
858
859   // Remove the conditional branch from entry to the blocks.
860   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
861
862   // Merge the combined block into the entry of the diamond.
863   MergeBlocks(BBI, *BBI1);
864
865   // 'True' and 'false' aren't combined, see if we need to add a unconditional
866   // branch to the 'false' block.
867   if (NeedBr1 && !canFallThroughTo(BBI.BB, BBI2->BB)) {
868     InsertUncondBranch(BBI.BB, BBI2->BB, TII);
869     BBI1->HasFallThrough = false;
870   }
871
872   // If the if-converted block fallthrough or unconditionally branch into the
873   // tail block, and the tail block does not have other predecessors, then
874   // fold the tail block in as well.
875   BBInfo *CvtBBI = NeedBr1 ? BBI2 : &BBI;
876   if (BBI.TailBB &&
877       BBI.TailBB->pred_size() == 1 && CvtBBI->BB->succ_size() == 1) {
878     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
879     BBInfo TailBBI = BBAnalysis[BBI.TailBB->getNumber()];
880     MergeBlocks(*CvtBBI, TailBBI);
881     TailBBI.Kind = ICDead;
882   }
883
884   RemoveExtraEdges(BBI);
885
886   // Update block info.
887   BBI.Kind = ICDead;
888   TrueBBI.Kind = ICDead;
889   FalseBBI.Kind = ICDead;
890
891   // FIXME: Must maintain LiveIns.
892   return true;
893 }
894
895 /// PredicateBlock - Predicate every instruction in the block with the specified
896 /// condition. If IgnoreTerm is true, skip over all terminator instructions.
897 void IfConverter::PredicateBlock(BBInfo &BBI,
898                                  std::vector<MachineOperand> &Cond,
899                                  bool IgnoreTerm) {
900   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
901        I != E; ++I) {
902     if (IgnoreTerm && TII->isTerminatorInstr(I->getOpcode()))
903       continue;
904     if (TII->isPredicated(I))
905       continue;
906     if (!TII->PredicateInstruction(I, Cond)) {
907       cerr << "Unable to predicate " << *I << "!\n";
908       abort();
909     }
910   }
911
912   BBI.NonPredSize = 0;
913   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
914
915   NumIfConvBBs++;
916 }
917
918 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
919 ///
920 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI) {
921   ToBBI.BB->splice(ToBBI.BB->end(),
922                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
923
924   // Redirect all branches to FromBB to ToBB.
925   std::vector<MachineBasicBlock *> Preds(FromBBI.BB->pred_begin(),
926                                          FromBBI.BB->pred_end());
927   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
928     MachineBasicBlock *Pred = Preds[i];
929     if (Pred == ToBBI.BB)
930       continue;
931     Pred->ReplaceUsesOfBlockWith(FromBBI.BB, ToBBI.BB);
932   }
933  
934   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
935                                          FromBBI.BB->succ_end());
936   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
937   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
938
939   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
940     MachineBasicBlock *Succ = Succs[i];
941     // Fallthrough edge can't be transferred.
942     if (Succ == FallThrough)
943       continue;
944     FromBBI.BB->removeSuccessor(Succ);
945     if (!ToBBI.BB->isSuccessor(Succ))
946       ToBBI.BB->addSuccessor(Succ);
947   }
948
949   // Now FromBBI always fall through to the next block!
950   if (NBB)
951     FromBBI.BB->addSuccessor(NBB);
952
953   ToBBI.NonPredSize += FromBBI.NonPredSize;
954   FromBBI.NonPredSize = 0;
955
956   ToBBI.ModifyPredicate |= FromBBI.ModifyPredicate;
957   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
958
959   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
960             std::back_inserter(ToBBI.Predicate));
961   FromBBI.Predicate.clear();
962 }