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 "BranchFolding.h"
16 #include "llvm/Function.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/MC/MCInstrItineraries.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetRegisterInfo.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/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
36 // Hidden options for help debugging.
37 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
38 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
39 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
40 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
41 cl::init(false), cl::Hidden);
42 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
43 cl::init(false), cl::Hidden);
44 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
45 cl::init(false), cl::Hidden);
46 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
47 cl::init(false), cl::Hidden);
48 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
49 cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
51 cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
53 cl::init(false), cl::Hidden);
54 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
55 cl::init(true), cl::Hidden);
57 STATISTIC(NumSimple, "Number of simple if-conversions performed");
58 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
59 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
60 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
61 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
62 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
63 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
64 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
65 STATISTIC(NumDupBBs, "Number of duplicated blocks");
66 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
69 class IfConverter : public MachineFunctionPass {
71 ICNotClassfied, // BB data valid, but not classified.
72 ICSimpleFalse, // Same as ICSimple, but on the false path.
73 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
74 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
75 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
76 ICTriangleFalse, // Same as ICTriangle, but on the false path.
77 ICTriangle, // BB is entry of a triangle sub-CFG.
78 ICDiamond // BB is entry of a diamond sub-CFG.
81 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
82 /// if-conversion feasibility analysis. This includes results from
83 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
84 /// classification, and common tail block of its successors (if it's a
85 /// diamond shape), its size, whether it's predicable, and whether any
86 /// instruction can clobber the 'would-be' predicate.
88 /// IsDone - True if BB is not to be considered for ifcvt.
89 /// IsBeingAnalyzed - True if BB is currently being analyzed.
90 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
91 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
92 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
93 /// HasFallThrough - True if BB may fallthrough to the following BB.
94 /// IsUnpredicable - True if BB is known to be unpredicable.
95 /// ClobbersPred - True if BB could modify predicates (e.g. has
97 /// NonPredSize - Number of non-predicated instructions.
98 /// ExtraCost - Extra cost for multi-cycle instructions.
99 /// ExtraCost2 - Some instructions are slower when predicated
100 /// BB - Corresponding MachineBasicBlock.
101 /// TrueBB / FalseBB- See AnalyzeBranch().
102 /// BrCond - Conditions for end of block conditional branches.
103 /// Predicate - Predicate used in the BB.
106 bool IsBeingAnalyzed : 1;
109 bool IsBrAnalyzable : 1;
110 bool HasFallThrough : 1;
111 bool IsUnpredicable : 1;
112 bool CannotBeCopied : 1;
113 bool ClobbersPred : 1;
114 unsigned NonPredSize;
117 MachineBasicBlock *BB;
118 MachineBasicBlock *TrueBB;
119 MachineBasicBlock *FalseBB;
120 SmallVector<MachineOperand, 4> BrCond;
121 SmallVector<MachineOperand, 4> Predicate;
122 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
123 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
124 HasFallThrough(false), IsUnpredicable(false),
125 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
126 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
129 /// IfcvtToken - Record information about pending if-conversions to attempt:
130 /// BBI - Corresponding BBInfo.
131 /// Kind - Type of block. See IfcvtKind.
132 /// NeedSubsumption - True if the to-be-predicated BB has already been
134 /// NumDups - Number of instructions that would be duplicated due
135 /// to this if-conversion. (For diamonds, the number of
136 /// identical instructions at the beginnings of both
138 /// NumDups2 - For diamonds, the number of identical instructions
139 /// at the ends of both paths.
143 bool NeedSubsumption;
146 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
147 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
150 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
151 /// basic block number.
152 std::vector<BBInfo> BBAnalysis;
154 const TargetLowering *TLI;
155 const TargetInstrInfo *TII;
156 const TargetRegisterInfo *TRI;
157 const InstrItineraryData *InstrItins;
158 const MachineBranchProbabilityInfo *MBPI;
159 MachineRegisterInfo *MRI;
166 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
167 initializeIfConverterPass(*PassRegistry::getPassRegistry());
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.addRequired<MachineBranchProbabilityInfo>();
172 MachineFunctionPass::getAnalysisUsage(AU);
175 virtual bool runOnMachineFunction(MachineFunction &MF);
178 bool ReverseBranchCondition(BBInfo &BBI);
179 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
180 const BranchProbability &Prediction) const;
181 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
182 bool FalseBranch, unsigned &Dups,
183 const BranchProbability &Prediction) const;
184 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
185 unsigned &Dups1, unsigned &Dups2) const;
186 void ScanInstructions(BBInfo &BBI);
187 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
188 std::vector<IfcvtToken*> &Tokens);
189 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
190 bool isTriangle = false, bool RevBranch = false);
191 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
192 void InvalidatePreds(MachineBasicBlock *BB);
193 void RemoveExtraEdges(BBInfo &BBI);
194 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
195 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
196 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
197 unsigned NumDups1, unsigned NumDups2);
198 void PredicateBlock(BBInfo &BBI,
199 MachineBasicBlock::iterator E,
200 SmallVectorImpl<MachineOperand> &Cond,
201 SmallSet<unsigned, 4> &Redefs,
202 SmallSet<unsigned, 4> *LaterRedefs = 0);
203 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
204 SmallVectorImpl<MachineOperand> &Cond,
205 SmallSet<unsigned, 4> &Redefs,
206 bool IgnoreBr = false);
207 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
209 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
210 unsigned Cycle, unsigned Extra,
211 const BranchProbability &Prediction) const {
212 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
216 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
217 unsigned TCycle, unsigned TExtra,
218 MachineBasicBlock &FBB,
219 unsigned FCycle, unsigned FExtra,
220 const BranchProbability &Prediction) const {
221 return TCycle > 0 && FCycle > 0 &&
222 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
226 // blockAlwaysFallThrough - Block ends without a terminator.
227 bool blockAlwaysFallThrough(BBInfo &BBI) const {
228 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
231 // IfcvtTokenCmp - Used to sort if-conversion candidates.
232 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
233 int Incr1 = (C1->Kind == ICDiamond)
234 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
235 int Incr2 = (C2->Kind == ICDiamond)
236 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
239 else if (Incr1 == Incr2) {
240 // Favors subsumption.
241 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
243 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
244 // Favors diamond over triangle, etc.
245 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
247 else if (C1->Kind == C2->Kind)
248 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
255 char IfConverter::ID = 0;
258 char &llvm::IfConverterID = IfConverter::ID;
260 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
261 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
262 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
264 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
265 TLI = MF.getTarget().getTargetLowering();
266 TII = MF.getTarget().getInstrInfo();
267 TRI = MF.getTarget().getRegisterInfo();
268 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
269 MRI = &MF.getRegInfo();
270 InstrItins = MF.getTarget().getInstrItineraryData();
271 if (!TII) return false;
273 PreRegAlloc = MRI->isSSA();
275 bool BFChange = false;
277 // Tail merge tend to expose more if-conversion opportunities.
278 BranchFolder BF(true, false);
279 BFChange = BF.OptimizeFunction(MF, TII,
280 MF.getTarget().getRegisterInfo(),
281 getAnalysisIfAvailable<MachineModuleInfo>());
284 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
285 << MF.getFunction()->getName() << "\'");
287 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
288 DEBUG(dbgs() << " skipped\n");
291 DEBUG(dbgs() << "\n");
294 BBAnalysis.resize(MF.getNumBlockIDs());
296 std::vector<IfcvtToken*> Tokens;
298 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
299 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
300 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
301 // Do an initial analysis for each basic block and find all the potential
302 // candidates to perform if-conversion.
304 AnalyzeBlocks(MF, Tokens);
305 while (!Tokens.empty()) {
306 IfcvtToken *Token = Tokens.back();
308 BBInfo &BBI = Token->BBI;
309 IfcvtKind Kind = Token->Kind;
310 unsigned NumDups = Token->NumDups;
311 unsigned NumDups2 = Token->NumDups2;
315 // If the block has been evicted out of the queue or it has already been
316 // marked dead (due to it being predicated), then skip it.
318 BBI.IsEnqueued = false;
322 BBI.IsEnqueued = false;
326 default: llvm_unreachable("Unexpected!");
328 case ICSimpleFalse: {
329 bool isFalse = Kind == ICSimpleFalse;
330 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
331 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
333 << "): BB#" << BBI.BB->getNumber() << " ("
334 << ((Kind == ICSimpleFalse)
335 ? BBI.FalseBB->getNumber()
336 : BBI.TrueBB->getNumber()) << ") ");
337 RetVal = IfConvertSimple(BBI, Kind);
338 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
340 if (isFalse) ++NumSimpleFalse;
347 case ICTriangleFalse:
348 case ICTriangleFRev: {
349 bool isFalse = Kind == ICTriangleFalse;
350 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
351 if (DisableTriangle && !isFalse && !isRev) break;
352 if (DisableTriangleR && !isFalse && isRev) break;
353 if (DisableTriangleF && isFalse && !isRev) break;
354 if (DisableTriangleFR && isFalse && isRev) break;
355 DEBUG(dbgs() << "Ifcvt (Triangle");
357 DEBUG(dbgs() << " false");
359 DEBUG(dbgs() << " rev");
360 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
361 << BBI.TrueBB->getNumber() << ",F:"
362 << BBI.FalseBB->getNumber() << ") ");
363 RetVal = IfConvertTriangle(BBI, Kind);
364 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
367 if (isRev) ++NumTriangleFRev;
368 else ++NumTriangleFalse;
370 if (isRev) ++NumTriangleRev;
377 if (DisableDiamond) break;
378 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
379 << BBI.TrueBB->getNumber() << ",F:"
380 << BBI.FalseBB->getNumber() << ") ");
381 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
382 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
383 if (RetVal) ++NumDiamonds;
390 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
391 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
392 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
398 MadeChange |= Change;
401 // Delete tokens in case of early exit.
402 while (!Tokens.empty()) {
403 IfcvtToken *Token = Tokens.back();
411 if (MadeChange && IfCvtBranchFold) {
412 BranchFolder BF(false, false);
413 BF.OptimizeFunction(MF, TII,
414 MF.getTarget().getRegisterInfo(),
415 getAnalysisIfAvailable<MachineModuleInfo>());
418 MadeChange |= BFChange;
422 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
423 /// its 'true' successor.
424 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
425 MachineBasicBlock *TrueBB) {
426 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
427 E = BB->succ_end(); SI != E; ++SI) {
428 MachineBasicBlock *SuccBB = *SI;
429 if (SuccBB != TrueBB)
435 /// ReverseBranchCondition - Reverse the condition of the end of the block
436 /// branch. Swap block's 'true' and 'false' successors.
437 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
438 DebugLoc dl; // FIXME: this is nowhere
439 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
440 TII->RemoveBranch(*BBI.BB);
441 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
442 std::swap(BBI.TrueBB, BBI.FalseBB);
448 /// getNextBlock - Returns the next block in the function blocks ordering. If
449 /// it is the end, returns NULL.
450 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
451 MachineFunction::iterator I = BB;
452 MachineFunction::iterator E = BB->getParent()->end();
458 /// ValidSimple - Returns true if the 'true' block (along with its
459 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
460 /// number of instructions that the ifcvt would need to duplicate if performed
462 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
463 const BranchProbability &Prediction) const {
465 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
468 if (TrueBBI.IsBrAnalyzable)
471 if (TrueBBI.BB->pred_size() > 1) {
472 if (TrueBBI.CannotBeCopied ||
473 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
476 Dups = TrueBBI.NonPredSize;
482 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
483 /// with their common predecessor) forms a valid triangle shape for ifcvt.
484 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
485 /// branches to the 'false' block rather than the other way around. It also
486 /// returns the number of instructions that the ifcvt would need to duplicate
487 /// if performed in 'Dups'.
488 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
489 bool FalseBranch, unsigned &Dups,
490 const BranchProbability &Prediction) const {
492 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
495 if (TrueBBI.BB->pred_size() > 1) {
496 if (TrueBBI.CannotBeCopied)
499 unsigned Size = TrueBBI.NonPredSize;
500 if (TrueBBI.IsBrAnalyzable) {
501 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
502 // Ends with an unconditional branch. It will be removed.
505 MachineBasicBlock *FExit = FalseBranch
506 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
508 // Require a conditional branch
512 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
517 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
518 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
519 MachineFunction::iterator I = TrueBBI.BB;
520 if (++I == TrueBBI.BB->getParent()->end())
524 return TExit && TExit == FalseBBI.BB;
527 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
528 /// with their common predecessor) forms a valid diamond shape for ifcvt.
529 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
530 unsigned &Dups1, unsigned &Dups2) const {
532 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
533 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
536 MachineBasicBlock *TT = TrueBBI.TrueBB;
537 MachineBasicBlock *FT = FalseBBI.TrueBB;
539 if (!TT && blockAlwaysFallThrough(TrueBBI))
540 TT = getNextBlock(TrueBBI.BB);
541 if (!FT && blockAlwaysFallThrough(FalseBBI))
542 FT = getNextBlock(FalseBBI.BB);
545 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
547 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
550 // FIXME: Allow true block to have an early exit?
551 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
552 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
555 // Count duplicate instructions at the beginning of the true and false blocks.
556 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
557 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
558 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
559 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
560 while (TIB != TIE && FIB != FIE) {
561 // Skip dbg_value instructions. These do not count.
562 if (TIB->isDebugValue()) {
563 while (TIB != TIE && TIB->isDebugValue())
568 if (FIB->isDebugValue()) {
569 while (FIB != FIE && FIB->isDebugValue())
574 if (!TIB->isIdenticalTo(FIB))
581 // Now, in preparation for counting duplicate instructions at the ends of the
582 // blocks, move the end iterators up past any branch instructions.
585 if (!TIE->isBranch())
590 if (!FIE->isBranch())
594 // If Dups1 includes all of a block, then don't count duplicate
595 // instructions at the end of the blocks.
596 if (TIB == TIE || FIB == FIE)
599 // Count duplicate instructions at the ends of the blocks.
600 while (TIE != TIB && FIE != FIB) {
601 // Skip dbg_value instructions. These do not count.
602 if (TIE->isDebugValue()) {
603 while (TIE != TIB && TIE->isDebugValue())
608 if (FIE->isDebugValue()) {
609 while (FIE != FIB && FIE->isDebugValue())
614 if (!TIE->isIdenticalTo(FIE))
624 /// ScanInstructions - Scan all the instructions in the block to determine if
625 /// the block is predicable. In most cases, that means all the instructions
626 /// in the block are isPredicable(). Also checks if the block contains any
627 /// instruction which can clobber a predicate (e.g. condition code register).
628 /// If so, the block is not predicable unless it's the last instruction.
629 void IfConverter::ScanInstructions(BBInfo &BBI) {
633 bool AlreadyPredicated = !BBI.Predicate.empty();
634 // First analyze the end of BB branches.
635 BBI.TrueBB = BBI.FalseBB = NULL;
638 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
639 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
641 if (BBI.BrCond.size()) {
642 // No false branch. This BB must end with a conditional branch and a
645 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
647 // Malformed bcc? True and false blocks are the same?
648 BBI.IsUnpredicable = true;
653 // Then scan all the instructions.
657 BBI.ClobbersPred = false;
658 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
660 if (I->isDebugValue())
663 if (I->isNotDuplicable())
664 BBI.CannotBeCopied = true;
666 bool isPredicated = TII->isPredicated(I);
667 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
672 unsigned ExtraPredCost = 0;
673 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
676 BBI.ExtraCost += NumCycles-1;
677 BBI.ExtraCost2 += ExtraPredCost;
678 } else if (!AlreadyPredicated) {
679 // FIXME: This instruction is already predicated before the
680 // if-conversion pass. It's probably something like a conditional move.
681 // Mark this block unpredicable for now.
682 BBI.IsUnpredicable = true;
687 if (BBI.ClobbersPred && !isPredicated) {
688 // Predicate modification instruction should end the block (except for
689 // already predicated instructions and end of block branches).
691 // A conditional branch is not predicable, but it may be eliminated.
695 // Predicate may have been modified, the subsequent (currently)
696 // unpredicated instructions cannot be correctly predicated.
697 BBI.IsUnpredicable = true;
701 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
702 // still potentially predicable.
703 std::vector<MachineOperand> PredDefs;
704 if (TII->DefinesPredicate(I, PredDefs))
705 BBI.ClobbersPred = true;
707 if (!TII->isPredicable(I)) {
708 BBI.IsUnpredicable = true;
714 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
715 /// predicated by the specified predicate.
716 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
717 SmallVectorImpl<MachineOperand> &Pred,
718 bool isTriangle, bool RevBranch) {
719 // If the block is dead or unpredicable, then it cannot be predicated.
720 if (BBI.IsDone || BBI.IsUnpredicable)
723 // If it is already predicated, check if its predicate subsumes the new
725 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
728 if (BBI.BrCond.size()) {
732 // Test predicate subsumption.
733 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
734 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
736 if (TII->ReverseBranchCondition(Cond))
739 if (TII->ReverseBranchCondition(RevPred) ||
740 !TII->SubsumesPredicate(Cond, RevPred))
747 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
748 /// the specified block. Record its successors and whether it looks like an
749 /// if-conversion candidate.
750 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
751 std::vector<IfcvtToken*> &Tokens) {
752 BBInfo &BBI = BBAnalysis[BB->getNumber()];
754 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
758 BBI.IsBeingAnalyzed = true;
760 ScanInstructions(BBI);
762 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
763 // considered for ifcvt anymore.
764 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
765 BBI.IsBeingAnalyzed = false;
766 BBI.IsAnalyzed = true;
770 // Do not ifcvt if either path is a back edge to the entry block.
771 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
772 BBI.IsBeingAnalyzed = false;
773 BBI.IsAnalyzed = true;
777 // Do not ifcvt if true and false fallthrough blocks are the same.
779 BBI.IsBeingAnalyzed = false;
780 BBI.IsAnalyzed = true;
784 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
785 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
787 if (TrueBBI.IsDone && FalseBBI.IsDone) {
788 BBI.IsBeingAnalyzed = false;
789 BBI.IsAnalyzed = true;
793 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
794 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
798 bool TNeedSub = !TrueBBI.Predicate.empty();
799 bool FNeedSub = !FalseBBI.Predicate.empty();
800 bool Enqueued = false;
802 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
804 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
805 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
806 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
807 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
808 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
810 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
811 FeasibilityAnalysis(FalseBBI, RevCond)) {
819 // Note TailBB can be empty.
820 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
825 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
826 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
827 TrueBBI.ExtraCost2, Prediction) &&
828 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
836 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
840 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
841 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
842 TrueBBI.ExtraCost2, Prediction) &&
843 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
844 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
848 if (ValidSimple(TrueBBI, Dups, Prediction) &&
849 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
850 TrueBBI.ExtraCost2, Prediction) &&
851 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
852 // Simple (split, no rejoin):
859 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
864 // Try the other path...
865 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
866 Prediction.getCompl()) &&
867 MeetIfcvtSizeLimit(*FalseBBI.BB,
868 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
869 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
870 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
871 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
875 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
876 Prediction.getCompl()) &&
877 MeetIfcvtSizeLimit(*FalseBBI.BB,
878 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
879 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
880 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
881 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
885 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
886 MeetIfcvtSizeLimit(*FalseBBI.BB,
887 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
888 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
889 FeasibilityAnalysis(FalseBBI, RevCond)) {
890 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
895 BBI.IsEnqueued = Enqueued;
896 BBI.IsBeingAnalyzed = false;
897 BBI.IsAnalyzed = true;
901 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
903 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
904 std::vector<IfcvtToken*> &Tokens) {
905 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
906 MachineBasicBlock *BB = I;
907 AnalyzeBlock(BB, Tokens);
910 // Sort to favor more complex ifcvt scheme.
911 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
914 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
915 /// that all the intervening blocks are empty (given BB can fall through to its
917 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
918 MachineFunction::iterator PI = BB;
919 MachineFunction::iterator I = llvm::next(PI);
920 MachineFunction::iterator TI = ToBB;
921 MachineFunction::iterator E = BB->getParent()->end();
923 // Check isSuccessor to avoid case where the next block is empty, but
924 // it's not a successor.
925 if (I == E || !I->empty() || !PI->isSuccessor(I))
932 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
933 /// to determine if it can be if-converted. If predecessor is already enqueued,
935 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
936 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
937 E = BB->pred_end(); PI != E; ++PI) {
938 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
939 if (PBBI.IsDone || PBBI.BB == BB)
941 PBBI.IsAnalyzed = false;
942 PBBI.IsEnqueued = false;
946 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
948 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
949 const TargetInstrInfo *TII) {
950 DebugLoc dl; // FIXME: this is nowhere
951 SmallVector<MachineOperand, 0> NoCond;
952 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
955 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
957 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
958 MachineBasicBlock *TBB = NULL, *FBB = NULL;
959 SmallVector<MachineOperand, 4> Cond;
960 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
961 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
964 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
965 /// modeled as read + write (sort like two-address instructions). These
966 /// routines track register liveness and add implicit uses to if-converted
967 /// instructions to conform to the model.
968 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
969 const TargetRegisterInfo *TRI) {
970 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
971 E = BB->livein_end(); I != E; ++I) {
974 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
975 Redefs.insert(*SubRegs);
979 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
980 const TargetRegisterInfo *TRI,
981 bool AddImpUse = false) {
982 SmallVector<unsigned, 4> Defs;
983 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
984 const MachineOperand &MO = MI->getOperand(i);
987 unsigned Reg = MO.getReg();
992 else if (MO.isKill()) {
994 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
995 Redefs.erase(*SubRegs);
998 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
999 unsigned Reg = Defs[i];
1000 if (Redefs.count(Reg)) {
1002 // Treat predicated update as read + write.
1003 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
1004 true/*IsImp*/,false/*IsKill*/,
1005 false/*IsDead*/,true/*IsUndef*/));
1008 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1009 Redefs.insert(*SubRegs);
1014 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1015 MachineBasicBlock::iterator E,
1016 SmallSet<unsigned,4> &Redefs,
1017 const TargetRegisterInfo *TRI) {
1019 UpdatePredRedefs(I, Redefs, TRI);
1024 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1026 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1027 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1028 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1029 BBInfo *CvtBBI = &TrueBBI;
1030 BBInfo *NextBBI = &FalseBBI;
1032 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1033 if (Kind == ICSimpleFalse)
1034 std::swap(CvtBBI, NextBBI);
1036 if (CvtBBI->IsDone ||
1037 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1038 // Something has changed. It's no longer safe to predicate this block.
1039 BBI.IsAnalyzed = false;
1040 CvtBBI->IsAnalyzed = false;
1044 if (Kind == ICSimpleFalse)
1045 if (TII->ReverseBranchCondition(Cond))
1046 llvm_unreachable("Unable to reverse branch condition!");
1048 // Initialize liveins to the first BB. These are potentiall redefined by
1049 // predicated instructions.
1050 SmallSet<unsigned, 4> Redefs;
1051 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1052 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1054 if (CvtBBI->BB->pred_size() > 1) {
1055 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1056 // Copy instructions in the true block, predicate them, and add them to
1058 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1060 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1062 // Merge converted block into entry block.
1063 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1064 MergeBlocks(BBI, *CvtBBI);
1067 bool IterIfcvt = true;
1068 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1069 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1070 BBI.HasFallThrough = false;
1071 // Now ifcvt'd block will look like this:
1078 // We cannot further ifcvt this block because the unconditional branch
1079 // will have to be predicated on the new condition, that will not be
1080 // available if cmp executes.
1084 RemoveExtraEdges(BBI);
1086 // Update block info. BB can be iteratively if-converted.
1089 InvalidatePreds(BBI.BB);
1090 CvtBBI->IsDone = true;
1092 // FIXME: Must maintain LiveIns.
1096 /// IfConvertTriangle - If convert a triangle sub-CFG.
1098 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1099 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1100 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1101 BBInfo *CvtBBI = &TrueBBI;
1102 BBInfo *NextBBI = &FalseBBI;
1103 DebugLoc dl; // FIXME: this is nowhere
1105 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1106 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1107 std::swap(CvtBBI, NextBBI);
1109 if (CvtBBI->IsDone ||
1110 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1111 // Something has changed. It's no longer safe to predicate this block.
1112 BBI.IsAnalyzed = false;
1113 CvtBBI->IsAnalyzed = false;
1117 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1118 if (TII->ReverseBranchCondition(Cond))
1119 llvm_unreachable("Unable to reverse branch condition!");
1121 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1122 if (ReverseBranchCondition(*CvtBBI)) {
1123 // BB has been changed, modify its predecessors (except for this
1124 // one) so they don't get ifcvt'ed based on bad intel.
1125 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1126 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1127 MachineBasicBlock *PBB = *PI;
1130 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1131 if (PBBI.IsEnqueued) {
1132 PBBI.IsAnalyzed = false;
1133 PBBI.IsEnqueued = false;
1139 // Initialize liveins to the first BB. These are potentially redefined by
1140 // predicated instructions.
1141 SmallSet<unsigned, 4> Redefs;
1142 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1143 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1145 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1146 if (CvtBBI->BB->pred_size() > 1) {
1147 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1148 // Copy instructions in the true block, predicate them, and add them to
1150 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1152 // Predicate the 'true' block after removing its branch.
1153 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1154 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1156 // Now merge the entry of the triangle with the true block.
1157 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1158 MergeBlocks(BBI, *CvtBBI, false);
1161 // If 'true' block has a 'false' successor, add an exit branch to it.
1163 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1164 CvtBBI->BrCond.end());
1165 if (TII->ReverseBranchCondition(RevCond))
1166 llvm_unreachable("Unable to reverse branch condition!");
1167 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1168 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1171 // Merge in the 'false' block if the 'false' block has no other
1172 // predecessors. Otherwise, add an unconditional branch to 'false'.
1173 bool FalseBBDead = false;
1174 bool IterIfcvt = true;
1175 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1176 if (!isFallThrough) {
1177 // Only merge them if the true block does not fallthrough to the false
1178 // block. By not merging them, we make it possible to iteratively
1179 // ifcvt the blocks.
1180 if (!HasEarlyExit &&
1181 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1182 MergeBlocks(BBI, *NextBBI);
1185 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1186 BBI.HasFallThrough = false;
1188 // Mixed predicated and unpredicated code. This cannot be iteratively
1193 RemoveExtraEdges(BBI);
1195 // Update block info. BB can be iteratively if-converted.
1198 InvalidatePreds(BBI.BB);
1199 CvtBBI->IsDone = true;
1201 NextBBI->IsDone = true;
1203 // FIXME: Must maintain LiveIns.
1207 /// IfConvertDiamond - If convert a diamond sub-CFG.
1209 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1210 unsigned NumDups1, unsigned NumDups2) {
1211 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1212 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1213 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1214 // True block must fall through or end with an unanalyzable terminator.
1216 if (blockAlwaysFallThrough(TrueBBI))
1217 TailBB = FalseBBI.TrueBB;
1218 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1221 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1222 TrueBBI.BB->pred_size() > 1 ||
1223 FalseBBI.BB->pred_size() > 1) {
1224 // Something has changed. It's no longer safe to predicate these blocks.
1225 BBI.IsAnalyzed = false;
1226 TrueBBI.IsAnalyzed = false;
1227 FalseBBI.IsAnalyzed = false;
1231 // Put the predicated instructions from the 'true' block before the
1232 // instructions from the 'false' block, unless the true block would clobber
1233 // the predicate, in which case, do the opposite.
1234 BBInfo *BBI1 = &TrueBBI;
1235 BBInfo *BBI2 = &FalseBBI;
1236 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1237 if (TII->ReverseBranchCondition(RevCond))
1238 llvm_unreachable("Unable to reverse branch condition!");
1239 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1240 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1242 // Figure out the more profitable ordering.
1243 bool DoSwap = false;
1244 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1246 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1247 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1251 std::swap(BBI1, BBI2);
1252 std::swap(Cond1, Cond2);
1255 // Remove the conditional branch from entry to the blocks.
1256 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1258 // Initialize liveins to the first BB. These are potentially redefined by
1259 // predicated instructions.
1260 SmallSet<unsigned, 4> Redefs;
1261 InitPredRedefs(BBI1->BB, Redefs, TRI);
1263 // Remove the duplicated instructions at the beginnings of both paths.
1264 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1265 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1266 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1267 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1268 // Skip dbg_value instructions
1269 while (DI1 != DIE1 && DI1->isDebugValue())
1271 while (DI2 != DIE2 && DI2->isDebugValue())
1273 BBI1->NonPredSize -= NumDups1;
1274 BBI2->NonPredSize -= NumDups1;
1276 // Skip past the dups on each side separately since there may be
1277 // differing dbg_value entries.
1278 for (unsigned i = 0; i < NumDups1; ++DI1) {
1279 if (!DI1->isDebugValue())
1282 while (NumDups1 != 0) {
1284 if (!DI2->isDebugValue())
1288 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1289 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1290 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1292 // Remove branch from 'true' block and remove duplicated instructions.
1293 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1294 DI1 = BBI1->BB->end();
1295 for (unsigned i = 0; i != NumDups2; ) {
1296 // NumDups2 only counted non-dbg_value instructions, so this won't
1297 // run off the head of the list.
1298 assert (DI1 != BBI1->BB->begin());
1300 // skip dbg_value instructions
1301 if (!DI1->isDebugValue())
1304 BBI1->BB->erase(DI1, BBI1->BB->end());
1306 // Remove 'false' block branch and find the last instruction to predicate.
1307 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1308 DI2 = BBI2->BB->end();
1309 while (NumDups2 != 0) {
1310 // NumDups2 only counted non-dbg_value instructions, so this won't
1311 // run off the head of the list.
1312 assert (DI2 != BBI2->BB->begin());
1314 // skip dbg_value instructions
1315 if (!DI2->isDebugValue())
1319 // Remember which registers would later be defined by the false block.
1320 // This allows us not to predicate instructions in the true block that would
1321 // later be re-defined. That is, rather than
1327 SmallSet<unsigned, 4> RedefsByFalse;
1328 SmallSet<unsigned, 4> ExtUses;
1329 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1330 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1331 if (FI->isDebugValue())
1333 SmallVector<unsigned, 4> Defs;
1334 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1335 const MachineOperand &MO = FI->getOperand(i);
1338 unsigned Reg = MO.getReg();
1342 Defs.push_back(Reg);
1343 } else if (!RedefsByFalse.count(Reg)) {
1344 // These are defined before ctrl flow reach the 'false' instructions.
1345 // They cannot be modified by the 'true' instructions.
1346 ExtUses.insert(Reg);
1347 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1348 ExtUses.insert(*SubRegs);
1352 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1353 unsigned Reg = Defs[i];
1354 if (!ExtUses.count(Reg)) {
1355 RedefsByFalse.insert(Reg);
1356 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
1357 RedefsByFalse.insert(*SubRegs);
1363 // Predicate the 'true' block.
1364 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1366 // Predicate the 'false' block.
1367 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1369 // Merge the true block into the entry of the diamond.
1370 MergeBlocks(BBI, *BBI1, TailBB == 0);
1371 MergeBlocks(BBI, *BBI2, TailBB == 0);
1373 // If the if-converted block falls through or unconditionally branches into
1374 // the tail block, and the tail block does not have other predecessors, then
1375 // fold the tail block in as well. Otherwise, unless it falls through to the
1376 // tail, add a unconditional branch to it.
1378 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1379 bool CanMergeTail = !TailBBI.HasFallThrough;
1380 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1381 // check if there are any other predecessors besides those.
1382 unsigned NumPreds = TailBB->pred_size();
1384 CanMergeTail = false;
1385 else if (NumPreds == 1 && CanMergeTail) {
1386 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1387 if (*PI != BBI1->BB && *PI != BBI2->BB)
1388 CanMergeTail = false;
1391 MergeBlocks(BBI, TailBBI);
1392 TailBBI.IsDone = true;
1394 BBI.BB->addSuccessor(TailBB);
1395 InsertUncondBranch(BBI.BB, TailBB, TII);
1396 BBI.HasFallThrough = false;
1400 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1401 // which can happen here if TailBB is unanalyzable and is merged, so
1402 // explicitly remove BBI1 and BBI2 as successors.
1403 BBI.BB->removeSuccessor(BBI1->BB);
1404 BBI.BB->removeSuccessor(BBI2->BB);
1405 RemoveExtraEdges(BBI);
1407 // Update block info.
1408 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1409 InvalidatePreds(BBI.BB);
1411 // FIXME: Must maintain LiveIns.
1415 static bool MaySpeculate(const MachineInstr *MI,
1416 SmallSet<unsigned, 4> &LaterRedefs,
1417 const TargetInstrInfo *TII) {
1418 bool SawStore = true;
1419 if (!MI->isSafeToMove(TII, 0, SawStore))
1422 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1423 const MachineOperand &MO = MI->getOperand(i);
1426 unsigned Reg = MO.getReg();
1429 if (MO.isDef() && !LaterRedefs.count(Reg))
1436 /// PredicateBlock - Predicate instructions from the start of the block to the
1437 /// specified end with the specified condition.
1438 void IfConverter::PredicateBlock(BBInfo &BBI,
1439 MachineBasicBlock::iterator E,
1440 SmallVectorImpl<MachineOperand> &Cond,
1441 SmallSet<unsigned, 4> &Redefs,
1442 SmallSet<unsigned, 4> *LaterRedefs) {
1443 bool AnyUnpred = false;
1444 bool MaySpec = LaterRedefs != 0;
1445 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1446 if (I->isDebugValue() || TII->isPredicated(I))
1448 // It may be possible not to predicate an instruction if it's the 'true'
1449 // side of a diamond and the 'false' side may re-define the instruction's
1451 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1455 // If any instruction is predicated, then every instruction after it must
1458 if (!TII->PredicateInstruction(I, Cond)) {
1460 dbgs() << "Unable to predicate " << *I << "!\n";
1462 llvm_unreachable(0);
1465 // If the predicated instruction now redefines a register as the result of
1466 // if-conversion, add an implicit kill.
1467 UpdatePredRedefs(I, Redefs, TRI, true);
1470 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1472 BBI.IsAnalyzed = false;
1473 BBI.NonPredSize = 0;
1480 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1481 /// the destination block. Skip end of block branches if IgnoreBr is true.
1482 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1483 SmallVectorImpl<MachineOperand> &Cond,
1484 SmallSet<unsigned, 4> &Redefs,
1486 MachineFunction &MF = *ToBBI.BB->getParent();
1488 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1489 E = FromBBI.BB->end(); I != E; ++I) {
1490 // Do not copy the end of the block branches.
1491 if (IgnoreBr && I->isBranch())
1494 MachineInstr *MI = MF.CloneMachineInstr(I);
1495 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1496 ToBBI.NonPredSize++;
1497 unsigned ExtraPredCost = 0;
1498 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1500 ToBBI.ExtraCost += NumCycles-1;
1501 ToBBI.ExtraCost2 += ExtraPredCost;
1503 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1504 if (!TII->PredicateInstruction(MI, Cond)) {
1506 dbgs() << "Unable to predicate " << *I << "!\n";
1508 llvm_unreachable(0);
1512 // If the predicated instruction now redefines a register as the result of
1513 // if-conversion, add an implicit kill.
1514 UpdatePredRedefs(MI, Redefs, TRI, true);
1518 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1519 FromBBI.BB->succ_end());
1520 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1521 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1523 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1524 MachineBasicBlock *Succ = Succs[i];
1525 // Fallthrough edge can't be transferred.
1526 if (Succ == FallThrough)
1528 ToBBI.BB->addSuccessor(Succ);
1532 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1533 std::back_inserter(ToBBI.Predicate));
1534 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1536 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1537 ToBBI.IsAnalyzed = false;
1542 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1543 /// This will leave FromBB as an empty block, so remove all of its
1544 /// successor edges except for the fall-through edge. If AddEdges is true,
1545 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1547 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1548 ToBBI.BB->splice(ToBBI.BB->end(),
1549 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1551 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1552 FromBBI.BB->succ_end());
1553 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1554 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1556 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1557 MachineBasicBlock *Succ = Succs[i];
1558 // Fallthrough edge can't be transferred.
1559 if (Succ == FallThrough)
1561 FromBBI.BB->removeSuccessor(Succ);
1563 ToBBI.BB->addSuccessor(Succ);
1566 // Now FromBBI always falls through to the next block!
1567 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1568 FromBBI.BB->addSuccessor(NBB);
1570 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1571 std::back_inserter(ToBBI.Predicate));
1572 FromBBI.Predicate.clear();
1574 ToBBI.NonPredSize += FromBBI.NonPredSize;
1575 ToBBI.ExtraCost += FromBBI.ExtraCost;
1576 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1577 FromBBI.NonPredSize = 0;
1578 FromBBI.ExtraCost = 0;
1579 FromBBI.ExtraCost2 = 0;
1581 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1582 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1583 ToBBI.IsAnalyzed = false;
1584 FromBBI.IsAnalyzed = false;