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