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