Change if-conversion to keep track of the extra cost due to microcoded
[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 is distributed under the University of Illinois Open Source
6 // 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 "BranchFolding.h"
16 #include "llvm/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetInstrItineraries.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 using namespace llvm;
34
35 // Hidden options for help debugging.
36 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
39 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
40                                    cl::init(false), cl::Hidden);
41 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
42                                     cl::init(false), cl::Hidden);
43 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
44                                      cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
46                                       cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
48                                       cl::init(false), cl::Hidden);
49 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
50                                        cl::init(false), cl::Hidden);
51 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
52                                     cl::init(false), cl::Hidden);
53 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54                                      cl::init(true), cl::Hidden);
55
56 STATISTIC(NumSimple,       "Number of simple if-conversions performed");
57 STATISTIC(NumSimpleFalse,  "Number of simple (F) if-conversions performed");
58 STATISTIC(NumTriangle,     "Number of triangle if-conversions performed");
59 STATISTIC(NumTriangleRev,  "Number of triangle (R) if-conversions performed");
60 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
63 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
64 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
65
66 namespace {
67   class IfConverter : public MachineFunctionPass {
68     enum IfcvtKind {
69       ICNotClassfied,  // BB data valid, but not classified.
70       ICSimpleFalse,   // Same as ICSimple, but on the false path.
71       ICSimple,        // BB is entry of an one split, no rejoin sub-CFG.
72       ICTriangleFRev,  // Same as ICTriangleFalse, but false path rev condition.
73       ICTriangleRev,   // Same as ICTriangle, but true path rev condition.
74       ICTriangleFalse, // Same as ICTriangle, but on the false path.
75       ICTriangle,      // BB is entry of a triangle sub-CFG.
76       ICDiamond        // BB is entry of a diamond sub-CFG.
77     };
78
79     /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80     /// if-conversion feasibility analysis. This includes results from
81     /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
82     /// classification, and common tail block of its successors (if it's a
83     /// diamond shape), its size, whether it's predicable, and whether any
84     /// instruction can clobber the 'would-be' predicate.
85     ///
86     /// IsDone          - True if BB is not to be considered for ifcvt.
87     /// IsBeingAnalyzed - True if BB is currently being analyzed.
88     /// IsAnalyzed      - True if BB has been analyzed (info is still valid).
89     /// IsEnqueued      - True if BB has been enqueued to be ifcvt'ed.
90     /// IsBrAnalyzable  - True if AnalyzeBranch() returns false.
91     /// HasFallThrough  - True if BB may fallthrough to the following BB.
92     /// IsUnpredicable  - True if BB is known to be unpredicable.
93     /// ClobbersPred    - True if BB could modify predicates (e.g. has
94     ///                   cmp, call, etc.)
95     /// NonPredSize     - Number of non-predicated instructions.
96     /// ExtraCost       - Extra cost for microcoded instructions.
97     /// BB              - Corresponding MachineBasicBlock.
98     /// TrueBB / FalseBB- See AnalyzeBranch().
99     /// BrCond          - Conditions for end of block conditional branches.
100     /// Predicate       - Predicate used in the BB.
101     struct BBInfo {
102       bool IsDone          : 1;
103       bool IsBeingAnalyzed : 1;
104       bool IsAnalyzed      : 1;
105       bool IsEnqueued      : 1;
106       bool IsBrAnalyzable  : 1;
107       bool HasFallThrough  : 1;
108       bool IsUnpredicable  : 1;
109       bool CannotBeCopied  : 1;
110       bool ClobbersPred    : 1;
111       unsigned NonPredSize;
112       unsigned ExtraCost;
113       MachineBasicBlock *BB;
114       MachineBasicBlock *TrueBB;
115       MachineBasicBlock *FalseBB;
116       SmallVector<MachineOperand, 4> BrCond;
117       SmallVector<MachineOperand, 4> Predicate;
118       BBInfo() : IsDone(false), IsBeingAnalyzed(false),
119                  IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
120                  HasFallThrough(false), IsUnpredicable(false),
121                  CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
122                  ExtraCost(0), BB(0), TrueBB(0), FalseBB(0) {}
123     };
124
125     /// IfcvtToken - Record information about pending if-conversions to attempt:
126     /// BBI             - Corresponding BBInfo.
127     /// Kind            - Type of block. See IfcvtKind.
128     /// NeedSubsumption - True if the to-be-predicated BB has already been
129     ///                   predicated.
130     /// NumDups      - Number of instructions that would be duplicated due
131     ///                   to this if-conversion. (For diamonds, the number of
132     ///                   identical instructions at the beginnings of both
133     ///                   paths).
134     /// NumDups2     - For diamonds, the number of identical instructions
135     ///                   at the ends of both paths.
136     struct IfcvtToken {
137       BBInfo &BBI;
138       IfcvtKind Kind;
139       bool NeedSubsumption;
140       unsigned NumDups;
141       unsigned NumDups2;
142       IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
143         : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
144     };
145
146     /// Roots - Basic blocks that do not have successors. These are the starting
147     /// points of Graph traversal.
148     std::vector<MachineBasicBlock*> Roots;
149
150     /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
151     /// basic block number.
152     std::vector<BBInfo> BBAnalysis;
153
154     const TargetLowering *TLI;
155     const TargetInstrInfo *TII;
156     const TargetRegisterInfo *TRI;
157     const InstrItineraryData *InstrItins;
158     const MachineLoopInfo *MLI;
159     bool MadeChange;
160     int FnNum;
161   public:
162     static char ID;
163     IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164       initializeIfConverterPass(*PassRegistry::getPassRegistry());
165     }
166     
167     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168       AU.addRequired<MachineLoopInfo>();
169       MachineFunctionPass::getAnalysisUsage(AU);
170     }
171
172     virtual bool runOnMachineFunction(MachineFunction &MF);
173     virtual const char *getPassName() const { return "If Converter"; }
174
175   private:
176     bool ReverseBranchCondition(BBInfo &BBI);
177     bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178                      float Prediction, float Confidence) const;
179     bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
180                        bool FalseBranch, unsigned &Dups,
181                        float Prediction, float Confidence) const;
182     bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183                       unsigned &Dups1, unsigned &Dups2) const;
184     void ScanInstructions(BBInfo &BBI);
185     BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186                          std::vector<IfcvtToken*> &Tokens);
187     bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
188                              bool isTriangle = false, bool RevBranch = false);
189     void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
190     void InvalidatePreds(MachineBasicBlock *BB);
191     void RemoveExtraEdges(BBInfo &BBI);
192     bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193     bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
194     bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195                           unsigned NumDups1, unsigned NumDups2);
196     void PredicateBlock(BBInfo &BBI,
197                         MachineBasicBlock::iterator E,
198                         SmallVectorImpl<MachineOperand> &Cond,
199                         SmallSet<unsigned, 4> &Redefs);
200     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
201                                SmallVectorImpl<MachineOperand> &Cond,
202                                SmallSet<unsigned, 4> &Redefs,
203                                bool IgnoreBr = false);
204     void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
205
206     bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
207                             float Prediction, float Confidence) const {
208       return Size > 0 && TII->isProfitableToIfCvt(BB, Size,
209                                                   Prediction, Confidence);
210     }
211
212     bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
213                             MachineBasicBlock &FBB, unsigned FSize,
214                             float Prediction, float Confidence) const {
215       return TSize > 0 && FSize > 0 &&
216         TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize,
217                                  Prediction, Confidence);
218     }
219
220     // blockAlwaysFallThrough - Block ends without a terminator.
221     bool blockAlwaysFallThrough(BBInfo &BBI) const {
222       return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
223     }
224
225     // IfcvtTokenCmp - Used to sort if-conversion candidates.
226     static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
227       int Incr1 = (C1->Kind == ICDiamond)
228         ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
229       int Incr2 = (C2->Kind == ICDiamond)
230         ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
231       if (Incr1 > Incr2)
232         return true;
233       else if (Incr1 == Incr2) {
234         // Favors subsumption.
235         if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
236           return true;
237         else if (C1->NeedSubsumption == C2->NeedSubsumption) {
238           // Favors diamond over triangle, etc.
239           if ((unsigned)C1->Kind < (unsigned)C2->Kind)
240             return true;
241           else if (C1->Kind == C2->Kind)
242             return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
243         }
244       }
245       return false;
246     }
247   };
248
249   char IfConverter::ID = 0;
250 }
251
252 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
253 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
254 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
255
256 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
257
258 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
259   TLI = MF.getTarget().getTargetLowering();
260   TII = MF.getTarget().getInstrInfo();
261   TRI = MF.getTarget().getRegisterInfo();
262   MLI = &getAnalysis<MachineLoopInfo>();
263   InstrItins = MF.getTarget().getInstrItineraryData();
264   if (!TII) return false;
265
266   // Tail merge tend to expose more if-conversion opportunities.
267   BranchFolder BF(true);
268   bool BFChange = BF.OptimizeFunction(MF, TII,
269                                    MF.getTarget().getRegisterInfo(),
270                                    getAnalysisIfAvailable<MachineModuleInfo>());
271
272   DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum <<  ") \'"
273                << MF.getFunction()->getName() << "\'");
274
275   if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
276     DEBUG(dbgs() << " skipped\n");
277     return false;
278   }
279   DEBUG(dbgs() << "\n");
280
281   MF.RenumberBlocks();
282   BBAnalysis.resize(MF.getNumBlockIDs());
283
284   // Look for root nodes, i.e. blocks without successors.
285   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
286     if (I->succ_empty())
287       Roots.push_back(I);
288
289   std::vector<IfcvtToken*> Tokens;
290   MadeChange = false;
291   unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
292     NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
293   while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
294     // Do an initial analysis for each basic block and find all the potential
295     // candidates to perform if-conversion.
296     bool Change = false;
297     AnalyzeBlocks(MF, Tokens);
298     while (!Tokens.empty()) {
299       IfcvtToken *Token = Tokens.back();
300       Tokens.pop_back();
301       BBInfo &BBI = Token->BBI;
302       IfcvtKind Kind = Token->Kind;
303       unsigned NumDups = Token->NumDups;
304       unsigned NumDups2 = Token->NumDups2;
305
306       delete Token;
307
308       // If the block has been evicted out of the queue or it has already been
309       // marked dead (due to it being predicated), then skip it.
310       if (BBI.IsDone)
311         BBI.IsEnqueued = false;
312       if (!BBI.IsEnqueued)
313         continue;
314
315       BBI.IsEnqueued = false;
316
317       bool RetVal = false;
318       switch (Kind) {
319       default: assert(false && "Unexpected!");
320         break;
321       case ICSimple:
322       case ICSimpleFalse: {
323         bool isFalse = Kind == ICSimpleFalse;
324         if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
325         DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
326                                             " false" : "")
327                      << "): BB#" << BBI.BB->getNumber() << " ("
328                      << ((Kind == ICSimpleFalse)
329                          ? BBI.FalseBB->getNumber()
330                          : BBI.TrueBB->getNumber()) << ") ");
331         RetVal = IfConvertSimple(BBI, Kind);
332         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
333         if (RetVal) {
334           if (isFalse) ++NumSimpleFalse;
335           else         ++NumSimple;
336         }
337        break;
338       }
339       case ICTriangle:
340       case ICTriangleRev:
341       case ICTriangleFalse:
342       case ICTriangleFRev: {
343         bool isFalse = Kind == ICTriangleFalse;
344         bool isRev   = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
345         if (DisableTriangle && !isFalse && !isRev) break;
346         if (DisableTriangleR && !isFalse && isRev) break;
347         if (DisableTriangleF && isFalse && !isRev) break;
348         if (DisableTriangleFR && isFalse && isRev) break;
349         DEBUG(dbgs() << "Ifcvt (Triangle");
350         if (isFalse)
351           DEBUG(dbgs() << " false");
352         if (isRev)
353           DEBUG(dbgs() << " rev");
354         DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
355                      << BBI.TrueBB->getNumber() << ",F:"
356                      << BBI.FalseBB->getNumber() << ") ");
357         RetVal = IfConvertTriangle(BBI, Kind);
358         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
359         if (RetVal) {
360           if (isFalse) {
361             if (isRev) ++NumTriangleFRev;
362             else       ++NumTriangleFalse;
363           } else {
364             if (isRev) ++NumTriangleRev;
365             else       ++NumTriangle;
366           }
367         }
368         break;
369       }
370       case ICDiamond: {
371         if (DisableDiamond) break;
372         DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
373                      << BBI.TrueBB->getNumber() << ",F:"
374                      << BBI.FalseBB->getNumber() << ") ");
375         RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
376         DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
377         if (RetVal) ++NumDiamonds;
378         break;
379       }
380       }
381
382       Change |= RetVal;
383
384       NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
385         NumTriangleFalse + NumTriangleFRev + NumDiamonds;
386       if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
387         break;
388     }
389
390     if (!Change)
391       break;
392     MadeChange |= Change;
393   }
394
395   // Delete tokens in case of early exit.
396   while (!Tokens.empty()) {
397     IfcvtToken *Token = Tokens.back();
398     Tokens.pop_back();
399     delete Token;
400   }
401
402   Tokens.clear();
403   Roots.clear();
404   BBAnalysis.clear();
405
406   if (MadeChange && IfCvtBranchFold) {
407     BranchFolder BF(false);
408     BF.OptimizeFunction(MF, TII,
409                         MF.getTarget().getRegisterInfo(),
410                         getAnalysisIfAvailable<MachineModuleInfo>());
411   }
412
413   MadeChange |= BFChange;
414   return MadeChange;
415 }
416
417 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
418 /// its 'true' successor.
419 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
420                                          MachineBasicBlock *TrueBB) {
421   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
422          E = BB->succ_end(); SI != E; ++SI) {
423     MachineBasicBlock *SuccBB = *SI;
424     if (SuccBB != TrueBB)
425       return SuccBB;
426   }
427   return NULL;
428 }
429
430 /// ReverseBranchCondition - Reverse the condition of the end of the block
431 /// branch. Swap block's 'true' and 'false' successors.
432 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
433   DebugLoc dl;  // FIXME: this is nowhere
434   if (!TII->ReverseBranchCondition(BBI.BrCond)) {
435     TII->RemoveBranch(*BBI.BB);
436     TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
437     std::swap(BBI.TrueBB, BBI.FalseBB);
438     return true;
439   }
440   return false;
441 }
442
443 /// getNextBlock - Returns the next block in the function blocks ordering. If
444 /// it is the end, returns NULL.
445 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
446   MachineFunction::iterator I = BB;
447   MachineFunction::iterator E = BB->getParent()->end();
448   if (++I == E)
449     return NULL;
450   return I;
451 }
452
453 /// ValidSimple - Returns true if the 'true' block (along with its
454 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
455 /// number of instructions that the ifcvt would need to duplicate if performed
456 /// in Dups.
457 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
458                               float Prediction, float Confidence) const {
459   Dups = 0;
460   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
461     return false;
462
463   if (TrueBBI.IsBrAnalyzable)
464     return false;
465
466   if (TrueBBI.BB->pred_size() > 1) {
467     if (TrueBBI.CannotBeCopied ||
468         !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
469                                         Prediction, Confidence))
470       return false;
471     Dups = TrueBBI.NonPredSize;
472   }
473
474   return true;
475 }
476
477 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
478 /// with their common predecessor) forms a valid triangle shape for ifcvt.
479 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
480 /// branches to the 'false' block rather than the other way around. It also
481 /// returns the number of instructions that the ifcvt would need to duplicate
482 /// if performed in 'Dups'.
483 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
484                                 bool FalseBranch, unsigned &Dups,
485                                 float Prediction, float Confidence) const {
486   Dups = 0;
487   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
488     return false;
489
490   if (TrueBBI.BB->pred_size() > 1) {
491     if (TrueBBI.CannotBeCopied)
492       return false;
493
494     unsigned Size = TrueBBI.NonPredSize;
495     if (TrueBBI.IsBrAnalyzable) {
496       if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
497         // Ends with an unconditional branch. It will be removed.
498         --Size;
499       else {
500         MachineBasicBlock *FExit = FalseBranch
501           ? TrueBBI.TrueBB : TrueBBI.FalseBB;
502         if (FExit)
503           // Require a conditional branch
504           ++Size;
505       }
506     }
507     if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
508                                         Prediction, Confidence))
509       return false;
510     Dups = Size;
511   }
512
513   MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
514   if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
515     MachineFunction::iterator I = TrueBBI.BB;
516     if (++I == TrueBBI.BB->getParent()->end())
517       return false;
518     TExit = I;
519   }
520   return TExit && TExit == FalseBBI.BB;
521 }
522
523 static
524 MachineBasicBlock::iterator firstNonBranchInst(MachineBasicBlock *BB,
525                                                const TargetInstrInfo *TII) {
526   MachineBasicBlock::iterator I = BB->end();
527   while (I != BB->begin()) {
528     --I;
529     if (!I->getDesc().isBranch())
530       break;
531   }
532   return I;
533 }
534
535 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
536 /// with their common predecessor) forms a valid diamond shape for ifcvt.
537 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
538                                unsigned &Dups1, unsigned &Dups2) const {
539   Dups1 = Dups2 = 0;
540   if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
541       FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
542     return false;
543
544   MachineBasicBlock *TT = TrueBBI.TrueBB;
545   MachineBasicBlock *FT = FalseBBI.TrueBB;
546
547   if (!TT && blockAlwaysFallThrough(TrueBBI))
548     TT = getNextBlock(TrueBBI.BB);
549   if (!FT && blockAlwaysFallThrough(FalseBBI))
550     FT = getNextBlock(FalseBBI.BB);
551   if (TT != FT)
552     return false;
553   if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
554     return false;
555   if  (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
556     return false;
557
558   // FIXME: Allow true block to have an early exit?
559   if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
560       (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
561     return false;
562
563   MachineBasicBlock::iterator TI = TrueBBI.BB->begin();
564   MachineBasicBlock::iterator FI = FalseBBI.BB->begin();
565   MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
566   MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
567   // Skip dbg_value instructions
568   while (TI != TIE && TI->isDebugValue())
569     ++TI;
570   while (FI != FIE && FI->isDebugValue())
571     ++FI;
572   while (TI != TIE && FI != FIE) {
573     // Skip dbg_value instructions. These do not count.
574     if (TI->isDebugValue()) {
575       while (TI != TIE && TI->isDebugValue())
576         ++TI;
577       if (TI == TIE)
578         break;
579     }
580     if (FI->isDebugValue()) {
581       while (FI != FIE && FI->isDebugValue())
582         ++FI;
583       if (FI == FIE)
584         break;
585     }
586     if (!TI->isIdenticalTo(FI))
587       break;
588     ++Dups1;
589     ++TI;
590     ++FI;
591   }
592
593   TI = firstNonBranchInst(TrueBBI.BB, TII);
594   FI = firstNonBranchInst(FalseBBI.BB, TII);
595   MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
596   MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
597   // Skip dbg_value instructions at end of the bb's.
598   while (TI != TIB && TI->isDebugValue())
599     --TI;
600   while (FI != FIB && FI->isDebugValue())
601     --FI;
602   while (TI != TIB && FI != FIB) {
603     // Skip dbg_value instructions. These do not count.
604     if (TI->isDebugValue()) {
605       while (TI != TIB && TI->isDebugValue())
606         --TI;
607       if (TI == TIB)
608         break;
609     }
610     if (FI->isDebugValue()) {
611       while (FI != FIB && FI->isDebugValue())
612         --FI;
613       if (FI == FIB)
614         break;
615     }
616     if (!TI->isIdenticalTo(FI))
617       break;
618     ++Dups2;
619     --TI;
620     --FI;
621   }
622
623   return true;
624 }
625
626 /// ScanInstructions - Scan all the instructions in the block to determine if
627 /// the block is predicable. In most cases, that means all the instructions
628 /// in the block are isPredicable(). Also checks if the block contains any
629 /// instruction which can clobber a predicate (e.g. condition code register).
630 /// If so, the block is not predicable unless it's the last instruction.
631 void IfConverter::ScanInstructions(BBInfo &BBI) {
632   if (BBI.IsDone)
633     return;
634
635   bool AlreadyPredicated = BBI.Predicate.size() > 0;
636   // First analyze the end of BB branches.
637   BBI.TrueBB = BBI.FalseBB = NULL;
638   BBI.BrCond.clear();
639   BBI.IsBrAnalyzable =
640     !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
641   BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
642
643   if (BBI.BrCond.size()) {
644     // No false branch. This BB must end with a conditional branch and a
645     // fallthrough.
646     if (!BBI.FalseBB)
647       BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
648     if (!BBI.FalseBB) {
649       // Malformed bcc? True and false blocks are the same?
650       BBI.IsUnpredicable = true;
651       return;
652     }
653   }
654
655   // Then scan all the instructions.
656   BBI.NonPredSize = 0;
657   BBI.ExtraCost = 0;
658   BBI.ClobbersPred = false;
659   for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
660        I != E; ++I) {
661     if (I->isDebugValue())
662       continue;
663
664     const TargetInstrDesc &TID = I->getDesc();
665     if (TID.isNotDuplicable())
666       BBI.CannotBeCopied = true;
667
668     bool isPredicated = TII->isPredicated(I);
669     bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
670
671     if (!isCondBr) {
672       if (!isPredicated) {
673         BBI.NonPredSize++;
674         unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
675         if (NumOps > 1)
676           BBI.ExtraCost += NumOps-1;
677       } else if (!AlreadyPredicated) {
678         // FIXME: This instruction is already predicated before the
679         // if-conversion pass. It's probably something like a conditional move.
680         // Mark this block unpredicable for now.
681         BBI.IsUnpredicable = true;
682         return;
683       }
684     }
685
686     if (BBI.ClobbersPred && !isPredicated) {
687       // Predicate modification instruction should end the block (except for
688       // already predicated instructions and end of block branches).
689       if (isCondBr) {
690         // A conditional branch is not predicable, but it may be eliminated.
691         continue;
692       }
693
694       // Predicate may have been modified, the subsequent (currently)
695       // unpredicated instructions cannot be correctly predicated.
696       BBI.IsUnpredicable = true;
697       return;
698     }
699
700     // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
701     // still potentially predicable.
702     std::vector<MachineOperand> PredDefs;
703     if (TII->DefinesPredicate(I, PredDefs))
704       BBI.ClobbersPred = true;
705
706     if (!TII->isPredicable(I)) {
707       BBI.IsUnpredicable = true;
708       return;
709     }
710   }
711 }
712
713 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
714 /// predicated by the specified predicate.
715 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
716                                       SmallVectorImpl<MachineOperand> &Pred,
717                                       bool isTriangle, bool RevBranch) {
718   // If the block is dead or unpredicable, then it cannot be predicated.
719   if (BBI.IsDone || BBI.IsUnpredicable)
720     return false;
721
722   // If it is already predicated, check if its predicate subsumes the new
723   // predicate.
724   if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
725     return false;
726
727   if (BBI.BrCond.size()) {
728     if (!isTriangle)
729       return false;
730
731     // Test predicate subsumption.
732     SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
733     SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
734     if (RevBranch) {
735       if (TII->ReverseBranchCondition(Cond))
736         return false;
737     }
738     if (TII->ReverseBranchCondition(RevPred) ||
739         !TII->SubsumesPredicate(Cond, RevPred))
740       return false;
741   }
742
743   return true;
744 }
745
746 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
747 /// the specified block. Record its successors and whether it looks like an
748 /// if-conversion candidate.
749 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
750                                              std::vector<IfcvtToken*> &Tokens) {
751   BBInfo &BBI = BBAnalysis[BB->getNumber()];
752
753   if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
754     return BBI;
755
756   BBI.BB = BB;
757   BBI.IsBeingAnalyzed = true;
758
759   ScanInstructions(BBI);
760
761   // Unanalyzable or ends with fallthrough or unconditional branch.
762   if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
763     BBI.IsBeingAnalyzed = false;
764     BBI.IsAnalyzed = true;
765     return BBI;
766   }
767
768   // Do not ifcvt if either path is a back edge to the entry block.
769   if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
770     BBI.IsBeingAnalyzed = false;
771     BBI.IsAnalyzed = true;
772     return BBI;
773   }
774
775   // Do not ifcvt if true and false fallthrough blocks are the same.
776   if (!BBI.FalseBB) {
777     BBI.IsBeingAnalyzed = false;
778     BBI.IsAnalyzed = true;
779     return BBI;
780   }
781
782   BBInfo &TrueBBI  = AnalyzeBlock(BBI.TrueBB, Tokens);
783   BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
784
785   if (TrueBBI.IsDone && FalseBBI.IsDone) {
786     BBI.IsBeingAnalyzed = false;
787     BBI.IsAnalyzed = true;
788     return BBI;
789   }
790
791   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
792   bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
793
794   unsigned Dups = 0;
795   unsigned Dups2 = 0;
796   bool TNeedSub = TrueBBI.Predicate.size() > 0;
797   bool FNeedSub = FalseBBI.Predicate.size() > 0;
798   bool Enqueued = false;
799   
800   // Try to predict the branch, using loop info to guide us.
801   // General heuristics are:
802   //   - backedge -> 90% taken
803   //   - early exit -> 20% taken
804   //   - branch predictor confidence -> 90%
805   float Prediction = 0.5f;
806   float Confidence = 0.9f;
807   MachineLoop *Loop = MLI->getLoopFor(BB);
808   if (Loop) {
809     if (TrueBBI.BB == Loop->getHeader())
810       Prediction = 0.9f;
811     else if (FalseBBI.BB == Loop->getHeader())
812       Prediction = 0.1f;
813
814     MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
815     MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
816     if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
817       Prediction = 0.2f;
818     else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
819       Prediction = 0.8f;
820   }
821   
822   if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
823       MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
824                                        TrueBBI.ExtraCost),
825                          *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
826                                         FalseBBI.ExtraCost),
827                          Prediction, Confidence) &&
828       FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
829       FeasibilityAnalysis(FalseBBI, RevCond)) {
830     // Diamond:
831     //   EBB
832     //   / \_
833     //  |   |
834     // TBB FBB
835     //   \ /
836     //  TailBB
837     // Note TailBB can be empty.
838     Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
839                                     Dups2));
840     Enqueued = true;
841   }
842
843   if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
844       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
845                          Prediction, Confidence) &&
846       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
847     // Triangle:
848     //   EBB
849     //   | \_
850     //   |  |
851     //   | TBB
852     //   |  /
853     //   FBB
854     Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
855     Enqueued = true;
856   }
857
858   if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
859       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
860                          Prediction, Confidence) &&
861       FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
862     Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
863     Enqueued = true;
864   }
865
866   if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
867       MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
868                          Prediction, Confidence) &&
869       FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
870     // Simple (split, no rejoin):
871     //   EBB
872     //   | \_
873     //   |  |
874     //   | TBB---> exit
875     //   |
876     //   FBB
877     Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
878     Enqueued = true;
879   }
880
881   if (CanRevCond) {
882     // Try the other path...
883     if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
884                       1.0-Prediction, Confidence) &&
885         MeetIfcvtSizeLimit(*FalseBBI.BB,
886                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
887                            1.0-Prediction, Confidence) &&
888         FeasibilityAnalysis(FalseBBI, RevCond, true)) {
889       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
890       Enqueued = true;
891     }
892
893     if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
894                       1.0-Prediction, Confidence) &&
895         MeetIfcvtSizeLimit(*FalseBBI.BB,
896                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
897                            1.0-Prediction, Confidence) &&
898         FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
899       Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
900       Enqueued = true;
901     }
902
903     if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
904         MeetIfcvtSizeLimit(*FalseBBI.BB,
905                            FalseBBI.NonPredSize + FalseBBI.ExtraCost,
906                            1.0-Prediction, Confidence) &&
907         FeasibilityAnalysis(FalseBBI, RevCond)) {
908       Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
909       Enqueued = true;
910     }
911   }
912
913   BBI.IsEnqueued = Enqueued;
914   BBI.IsBeingAnalyzed = false;
915   BBI.IsAnalyzed = true;
916   return BBI;
917 }
918
919 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
920 /// candidates.
921 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
922                                 std::vector<IfcvtToken*> &Tokens) {
923   std::set<MachineBasicBlock*> Visited;
924   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
925     for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
926            E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
927       MachineBasicBlock *BB = *I;
928       AnalyzeBlock(BB, Tokens);
929     }
930   }
931
932   // Sort to favor more complex ifcvt scheme.
933   std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
934 }
935
936 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
937 /// that all the intervening blocks are empty (given BB can fall through to its
938 /// next block).
939 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
940   MachineFunction::iterator PI = BB;
941   MachineFunction::iterator I = llvm::next(PI);
942   MachineFunction::iterator TI = ToBB;
943   MachineFunction::iterator E = BB->getParent()->end();
944   while (I != TI) {
945     // Check isSuccessor to avoid case where the next block is empty, but
946     // it's not a successor.
947     if (I == E || !I->empty() || !PI->isSuccessor(I))
948       return false;
949     PI = I++;
950   }
951   return true;
952 }
953
954 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
955 /// to determine if it can be if-converted. If predecessor is already enqueued,
956 /// dequeue it!
957 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
958   for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
959          E = BB->pred_end(); PI != E; ++PI) {
960     BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
961     if (PBBI.IsDone || PBBI.BB == BB)
962       continue;
963     PBBI.IsAnalyzed = false;
964     PBBI.IsEnqueued = false;
965   }
966 }
967
968 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
969 ///
970 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
971                                const TargetInstrInfo *TII) {
972   DebugLoc dl;  // FIXME: this is nowhere
973   SmallVector<MachineOperand, 0> NoCond;
974   TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
975 }
976
977 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
978 /// successors.
979 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
980   MachineBasicBlock *TBB = NULL, *FBB = NULL;
981   SmallVector<MachineOperand, 4> Cond;
982   if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
983     BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
984 }
985
986 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
987 /// modeled as read + write (sort like two-address instructions). These
988 /// routines track register liveness and add implicit uses to if-converted
989 /// instructions to conform to the model.
990 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
991                            const TargetRegisterInfo *TRI) {
992   for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
993          E = BB->livein_end(); I != E; ++I) {
994     unsigned Reg = *I;
995     Redefs.insert(Reg);
996     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
997          *Subreg; ++Subreg)
998       Redefs.insert(*Subreg);
999   }
1000 }
1001
1002 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
1003                              const TargetRegisterInfo *TRI,
1004                              bool AddImpUse = false) {
1005   SmallVector<unsigned, 4> Defs;
1006   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1007     const MachineOperand &MO = MI->getOperand(i);
1008     if (!MO.isReg())
1009       continue;
1010     unsigned Reg = MO.getReg();
1011     if (!Reg)
1012       continue;
1013     if (MO.isDef())
1014       Defs.push_back(Reg);
1015     else if (MO.isKill()) {
1016       Redefs.erase(Reg);
1017       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1018         Redefs.erase(*SR);
1019     }
1020   }
1021   for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1022     unsigned Reg = Defs[i];
1023     if (Redefs.count(Reg)) {
1024       if (AddImpUse)
1025         // Treat predicated update as read + write.
1026         MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
1027                                                 true/*IsImp*/,false/*IsKill*/));
1028     } else {
1029       Redefs.insert(Reg);
1030       for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1031         Redefs.insert(*SR);
1032     }
1033   }
1034 }
1035
1036 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1037                              MachineBasicBlock::iterator E,
1038                              SmallSet<unsigned,4> &Redefs,
1039                              const TargetRegisterInfo *TRI) {
1040   while (I != E) {
1041     UpdatePredRedefs(I, Redefs, TRI);
1042     ++I;
1043   }
1044 }
1045
1046 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1047 ///
1048 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1049   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1050   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1051   BBInfo *CvtBBI = &TrueBBI;
1052   BBInfo *NextBBI = &FalseBBI;
1053
1054   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1055   if (Kind == ICSimpleFalse)
1056     std::swap(CvtBBI, NextBBI);
1057
1058   if (CvtBBI->IsDone ||
1059       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1060     // Something has changed. It's no longer safe to predicate this block.
1061     BBI.IsAnalyzed = false;
1062     CvtBBI->IsAnalyzed = false;
1063     return false;
1064   }
1065
1066   if (Kind == ICSimpleFalse)
1067     if (TII->ReverseBranchCondition(Cond))
1068       assert(false && "Unable to reverse branch condition!");
1069
1070   // Initialize liveins to the first BB. These are potentiall redefined by
1071   // predicated instructions.
1072   SmallSet<unsigned, 4> Redefs;
1073   InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1074   InitPredRedefs(NextBBI->BB, Redefs, TRI);
1075
1076   if (CvtBBI->BB->pred_size() > 1) {
1077     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1078     // Copy instructions in the true block, predicate them, and add them to
1079     // the entry block.
1080     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1081   } else {
1082     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1083
1084     // Merge converted block into entry block.
1085     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1086     MergeBlocks(BBI, *CvtBBI);
1087   }
1088
1089   bool IterIfcvt = true;
1090   if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1091     InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1092     BBI.HasFallThrough = false;
1093     // Now ifcvt'd block will look like this:
1094     // BB:
1095     // ...
1096     // t, f = cmp
1097     // if t op
1098     // b BBf
1099     //
1100     // We cannot further ifcvt this block because the unconditional branch
1101     // will have to be predicated on the new condition, that will not be
1102     // available if cmp executes.
1103     IterIfcvt = false;
1104   }
1105
1106   RemoveExtraEdges(BBI);
1107
1108   // Update block info. BB can be iteratively if-converted.
1109   if (!IterIfcvt)
1110     BBI.IsDone = true;
1111   InvalidatePreds(BBI.BB);
1112   CvtBBI->IsDone = true;
1113
1114   // FIXME: Must maintain LiveIns.
1115   return true;
1116 }
1117
1118 /// IfConvertTriangle - If convert a triangle sub-CFG.
1119 ///
1120 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1121   BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1122   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1123   BBInfo *CvtBBI = &TrueBBI;
1124   BBInfo *NextBBI = &FalseBBI;
1125   DebugLoc dl;  // FIXME: this is nowhere
1126
1127   SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1128   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1129     std::swap(CvtBBI, NextBBI);
1130
1131   if (CvtBBI->IsDone ||
1132       (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1133     // Something has changed. It's no longer safe to predicate this block.
1134     BBI.IsAnalyzed = false;
1135     CvtBBI->IsAnalyzed = false;
1136     return false;
1137   }
1138
1139   if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1140     if (TII->ReverseBranchCondition(Cond))
1141       assert(false && "Unable to reverse branch condition!");
1142
1143   if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1144     if (ReverseBranchCondition(*CvtBBI)) {
1145       // BB has been changed, modify its predecessors (except for this
1146       // one) so they don't get ifcvt'ed based on bad intel.
1147       for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1148              E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1149         MachineBasicBlock *PBB = *PI;
1150         if (PBB == BBI.BB)
1151           continue;
1152         BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1153         if (PBBI.IsEnqueued) {
1154           PBBI.IsAnalyzed = false;
1155           PBBI.IsEnqueued = false;
1156         }
1157       }
1158     }
1159   }
1160
1161   // Initialize liveins to the first BB. These are potentially redefined by
1162   // predicated instructions.
1163   SmallSet<unsigned, 4> Redefs;
1164   InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1165   InitPredRedefs(NextBBI->BB, Redefs, TRI);
1166
1167   bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1168   if (CvtBBI->BB->pred_size() > 1) {
1169     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1170     // Copy instructions in the true block, predicate them, and add them to
1171     // the entry block.
1172     CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1173   } else {
1174     // Predicate the 'true' block after removing its branch.
1175     CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1176     PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1177
1178     // Now merge the entry of the triangle with the true block.
1179     BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1180     MergeBlocks(BBI, *CvtBBI, false);
1181   }
1182
1183   // If 'true' block has a 'false' successor, add an exit branch to it.
1184   if (HasEarlyExit) {
1185     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1186                                            CvtBBI->BrCond.end());
1187     if (TII->ReverseBranchCondition(RevCond))
1188       assert(false && "Unable to reverse branch condition!");
1189     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1190     BBI.BB->addSuccessor(CvtBBI->FalseBB);
1191   }
1192
1193   // Merge in the 'false' block if the 'false' block has no other
1194   // predecessors. Otherwise, add an unconditional branch to 'false'.
1195   bool FalseBBDead = false;
1196   bool IterIfcvt = true;
1197   bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1198   if (!isFallThrough) {
1199     // Only merge them if the true block does not fallthrough to the false
1200     // block. By not merging them, we make it possible to iteratively
1201     // ifcvt the blocks.
1202     if (!HasEarlyExit &&
1203         NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1204       MergeBlocks(BBI, *NextBBI);
1205       FalseBBDead = true;
1206     } else {
1207       InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1208       BBI.HasFallThrough = false;
1209     }
1210     // Mixed predicated and unpredicated code. This cannot be iteratively
1211     // predicated.
1212     IterIfcvt = false;
1213   }
1214
1215   RemoveExtraEdges(BBI);
1216
1217   // Update block info. BB can be iteratively if-converted.
1218   if (!IterIfcvt)
1219     BBI.IsDone = true;
1220   InvalidatePreds(BBI.BB);
1221   CvtBBI->IsDone = true;
1222   if (FalseBBDead)
1223     NextBBI->IsDone = true;
1224
1225   // FIXME: Must maintain LiveIns.
1226   return true;
1227 }
1228
1229 /// IfConvertDiamond - If convert a diamond sub-CFG.
1230 ///
1231 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1232                                    unsigned NumDups1, unsigned NumDups2) {
1233   BBInfo &TrueBBI  = BBAnalysis[BBI.TrueBB->getNumber()];
1234   BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1235   MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1236   // True block must fall through or end with an unanalyzable terminator.
1237   if (!TailBB) {
1238     if (blockAlwaysFallThrough(TrueBBI))
1239       TailBB = FalseBBI.TrueBB;
1240     assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1241   }
1242
1243   if (TrueBBI.IsDone || FalseBBI.IsDone ||
1244       TrueBBI.BB->pred_size() > 1 ||
1245       FalseBBI.BB->pred_size() > 1) {
1246     // Something has changed. It's no longer safe to predicate these blocks.
1247     BBI.IsAnalyzed = false;
1248     TrueBBI.IsAnalyzed = false;
1249     FalseBBI.IsAnalyzed = false;
1250     return false;
1251   }
1252
1253   // Put the predicated instructions from the 'true' block before the
1254   // instructions from the 'false' block, unless the true block would clobber
1255   // the predicate, in which case, do the opposite.
1256   BBInfo *BBI1 = &TrueBBI;
1257   BBInfo *BBI2 = &FalseBBI;
1258   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1259   if (TII->ReverseBranchCondition(RevCond))
1260     assert(false && "Unable to reverse branch condition!");
1261   SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1262   SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1263
1264   // Figure out the more profitable ordering.
1265   bool DoSwap = false;
1266   if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1267     DoSwap = true;
1268   else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1269     if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1270       DoSwap = true;
1271   }
1272   if (DoSwap) {
1273     std::swap(BBI1, BBI2);
1274     std::swap(Cond1, Cond2);
1275   }
1276
1277   // Remove the conditional branch from entry to the blocks.
1278   BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1279
1280   // Initialize liveins to the first BB. These are potentially redefined by
1281   // predicated instructions.
1282   SmallSet<unsigned, 4> Redefs;
1283   InitPredRedefs(BBI1->BB, Redefs, TRI);
1284
1285   // Remove the duplicated instructions at the beginnings of both paths.
1286   MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1287   MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1288   MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1289   MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1290   // Skip dbg_value instructions
1291   while (DI1 != DIE1 && DI1->isDebugValue())
1292     ++DI1;
1293   while (DI2 != DIE2 && DI2->isDebugValue())
1294     ++DI2;
1295   BBI1->NonPredSize -= NumDups1;
1296   BBI2->NonPredSize -= NumDups1;
1297
1298   // Skip past the dups on each side separately since there may be
1299   // differing dbg_value entries.
1300   for (unsigned i = 0; i < NumDups1; ++DI1) {
1301     if (!DI1->isDebugValue())
1302       ++i;
1303   }
1304   while (NumDups1 != 0) {
1305     ++DI2;
1306     if (!DI2->isDebugValue())
1307       --NumDups1;
1308   }
1309
1310   UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1311   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1312   BBI2->BB->erase(BBI2->BB->begin(), DI2);
1313
1314   // Predicate the 'true' block after removing its branch.
1315   BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1316   DI1 = BBI1->BB->end();
1317   for (unsigned i = 0; i != NumDups2; ) {
1318     // NumDups2 only counted non-dbg_value instructions, so this won't
1319     // run off the head of the list.
1320     assert (DI1 != BBI1->BB->begin());
1321     --DI1;
1322     // skip dbg_value instructions
1323     if (!DI1->isDebugValue())
1324       ++i;
1325   }
1326   BBI1->BB->erase(DI1, BBI1->BB->end());
1327   PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
1328
1329   // Predicate the 'false' block.
1330   BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1331   DI2 = BBI2->BB->end();
1332   while (NumDups2 != 0) {
1333     // NumDups2 only counted non-dbg_value instructions, so this won't
1334     // run off the head of the list.
1335     assert (DI2 != BBI2->BB->begin());
1336     --DI2;
1337     // skip dbg_value instructions
1338     if (!DI2->isDebugValue())
1339       --NumDups2;
1340   }
1341   PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1342
1343   // Merge the true block into the entry of the diamond.
1344   MergeBlocks(BBI, *BBI1, TailBB == 0);
1345   MergeBlocks(BBI, *BBI2, TailBB == 0);
1346
1347   // If the if-converted block falls through or unconditionally branches into
1348   // the tail block, and the tail block does not have other predecessors, then
1349   // fold the tail block in as well. Otherwise, unless it falls through to the
1350   // tail, add a unconditional branch to it.
1351   if (TailBB) {
1352     BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
1353     bool CanMergeTail = !TailBBI.HasFallThrough;
1354     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1355     // check if there are any other predecessors besides those.
1356     unsigned NumPreds = TailBB->pred_size();
1357     if (NumPreds > 1)
1358       CanMergeTail = false;
1359     else if (NumPreds == 1 && CanMergeTail) {
1360       MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1361       if (*PI != BBI1->BB && *PI != BBI2->BB)
1362         CanMergeTail = false;
1363     }
1364     if (CanMergeTail) {
1365       MergeBlocks(BBI, TailBBI);
1366       TailBBI.IsDone = true;
1367     } else {
1368       BBI.BB->addSuccessor(TailBB);
1369       InsertUncondBranch(BBI.BB, TailBB, TII);
1370       BBI.HasFallThrough = false;
1371     }
1372   }
1373
1374   // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1375   // which can happen here if TailBB is unanalyzable and is merged, so
1376   // explicitly remove BBI1 and BBI2 as successors.
1377   BBI.BB->removeSuccessor(BBI1->BB);
1378   BBI.BB->removeSuccessor(BBI2->BB);
1379   RemoveExtraEdges(BBI);
1380
1381   // Update block info.
1382   BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1383   InvalidatePreds(BBI.BB);
1384
1385   // FIXME: Must maintain LiveIns.
1386   return true;
1387 }
1388
1389 /// PredicateBlock - Predicate instructions from the start of the block to the
1390 /// specified end with the specified condition.
1391 void IfConverter::PredicateBlock(BBInfo &BBI,
1392                                  MachineBasicBlock::iterator E,
1393                                  SmallVectorImpl<MachineOperand> &Cond,
1394                                  SmallSet<unsigned, 4> &Redefs) {
1395   for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1396     if (I->isDebugValue() || TII->isPredicated(I))
1397       continue;
1398     if (!TII->PredicateInstruction(I, Cond)) {
1399 #ifndef NDEBUG
1400       dbgs() << "Unable to predicate " << *I << "!\n";
1401 #endif
1402       llvm_unreachable(0);
1403     }
1404
1405     // If the predicated instruction now redefines a register as the result of
1406     // if-conversion, add an implicit kill.
1407     UpdatePredRedefs(I, Redefs, TRI, true);
1408   }
1409
1410   std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1411
1412   BBI.IsAnalyzed = false;
1413   BBI.NonPredSize = 0;
1414
1415   ++NumIfConvBBs;
1416 }
1417
1418 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1419 /// the destination block. Skip end of block branches if IgnoreBr is true.
1420 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1421                                         SmallVectorImpl<MachineOperand> &Cond,
1422                                         SmallSet<unsigned, 4> &Redefs,
1423                                         bool IgnoreBr) {
1424   MachineFunction &MF = *ToBBI.BB->getParent();
1425
1426   for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1427          E = FromBBI.BB->end(); I != E; ++I) {
1428     const TargetInstrDesc &TID = I->getDesc();
1429     // Do not copy the end of the block branches.
1430     if (IgnoreBr && TID.isBranch())
1431       break;
1432
1433     MachineInstr *MI = MF.CloneMachineInstr(I);
1434     ToBBI.BB->insert(ToBBI.BB->end(), MI);
1435     ToBBI.NonPredSize++;
1436     unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
1437     if (NumOps > 1)
1438       ToBBI.ExtraCost += NumOps-1;
1439
1440     if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1441       if (!TII->PredicateInstruction(MI, Cond)) {
1442 #ifndef NDEBUG
1443         dbgs() << "Unable to predicate " << *I << "!\n";
1444 #endif
1445         llvm_unreachable(0);
1446       }
1447     }
1448
1449     // If the predicated instruction now redefines a register as the result of
1450     // if-conversion, add an implicit kill.
1451     UpdatePredRedefs(MI, Redefs, TRI, true);
1452   }
1453
1454   if (!IgnoreBr) {
1455     std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1456                                            FromBBI.BB->succ_end());
1457     MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1458     MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1459
1460     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1461       MachineBasicBlock *Succ = Succs[i];
1462       // Fallthrough edge can't be transferred.
1463       if (Succ == FallThrough)
1464         continue;
1465       ToBBI.BB->addSuccessor(Succ);
1466     }
1467   }
1468
1469   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1470             std::back_inserter(ToBBI.Predicate));
1471   std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1472
1473   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1474   ToBBI.IsAnalyzed = false;
1475
1476   ++NumDupBBs;
1477 }
1478
1479 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1480 /// This will leave FromBB as an empty block, so remove all of its
1481 /// successor edges except for the fall-through edge.  If AddEdges is true,
1482 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1483 /// ToBBI.
1484 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1485   ToBBI.BB->splice(ToBBI.BB->end(),
1486                    FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1487
1488   std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1489                                          FromBBI.BB->succ_end());
1490   MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1491   MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1492
1493   for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1494     MachineBasicBlock *Succ = Succs[i];
1495     // Fallthrough edge can't be transferred.
1496     if (Succ == FallThrough)
1497       continue;
1498     FromBBI.BB->removeSuccessor(Succ);
1499     if (AddEdges)
1500       ToBBI.BB->addSuccessor(Succ);
1501   }
1502
1503   // Now FromBBI always falls through to the next block!
1504   if (NBB && !FromBBI.BB->isSuccessor(NBB))
1505     FromBBI.BB->addSuccessor(NBB);
1506
1507   std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1508             std::back_inserter(ToBBI.Predicate));
1509   FromBBI.Predicate.clear();
1510
1511   ToBBI.NonPredSize += FromBBI.NonPredSize;
1512   ToBBI.ExtraCost += FromBBI.ExtraCost;
1513   FromBBI.NonPredSize = 0;
1514   FromBBI.ExtraCost = 0;
1515
1516   ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1517   ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1518   ToBBI.IsAnalyzed = false;
1519   FromBBI.IsAnalyzed = false;
1520 }