1 //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the machine instruction level if-conversion pass.
12 //===----------------------------------------------------------------------===//
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/LivePhysRegs.h"
21 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSchedule.h"
27 #include "llvm/MC/MCInstrItineraries.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 // Hidden options for help debugging.
41 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
42 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
43 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
44 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
45 cl::init(false), cl::Hidden);
46 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
47 cl::init(false), cl::Hidden);
48 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
49 cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
51 cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
53 cl::init(false), cl::Hidden);
54 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
55 cl::init(false), cl::Hidden);
56 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
57 cl::init(false), cl::Hidden);
58 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
59 cl::init(true), cl::Hidden);
61 STATISTIC(NumSimple, "Number of simple if-conversions performed");
62 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
63 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
64 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
65 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
66 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
67 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
68 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
69 STATISTIC(NumDupBBs, "Number of duplicated blocks");
70 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
73 class IfConverter : public MachineFunctionPass {
75 ICNotClassfied, // BB data valid, but not classified.
76 ICSimpleFalse, // Same as ICSimple, but on the false path.
77 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
78 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
79 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
80 ICTriangleFalse, // Same as ICTriangle, but on the false path.
81 ICTriangle, // BB is entry of a triangle sub-CFG.
82 ICDiamond // BB is entry of a diamond sub-CFG.
85 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
86 /// if-conversion feasibility analysis. This includes results from
87 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
88 /// classification, and common tail block of its successors (if it's a
89 /// diamond shape), its size, whether it's predicable, and whether any
90 /// instruction can clobber the 'would-be' predicate.
92 /// IsDone - True if BB is not to be considered for ifcvt.
93 /// IsBeingAnalyzed - True if BB is currently being analyzed.
94 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
95 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
96 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
97 /// HasFallThrough - True if BB may fallthrough to the following BB.
98 /// IsUnpredicable - True if BB is known to be unpredicable.
99 /// ClobbersPred - True if BB could modify predicates (e.g. has
101 /// NonPredSize - Number of non-predicated instructions.
102 /// ExtraCost - Extra cost for multi-cycle instructions.
103 /// ExtraCost2 - Some instructions are slower when predicated
104 /// BB - Corresponding MachineBasicBlock.
105 /// TrueBB / FalseBB- See AnalyzeBranch().
106 /// BrCond - Conditions for end of block conditional branches.
107 /// Predicate - Predicate used in the BB.
110 bool IsBeingAnalyzed : 1;
113 bool IsBrAnalyzable : 1;
114 bool HasFallThrough : 1;
115 bool IsUnpredicable : 1;
116 bool CannotBeCopied : 1;
117 bool ClobbersPred : 1;
118 unsigned NonPredSize;
121 MachineBasicBlock *BB;
122 MachineBasicBlock *TrueBB;
123 MachineBasicBlock *FalseBB;
124 SmallVector<MachineOperand, 4> BrCond;
125 SmallVector<MachineOperand, 4> Predicate;
126 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
127 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
128 HasFallThrough(false), IsUnpredicable(false),
129 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
130 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
133 /// IfcvtToken - Record information about pending if-conversions to attempt:
134 /// BBI - Corresponding BBInfo.
135 /// Kind - Type of block. See IfcvtKind.
136 /// NeedSubsumption - True if the to-be-predicated BB has already been
138 /// NumDups - Number of instructions that would be duplicated due
139 /// to this if-conversion. (For diamonds, the number of
140 /// identical instructions at the beginnings of both
142 /// NumDups2 - For diamonds, the number of identical instructions
143 /// at the ends of both paths.
147 bool NeedSubsumption;
150 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
151 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
154 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
155 /// basic block number.
156 std::vector<BBInfo> BBAnalysis;
157 TargetSchedModel SchedModel;
159 const TargetLoweringBase *TLI;
160 const TargetInstrInfo *TII;
161 const TargetRegisterInfo *TRI;
162 const MachineBranchProbabilityInfo *MBPI;
163 MachineRegisterInfo *MRI;
166 LivePhysRegs DontKill;
173 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
174 initializeIfConverterPass(*PassRegistry::getPassRegistry());
177 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
178 AU.addRequired<MachineBranchProbabilityInfo>();
179 MachineFunctionPass::getAnalysisUsage(AU);
182 virtual bool runOnMachineFunction(MachineFunction &MF);
185 bool ReverseBranchCondition(BBInfo &BBI);
186 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
187 const BranchProbability &Prediction) const;
188 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
189 bool FalseBranch, unsigned &Dups,
190 const BranchProbability &Prediction) const;
191 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
192 unsigned &Dups1, unsigned &Dups2) const;
193 void ScanInstructions(BBInfo &BBI);
194 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
195 std::vector<IfcvtToken*> &Tokens);
196 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
197 bool isTriangle = false, bool RevBranch = false);
198 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
199 void InvalidatePreds(MachineBasicBlock *BB);
200 void RemoveExtraEdges(BBInfo &BBI);
201 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
202 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
203 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
204 unsigned NumDups1, unsigned NumDups2);
205 void PredicateBlock(BBInfo &BBI,
206 MachineBasicBlock::iterator E,
207 SmallVectorImpl<MachineOperand> &Cond,
208 SmallSet<unsigned, 4> *LaterRedefs = 0);
209 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
210 SmallVectorImpl<MachineOperand> &Cond,
211 bool IgnoreBr = false);
212 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
214 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
215 unsigned Cycle, unsigned Extra,
216 const BranchProbability &Prediction) const {
217 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
221 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
222 unsigned TCycle, unsigned TExtra,
223 MachineBasicBlock &FBB,
224 unsigned FCycle, unsigned FExtra,
225 const BranchProbability &Prediction) const {
226 return TCycle > 0 && FCycle > 0 &&
227 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
231 // blockAlwaysFallThrough - Block ends without a terminator.
232 bool blockAlwaysFallThrough(BBInfo &BBI) const {
233 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
236 // IfcvtTokenCmp - Used to sort if-conversion candidates.
237 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
238 int Incr1 = (C1->Kind == ICDiamond)
239 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
240 int Incr2 = (C2->Kind == ICDiamond)
241 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
244 else if (Incr1 == Incr2) {
245 // Favors subsumption.
246 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
248 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
249 // Favors diamond over triangle, etc.
250 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
252 else if (C1->Kind == C2->Kind)
253 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
260 char IfConverter::ID = 0;
263 char &llvm::IfConverterID = IfConverter::ID;
265 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
266 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
267 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
269 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
270 TLI = MF.getTarget().getTargetLowering();
271 TII = MF.getTarget().getInstrInfo();
272 TRI = MF.getTarget().getRegisterInfo();
273 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
274 MRI = &MF.getRegInfo();
276 const TargetSubtargetInfo &ST =
277 MF.getTarget().getSubtarget<TargetSubtargetInfo>();
278 SchedModel.init(*ST.getSchedModel(), &ST, TII);
280 if (!TII) return false;
282 PreRegAlloc = MRI->isSSA();
284 bool BFChange = false;
286 // Tail merge tend to expose more if-conversion opportunities.
287 BranchFolder BF(true, false);
288 BFChange = BF.OptimizeFunction(MF, TII,
289 MF.getTarget().getRegisterInfo(),
290 getAnalysisIfAvailable<MachineModuleInfo>());
293 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
294 << MF.getName() << "\'");
296 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
297 DEBUG(dbgs() << " skipped\n");
300 DEBUG(dbgs() << "\n");
303 BBAnalysis.resize(MF.getNumBlockIDs());
305 std::vector<IfcvtToken*> Tokens;
307 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
308 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
309 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
310 // Do an initial analysis for each basic block and find all the potential
311 // candidates to perform if-conversion.
313 AnalyzeBlocks(MF, Tokens);
314 while (!Tokens.empty()) {
315 IfcvtToken *Token = Tokens.back();
317 BBInfo &BBI = Token->BBI;
318 IfcvtKind Kind = Token->Kind;
319 unsigned NumDups = Token->NumDups;
320 unsigned NumDups2 = Token->NumDups2;
324 // If the block has been evicted out of the queue or it has already been
325 // marked dead (due to it being predicated), then skip it.
327 BBI.IsEnqueued = false;
331 BBI.IsEnqueued = false;
335 default: llvm_unreachable("Unexpected!");
337 case ICSimpleFalse: {
338 bool isFalse = Kind == ICSimpleFalse;
339 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
340 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
342 << "): BB#" << BBI.BB->getNumber() << " ("
343 << ((Kind == ICSimpleFalse)
344 ? BBI.FalseBB->getNumber()
345 : BBI.TrueBB->getNumber()) << ") ");
346 RetVal = IfConvertSimple(BBI, Kind);
347 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
349 if (isFalse) ++NumSimpleFalse;
356 case ICTriangleFalse:
357 case ICTriangleFRev: {
358 bool isFalse = Kind == ICTriangleFalse;
359 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
360 if (DisableTriangle && !isFalse && !isRev) break;
361 if (DisableTriangleR && !isFalse && isRev) break;
362 if (DisableTriangleF && isFalse && !isRev) break;
363 if (DisableTriangleFR && isFalse && isRev) break;
364 DEBUG(dbgs() << "Ifcvt (Triangle");
366 DEBUG(dbgs() << " false");
368 DEBUG(dbgs() << " rev");
369 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
370 << BBI.TrueBB->getNumber() << ",F:"
371 << BBI.FalseBB->getNumber() << ") ");
372 RetVal = IfConvertTriangle(BBI, Kind);
373 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
376 if (isRev) ++NumTriangleFRev;
377 else ++NumTriangleFalse;
379 if (isRev) ++NumTriangleRev;
386 if (DisableDiamond) break;
387 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
388 << BBI.TrueBB->getNumber() << ",F:"
389 << BBI.FalseBB->getNumber() << ") ");
390 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
391 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
392 if (RetVal) ++NumDiamonds;
399 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
400 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
401 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
407 MadeChange |= Change;
410 // Delete tokens in case of early exit.
411 while (!Tokens.empty()) {
412 IfcvtToken *Token = Tokens.back();
420 if (MadeChange && IfCvtBranchFold) {
421 BranchFolder BF(false, false);
422 BF.OptimizeFunction(MF, TII,
423 MF.getTarget().getRegisterInfo(),
424 getAnalysisIfAvailable<MachineModuleInfo>());
427 MadeChange |= BFChange;
431 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
432 /// its 'true' successor.
433 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
434 MachineBasicBlock *TrueBB) {
435 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
436 E = BB->succ_end(); SI != E; ++SI) {
437 MachineBasicBlock *SuccBB = *SI;
438 if (SuccBB != TrueBB)
444 /// ReverseBranchCondition - Reverse the condition of the end of the block
445 /// branch. Swap block's 'true' and 'false' successors.
446 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
447 DebugLoc dl; // FIXME: this is nowhere
448 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
449 TII->RemoveBranch(*BBI.BB);
450 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
451 std::swap(BBI.TrueBB, BBI.FalseBB);
457 /// getNextBlock - Returns the next block in the function blocks ordering. If
458 /// it is the end, returns NULL.
459 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
460 MachineFunction::iterator I = BB;
461 MachineFunction::iterator E = BB->getParent()->end();
467 /// ValidSimple - Returns true if the 'true' block (along with its
468 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
469 /// number of instructions that the ifcvt would need to duplicate if performed
471 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
472 const BranchProbability &Prediction) const {
474 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
477 if (TrueBBI.IsBrAnalyzable)
480 if (TrueBBI.BB->pred_size() > 1) {
481 if (TrueBBI.CannotBeCopied ||
482 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
485 Dups = TrueBBI.NonPredSize;
491 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
492 /// with their common predecessor) forms a valid triangle shape for ifcvt.
493 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
494 /// branches to the 'false' block rather than the other way around. It also
495 /// returns the number of instructions that the ifcvt would need to duplicate
496 /// if performed in 'Dups'.
497 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
498 bool FalseBranch, unsigned &Dups,
499 const BranchProbability &Prediction) const {
501 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
504 if (TrueBBI.BB->pred_size() > 1) {
505 if (TrueBBI.CannotBeCopied)
508 unsigned Size = TrueBBI.NonPredSize;
509 if (TrueBBI.IsBrAnalyzable) {
510 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
511 // Ends with an unconditional branch. It will be removed.
514 MachineBasicBlock *FExit = FalseBranch
515 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
517 // Require a conditional branch
521 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
526 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
527 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
528 MachineFunction::iterator I = TrueBBI.BB;
529 if (++I == TrueBBI.BB->getParent()->end())
533 return TExit && TExit == FalseBBI.BB;
536 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
537 /// with their common predecessor) forms a valid diamond shape for ifcvt.
538 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
539 unsigned &Dups1, unsigned &Dups2) const {
541 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
542 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
545 MachineBasicBlock *TT = TrueBBI.TrueBB;
546 MachineBasicBlock *FT = FalseBBI.TrueBB;
548 if (!TT && blockAlwaysFallThrough(TrueBBI))
549 TT = getNextBlock(TrueBBI.BB);
550 if (!FT && blockAlwaysFallThrough(FalseBBI))
551 FT = getNextBlock(FalseBBI.BB);
554 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
556 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
559 // FIXME: Allow true block to have an early exit?
560 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
561 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
564 // Count duplicate instructions at the beginning of the true and false blocks.
565 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
566 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
567 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
568 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
569 while (TIB != TIE && FIB != FIE) {
570 // Skip dbg_value instructions. These do not count.
571 if (TIB->isDebugValue()) {
572 while (TIB != TIE && TIB->isDebugValue())
577 if (FIB->isDebugValue()) {
578 while (FIB != FIE && FIB->isDebugValue())
583 if (!TIB->isIdenticalTo(FIB))
590 // Now, in preparation for counting duplicate instructions at the ends of the
591 // blocks, move the end iterators up past any branch instructions.
594 if (!TIE->isBranch())
599 if (!FIE->isBranch())
603 // If Dups1 includes all of a block, then don't count duplicate
604 // instructions at the end of the blocks.
605 if (TIB == TIE || FIB == FIE)
608 // Count duplicate instructions at the ends of the blocks.
609 while (TIE != TIB && FIE != FIB) {
610 // Skip dbg_value instructions. These do not count.
611 if (TIE->isDebugValue()) {
612 while (TIE != TIB && TIE->isDebugValue())
617 if (FIE->isDebugValue()) {
618 while (FIE != FIB && FIE->isDebugValue())
623 if (!TIE->isIdenticalTo(FIE))
633 /// ScanInstructions - Scan all the instructions in the block to determine if
634 /// the block is predicable. In most cases, that means all the instructions
635 /// in the block are isPredicable(). Also checks if the block contains any
636 /// instruction which can clobber a predicate (e.g. condition code register).
637 /// If so, the block is not predicable unless it's the last instruction.
638 void IfConverter::ScanInstructions(BBInfo &BBI) {
642 bool AlreadyPredicated = !BBI.Predicate.empty();
643 // First analyze the end of BB branches.
644 BBI.TrueBB = BBI.FalseBB = NULL;
647 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
648 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
650 if (BBI.BrCond.size()) {
651 // No false branch. This BB must end with a conditional branch and a
654 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
656 // Malformed bcc? True and false blocks are the same?
657 BBI.IsUnpredicable = true;
662 // Then scan all the instructions.
666 BBI.ClobbersPred = false;
667 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
669 if (I->isDebugValue())
672 if (I->isNotDuplicable())
673 BBI.CannotBeCopied = true;
675 bool isPredicated = TII->isPredicated(I);
676 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
678 // A conditional branch is not predicable, but it may be eliminated.
684 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
685 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
687 BBI.ExtraCost += NumCycles-1;
688 BBI.ExtraCost2 += ExtraPredCost;
689 } else if (!AlreadyPredicated) {
690 // FIXME: This instruction is already predicated before the
691 // if-conversion pass. It's probably something like a conditional move.
692 // Mark this block unpredicable for now.
693 BBI.IsUnpredicable = true;
697 if (BBI.ClobbersPred && !isPredicated) {
698 // Predicate modification instruction should end the block (except for
699 // already predicated instructions and end of block branches).
700 // Predicate may have been modified, the subsequent (currently)
701 // unpredicated instructions cannot be correctly predicated.
702 BBI.IsUnpredicable = true;
706 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
707 // still potentially predicable.
708 std::vector<MachineOperand> PredDefs;
709 if (TII->DefinesPredicate(I, PredDefs))
710 BBI.ClobbersPred = true;
712 if (!TII->isPredicable(I)) {
713 BBI.IsUnpredicable = true;
719 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
720 /// predicated by the specified predicate.
721 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
722 SmallVectorImpl<MachineOperand> &Pred,
723 bool isTriangle, bool RevBranch) {
724 // If the block is dead or unpredicable, then it cannot be predicated.
725 if (BBI.IsDone || BBI.IsUnpredicable)
728 // If it is already predicated, check if the new predicate subsumes
730 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
733 if (BBI.BrCond.size()) {
737 // Test predicate subsumption.
738 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
739 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
741 if (TII->ReverseBranchCondition(Cond))
744 if (TII->ReverseBranchCondition(RevPred) ||
745 !TII->SubsumesPredicate(Cond, RevPred))
752 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
753 /// the specified block. Record its successors and whether it looks like an
754 /// if-conversion candidate.
755 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
756 std::vector<IfcvtToken*> &Tokens) {
757 BBInfo &BBI = BBAnalysis[BB->getNumber()];
759 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
763 BBI.IsBeingAnalyzed = true;
765 ScanInstructions(BBI);
767 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
768 // considered for ifcvt anymore.
769 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
770 BBI.IsBeingAnalyzed = false;
771 BBI.IsAnalyzed = true;
775 // Do not ifcvt if either path is a back edge to the entry block.
776 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
777 BBI.IsBeingAnalyzed = false;
778 BBI.IsAnalyzed = true;
782 // Do not ifcvt if true and false fallthrough blocks are the same.
784 BBI.IsBeingAnalyzed = false;
785 BBI.IsAnalyzed = true;
789 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
790 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
792 if (TrueBBI.IsDone && FalseBBI.IsDone) {
793 BBI.IsBeingAnalyzed = false;
794 BBI.IsAnalyzed = true;
798 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
799 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
803 bool TNeedSub = !TrueBBI.Predicate.empty();
804 bool FNeedSub = !FalseBBI.Predicate.empty();
805 bool Enqueued = false;
807 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
809 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
810 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
811 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
812 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
813 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
815 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
816 FeasibilityAnalysis(FalseBBI, RevCond)) {
824 // Note TailBB can be empty.
825 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
830 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
831 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
832 TrueBBI.ExtraCost2, Prediction) &&
833 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
841 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
845 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
846 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
847 TrueBBI.ExtraCost2, Prediction) &&
848 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
849 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
853 if (ValidSimple(TrueBBI, Dups, Prediction) &&
854 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
855 TrueBBI.ExtraCost2, Prediction) &&
856 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
857 // Simple (split, no rejoin):
864 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
869 // Try the other path...
870 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
871 Prediction.getCompl()) &&
872 MeetIfcvtSizeLimit(*FalseBBI.BB,
873 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
874 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
875 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
876 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
880 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
881 Prediction.getCompl()) &&
882 MeetIfcvtSizeLimit(*FalseBBI.BB,
883 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
884 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
885 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
886 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
890 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
891 MeetIfcvtSizeLimit(*FalseBBI.BB,
892 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
893 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
894 FeasibilityAnalysis(FalseBBI, RevCond)) {
895 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
900 BBI.IsEnqueued = Enqueued;
901 BBI.IsBeingAnalyzed = false;
902 BBI.IsAnalyzed = true;
906 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
908 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
909 std::vector<IfcvtToken*> &Tokens) {
910 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
911 MachineBasicBlock *BB = I;
912 AnalyzeBlock(BB, Tokens);
915 // Sort to favor more complex ifcvt scheme.
916 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
919 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
920 /// that all the intervening blocks are empty (given BB can fall through to its
922 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
923 MachineFunction::iterator PI = BB;
924 MachineFunction::iterator I = llvm::next(PI);
925 MachineFunction::iterator TI = ToBB;
926 MachineFunction::iterator E = BB->getParent()->end();
928 // Check isSuccessor to avoid case where the next block is empty, but
929 // it's not a successor.
930 if (I == E || !I->empty() || !PI->isSuccessor(I))
937 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
938 /// to determine if it can be if-converted. If predecessor is already enqueued,
940 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
941 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
942 E = BB->pred_end(); PI != E; ++PI) {
943 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
944 if (PBBI.IsDone || PBBI.BB == BB)
946 PBBI.IsAnalyzed = false;
947 PBBI.IsEnqueued = false;
951 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
953 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
954 const TargetInstrInfo *TII) {
955 DebugLoc dl; // FIXME: this is nowhere
956 SmallVector<MachineOperand, 0> NoCond;
957 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
960 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
962 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
963 MachineBasicBlock *TBB = NULL, *FBB = NULL;
964 SmallVector<MachineOperand, 4> Cond;
965 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
966 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
969 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
970 /// values defined in MI which are not live/used by MI.
971 static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
972 for (ConstMIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
973 if (!Ops->isReg() || !Ops->isKill())
975 unsigned Reg = Ops->getReg();
978 Redefs.removeReg(Reg);
980 for (MIBundleOperands Ops(MI); Ops.isValid(); ++Ops) {
981 if (!Ops->isReg() || !Ops->isDef())
983 unsigned Reg = Ops->getReg();
984 if (Reg == 0 || Redefs.contains(Reg))
988 MachineOperand &Op = *Ops;
989 MachineInstr *MI = Op.getParent();
990 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
991 MIB.addReg(Reg, RegState::Implicit | RegState::Undef);
996 * Remove kill flags from operands with a registers in the @p DontKill set.
998 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
999 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1000 if (!O->isReg() || !O->isKill())
1002 if (DontKill.contains(O->getReg()))
1003 O->setIsKill(false);
1008 * Walks a range of machine instructions and removes kill flags for registers
1009 * in the @p DontKill set.
1011 static void RemoveKills(MachineBasicBlock::iterator I,
1012 MachineBasicBlock::iterator E,
1013 const LivePhysRegs &DontKill,
1014 const MCRegisterInfo &MCRI) {
1015 for ( ; I != E; ++I)
1016 RemoveKills(*I, DontKill);
1019 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1021 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1022 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1023 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1024 BBInfo *CvtBBI = &TrueBBI;
1025 BBInfo *NextBBI = &FalseBBI;
1027 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1028 if (Kind == ICSimpleFalse)
1029 std::swap(CvtBBI, NextBBI);
1031 if (CvtBBI->IsDone ||
1032 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1033 // Something has changed. It's no longer safe to predicate this block.
1034 BBI.IsAnalyzed = false;
1035 CvtBBI->IsAnalyzed = false;
1039 if (CvtBBI->BB->hasAddressTaken())
1040 // Conservatively abort if-conversion if BB's address is taken.
1043 if (Kind == ICSimpleFalse)
1044 if (TII->ReverseBranchCondition(Cond))
1045 llvm_unreachable("Unable to reverse branch condition!");
1047 // Initialize liveins to the first BB. These are potentiall redefined by
1048 // predicated instructions.
1050 Redefs.addLiveIns(CvtBBI->BB);
1051 Redefs.addLiveIns(NextBBI->BB);
1053 // Compute a set of registers which must not be killed by instructions in
1054 // BB1: This is everything live-in to BB2.
1056 DontKill.addLiveIns(NextBBI->BB);
1058 if (CvtBBI->BB->pred_size() > 1) {
1059 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1060 // Copy instructions in the true block, predicate them, and add them to
1062 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1064 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1065 // explicitly remove CvtBBI as a successor.
1066 BBI.BB->removeSuccessor(CvtBBI->BB);
1068 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
1069 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1071 // Merge converted block into entry block.
1072 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1073 MergeBlocks(BBI, *CvtBBI);
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:
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.
1093 RemoveExtraEdges(BBI);
1095 // Update block info. BB can be iteratively if-converted.
1098 InvalidatePreds(BBI.BB);
1099 CvtBBI->IsDone = true;
1101 // FIXME: Must maintain LiveIns.
1105 /// IfConvertTriangle - If convert a triangle sub-CFG.
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
1114 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1115 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1116 std::swap(CvtBBI, NextBBI);
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;
1126 if (CvtBBI->BB->hasAddressTaken())
1127 // Conservatively abort if-conversion if BB's address is taken.
1130 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1131 if (TII->ReverseBranchCondition(Cond))
1132 llvm_unreachable("Unable to reverse branch condition!");
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;
1143 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1144 if (PBBI.IsEnqueued) {
1145 PBBI.IsAnalyzed = false;
1146 PBBI.IsEnqueued = false;
1152 // Initialize liveins to the first BB. These are potentially redefined by
1153 // predicated instructions.
1155 Redefs.addLiveIns(CvtBBI->BB);
1156 Redefs.addLiveIns(NextBBI->BB);
1160 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1161 if (CvtBBI->BB->pred_size() > 1) {
1162 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1163 // Copy instructions in the true block, predicate them, and add them to
1165 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1167 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1168 // explicitly remove CvtBBI as a successor.
1169 BBI.BB->removeSuccessor(CvtBBI->BB);
1171 // Predicate the 'true' block after removing its branch.
1172 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1173 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1175 // Now merge the entry of the triangle with the true block.
1176 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1177 MergeBlocks(BBI, *CvtBBI, false);
1180 // If 'true' block has a 'false' successor, add an exit branch to it.
1182 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1183 CvtBBI->BrCond.end());
1184 if (TII->ReverseBranchCondition(RevCond))
1185 llvm_unreachable("Unable to reverse branch condition!");
1186 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1187 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1190 // Merge in the 'false' block if the 'false' block has no other
1191 // predecessors. Otherwise, add an unconditional branch to 'false'.
1192 bool FalseBBDead = false;
1193 bool IterIfcvt = true;
1194 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1195 if (!isFallThrough) {
1196 // Only merge them if the true block does not fallthrough to the false
1197 // block. By not merging them, we make it possible to iteratively
1198 // ifcvt the blocks.
1199 if (!HasEarlyExit &&
1200 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1201 !NextBBI->BB->hasAddressTaken()) {
1202 MergeBlocks(BBI, *NextBBI);
1205 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1206 BBI.HasFallThrough = false;
1208 // Mixed predicated and unpredicated code. This cannot be iteratively
1213 RemoveExtraEdges(BBI);
1215 // Update block info. BB can be iteratively if-converted.
1218 InvalidatePreds(BBI.BB);
1219 CvtBBI->IsDone = true;
1221 NextBBI->IsDone = true;
1223 // FIXME: Must maintain LiveIns.
1227 /// IfConvertDiamond - If convert a diamond sub-CFG.
1229 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1230 unsigned NumDups1, unsigned NumDups2) {
1231 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1232 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1233 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1234 // True block must fall through or end with an unanalyzable terminator.
1236 if (blockAlwaysFallThrough(TrueBBI))
1237 TailBB = FalseBBI.TrueBB;
1238 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1241 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1242 TrueBBI.BB->pred_size() > 1 ||
1243 FalseBBI.BB->pred_size() > 1) {
1244 // Something has changed. It's no longer safe to predicate these blocks.
1245 BBI.IsAnalyzed = false;
1246 TrueBBI.IsAnalyzed = false;
1247 FalseBBI.IsAnalyzed = false;
1251 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1252 // Conservatively abort if-conversion if either BB has its address taken.
1255 // Put the predicated instructions from the 'true' block before the
1256 // instructions from the 'false' block, unless the true block would clobber
1257 // the predicate, in which case, do the opposite.
1258 BBInfo *BBI1 = &TrueBBI;
1259 BBInfo *BBI2 = &FalseBBI;
1260 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1261 if (TII->ReverseBranchCondition(RevCond))
1262 llvm_unreachable("Unable to reverse branch condition!");
1263 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1264 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1266 // Figure out the more profitable ordering.
1267 bool DoSwap = false;
1268 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1270 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1271 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1275 std::swap(BBI1, BBI2);
1276 std::swap(Cond1, Cond2);
1279 // Remove the conditional branch from entry to the blocks.
1280 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1282 // Initialize liveins to the first BB. These are potentially redefined by
1283 // predicated instructions.
1285 Redefs.addLiveIns(BBI1->BB);
1287 // Remove the duplicated instructions at the beginnings of both paths.
1288 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1289 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1290 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1291 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1292 // Skip dbg_value instructions
1293 while (DI1 != DIE1 && DI1->isDebugValue())
1295 while (DI2 != DIE2 && DI2->isDebugValue())
1297 BBI1->NonPredSize -= NumDups1;
1298 BBI2->NonPredSize -= NumDups1;
1300 // Skip past the dups on each side separately since there may be
1301 // differing dbg_value entries.
1302 for (unsigned i = 0; i < NumDups1; ++DI1) {
1303 if (!DI1->isDebugValue())
1306 while (NumDups1 != 0) {
1308 if (!DI2->isDebugValue())
1312 // Compute a set of registers which must not be killed by instructions in BB1:
1313 // This is everything used+live in BB2 after the duplicated instructions. We
1314 // can compute this set by simulating liveness backwards from the end of BB2.
1316 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1317 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
1318 DontKill.stepBackward(*I);
1321 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1323 Redefs.stepForward(*I);
1325 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1326 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1328 // Remove branch from 'true' block and remove duplicated instructions.
1329 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1330 DI1 = BBI1->BB->end();
1331 for (unsigned i = 0; i != NumDups2; ) {
1332 // NumDups2 only counted non-dbg_value instructions, so this won't
1333 // run off the head of the list.
1334 assert (DI1 != BBI1->BB->begin());
1336 // skip dbg_value instructions
1337 if (!DI1->isDebugValue())
1340 BBI1->BB->erase(DI1, BBI1->BB->end());
1342 // Kill flags in the true block for registers living into the false block
1344 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1346 // Remove 'false' block branch and find the last instruction to predicate.
1347 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1348 DI2 = BBI2->BB->end();
1349 while (NumDups2 != 0) {
1350 // NumDups2 only counted non-dbg_value instructions, so this won't
1351 // run off the head of the list.
1352 assert (DI2 != BBI2->BB->begin());
1354 // skip dbg_value instructions
1355 if (!DI2->isDebugValue())
1359 // Remember which registers would later be defined by the false block.
1360 // This allows us not to predicate instructions in the true block that would
1361 // later be re-defined. That is, rather than
1367 SmallSet<unsigned, 4> RedefsByFalse;
1368 SmallSet<unsigned, 4> ExtUses;
1369 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1370 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1371 if (FI->isDebugValue())
1373 SmallVector<unsigned, 4> Defs;
1374 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1375 const MachineOperand &MO = FI->getOperand(i);
1378 unsigned Reg = MO.getReg();
1382 Defs.push_back(Reg);
1383 } else if (!RedefsByFalse.count(Reg)) {
1384 // These are defined before ctrl flow reach the 'false' instructions.
1385 // They cannot be modified by the 'true' instructions.
1386 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1387 SubRegs.isValid(); ++SubRegs)
1388 ExtUses.insert(*SubRegs);
1392 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1393 unsigned Reg = Defs[i];
1394 if (!ExtUses.count(Reg)) {
1395 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1396 SubRegs.isValid(); ++SubRegs)
1397 RedefsByFalse.insert(*SubRegs);
1403 // Predicate the 'true' block.
1404 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
1406 // Predicate the 'false' block.
1407 PredicateBlock(*BBI2, DI2, *Cond2);
1409 // Merge the true block into the entry of the diamond.
1410 MergeBlocks(BBI, *BBI1, TailBB == 0);
1411 MergeBlocks(BBI, *BBI2, TailBB == 0);
1413 // If the if-converted block falls through or unconditionally branches into
1414 // the tail block, and the tail block does not have other predecessors, then
1415 // fold the tail block in as well. Otherwise, unless it falls through to the
1416 // tail, add a unconditional branch to it.
1418 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1419 bool CanMergeTail = !TailBBI.HasFallThrough &&
1420 !TailBBI.BB->hasAddressTaken();
1421 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1422 // check if there are any other predecessors besides those.
1423 unsigned NumPreds = TailBB->pred_size();
1425 CanMergeTail = false;
1426 else if (NumPreds == 1 && CanMergeTail) {
1427 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1428 if (*PI != BBI1->BB && *PI != BBI2->BB)
1429 CanMergeTail = false;
1432 MergeBlocks(BBI, TailBBI);
1433 TailBBI.IsDone = true;
1435 BBI.BB->addSuccessor(TailBB);
1436 InsertUncondBranch(BBI.BB, TailBB, TII);
1437 BBI.HasFallThrough = false;
1441 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1442 // which can happen here if TailBB is unanalyzable and is merged, so
1443 // explicitly remove BBI1 and BBI2 as successors.
1444 BBI.BB->removeSuccessor(BBI1->BB);
1445 BBI.BB->removeSuccessor(BBI2->BB);
1446 RemoveExtraEdges(BBI);
1448 // Update block info.
1449 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1450 InvalidatePreds(BBI.BB);
1452 // FIXME: Must maintain LiveIns.
1456 static bool MaySpeculate(const MachineInstr *MI,
1457 SmallSet<unsigned, 4> &LaterRedefs,
1458 const TargetInstrInfo *TII) {
1459 bool SawStore = true;
1460 if (!MI->isSafeToMove(TII, 0, SawStore))
1463 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1464 const MachineOperand &MO = MI->getOperand(i);
1467 unsigned Reg = MO.getReg();
1470 if (MO.isDef() && !LaterRedefs.count(Reg))
1477 /// PredicateBlock - Predicate instructions from the start of the block to the
1478 /// specified end with the specified condition.
1479 void IfConverter::PredicateBlock(BBInfo &BBI,
1480 MachineBasicBlock::iterator E,
1481 SmallVectorImpl<MachineOperand> &Cond,
1482 SmallSet<unsigned, 4> *LaterRedefs) {
1483 bool AnyUnpred = false;
1484 bool MaySpec = LaterRedefs != 0;
1485 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1486 if (I->isDebugValue() || TII->isPredicated(I))
1488 // It may be possible not to predicate an instruction if it's the 'true'
1489 // side of a diamond and the 'false' side may re-define the instruction's
1491 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1495 // If any instruction is predicated, then every instruction after it must
1498 if (!TII->PredicateInstruction(I, Cond)) {
1500 dbgs() << "Unable to predicate " << *I << "!\n";
1502 llvm_unreachable(0);
1505 // If the predicated instruction now redefines a register as the result of
1506 // if-conversion, add an implicit kill.
1507 UpdatePredRedefs(I, Redefs);
1510 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1512 BBI.IsAnalyzed = false;
1513 BBI.NonPredSize = 0;
1520 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1521 /// the destination block. Skip end of block branches if IgnoreBr is true.
1522 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1523 SmallVectorImpl<MachineOperand> &Cond,
1525 MachineFunction &MF = *ToBBI.BB->getParent();
1527 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1528 E = FromBBI.BB->end(); I != E; ++I) {
1529 // Do not copy the end of the block branches.
1530 if (IgnoreBr && I->isBranch())
1533 MachineInstr *MI = MF.CloneMachineInstr(I);
1534 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1535 ToBBI.NonPredSize++;
1536 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1537 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
1539 ToBBI.ExtraCost += NumCycles-1;
1540 ToBBI.ExtraCost2 += ExtraPredCost;
1542 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1543 if (!TII->PredicateInstruction(MI, Cond)) {
1545 dbgs() << "Unable to predicate " << *I << "!\n";
1547 llvm_unreachable(0);
1551 // If the predicated instruction now redefines a register as the result of
1552 // if-conversion, add an implicit kill.
1553 UpdatePredRedefs(MI, Redefs);
1555 // Some kill flags may not be correct anymore.
1556 if (!DontKill.empty())
1557 RemoveKills(*MI, DontKill);
1561 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1562 FromBBI.BB->succ_end());
1563 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1564 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1566 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1567 MachineBasicBlock *Succ = Succs[i];
1568 // Fallthrough edge can't be transferred.
1569 if (Succ == FallThrough)
1571 ToBBI.BB->addSuccessor(Succ);
1575 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1576 std::back_inserter(ToBBI.Predicate));
1577 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1579 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1580 ToBBI.IsAnalyzed = false;
1585 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1586 /// This will leave FromBB as an empty block, so remove all of its
1587 /// successor edges except for the fall-through edge. If AddEdges is true,
1588 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1590 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1591 assert(!FromBBI.BB->hasAddressTaken() &&
1592 "Removing a BB whose address is taken!");
1594 ToBBI.BB->splice(ToBBI.BB->end(),
1595 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1597 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1598 FromBBI.BB->succ_end());
1599 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1600 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1602 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1603 MachineBasicBlock *Succ = Succs[i];
1604 // Fallthrough edge can't be transferred.
1605 if (Succ == FallThrough)
1607 FromBBI.BB->removeSuccessor(Succ);
1608 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
1609 ToBBI.BB->addSuccessor(Succ);
1612 // Now FromBBI always falls through to the next block!
1613 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1614 FromBBI.BB->addSuccessor(NBB);
1616 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1617 std::back_inserter(ToBBI.Predicate));
1618 FromBBI.Predicate.clear();
1620 ToBBI.NonPredSize += FromBBI.NonPredSize;
1621 ToBBI.ExtraCost += FromBBI.ExtraCost;
1622 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1623 FromBBI.NonPredSize = 0;
1624 FromBBI.ExtraCost = 0;
1625 FromBBI.ExtraCost2 = 0;
1627 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1628 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1629 ToBBI.IsAnalyzed = false;
1630 FromBBI.IsAnalyzed = false;