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/MC/MCInstrItineraries.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
35 // Hidden options for help debugging.
36 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
39 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
40 cl::init(false), cl::Hidden);
41 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
42 cl::init(false), cl::Hidden);
43 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
44 cl::init(false), cl::Hidden);
45 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
46 cl::init(false), cl::Hidden);
47 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
48 cl::init(false), cl::Hidden);
49 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
50 cl::init(false), cl::Hidden);
51 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
52 cl::init(false), cl::Hidden);
53 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
56 STATISTIC(NumSimple, "Number of simple if-conversions performed");
57 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
59 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
60 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
64 STATISTIC(NumDupBBs, "Number of duplicated blocks");
65 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
68 class IfConverter : public MachineFunctionPass {
70 ICNotClassfied, // BB data valid, but not classified.
71 ICSimpleFalse, // Same as ICSimple, but on the false path.
72 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
73 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
74 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
75 ICTriangleFalse, // Same as ICTriangle, but on the false path.
76 ICTriangle, // BB is entry of a triangle sub-CFG.
77 ICDiamond // BB is entry of a diamond sub-CFG.
80 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
81 /// if-conversion feasibility analysis. This includes results from
82 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
83 /// classification, and common tail block of its successors (if it's a
84 /// diamond shape), its size, whether it's predicable, and whether any
85 /// instruction can clobber the 'would-be' predicate.
87 /// IsDone - True if BB is not to be considered for ifcvt.
88 /// IsBeingAnalyzed - True if BB is currently being analyzed.
89 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
90 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
91 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
92 /// HasFallThrough - True if BB may fallthrough to the following BB.
93 /// IsUnpredicable - True if BB is known to be unpredicable.
94 /// ClobbersPred - True if BB could modify predicates (e.g. has
96 /// NonPredSize - Number of non-predicated instructions.
97 /// ExtraCost - Extra cost for multi-cycle instructions.
98 /// ExtraCost2 - Some instructions are slower when predicated
99 /// BB - Corresponding MachineBasicBlock.
100 /// TrueBB / FalseBB- See AnalyzeBranch().
101 /// BrCond - Conditions for end of block conditional branches.
102 /// Predicate - Predicate used in the BB.
105 bool IsBeingAnalyzed : 1;
108 bool IsBrAnalyzable : 1;
109 bool HasFallThrough : 1;
110 bool IsUnpredicable : 1;
111 bool CannotBeCopied : 1;
112 bool ClobbersPred : 1;
113 unsigned NonPredSize;
116 MachineBasicBlock *BB;
117 MachineBasicBlock *TrueBB;
118 MachineBasicBlock *FalseBB;
119 SmallVector<MachineOperand, 4> BrCond;
120 SmallVector<MachineOperand, 4> Predicate;
121 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
122 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
123 HasFallThrough(false), IsUnpredicable(false),
124 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
125 ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
128 /// IfcvtToken - Record information about pending if-conversions to attempt:
129 /// BBI - Corresponding BBInfo.
130 /// Kind - Type of block. See IfcvtKind.
131 /// NeedSubsumption - True if the to-be-predicated BB has already been
133 /// NumDups - Number of instructions that would be duplicated due
134 /// to this if-conversion. (For diamonds, the number of
135 /// identical instructions at the beginnings of both
137 /// NumDups2 - For diamonds, the number of identical instructions
138 /// at the ends of both paths.
142 bool NeedSubsumption;
145 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
146 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
149 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
150 /// basic block number.
151 std::vector<BBInfo> BBAnalysis;
153 const TargetLowering *TLI;
154 const TargetInstrInfo *TII;
155 const TargetRegisterInfo *TRI;
156 const InstrItineraryData *InstrItins;
157 const MachineBranchProbabilityInfo *MBPI;
163 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164 initializeIfConverterPass(*PassRegistry::getPassRegistry());
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<MachineBranchProbabilityInfo>();
169 MachineFunctionPass::getAnalysisUsage(AU);
172 virtual bool runOnMachineFunction(MachineFunction &MF);
173 virtual const char *getPassName() const { return "If Converter"; }
176 bool ReverseBranchCondition(BBInfo &BBI);
177 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178 const BranchProbability &Prediction) const;
179 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
180 bool FalseBranch, unsigned &Dups,
181 const BranchProbability &Prediction) const;
182 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183 unsigned &Dups1, unsigned &Dups2) const;
184 void ScanInstructions(BBInfo &BBI);
185 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186 std::vector<IfcvtToken*> &Tokens);
187 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
188 bool isTriangle = false, bool RevBranch = false);
189 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
190 void InvalidatePreds(MachineBasicBlock *BB);
191 void RemoveExtraEdges(BBInfo &BBI);
192 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
194 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195 unsigned NumDups1, unsigned NumDups2);
196 void PredicateBlock(BBInfo &BBI,
197 MachineBasicBlock::iterator E,
198 SmallVectorImpl<MachineOperand> &Cond,
199 SmallSet<unsigned, 4> &Redefs,
200 SmallSet<unsigned, 4> *LaterRedefs = 0);
201 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
202 SmallVectorImpl<MachineOperand> &Cond,
203 SmallSet<unsigned, 4> &Redefs,
204 bool IgnoreBr = false);
205 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
207 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
208 unsigned Cycle, unsigned Extra,
209 const BranchProbability &Prediction) const {
210 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
214 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
215 unsigned TCycle, unsigned TExtra,
216 MachineBasicBlock &FBB,
217 unsigned FCycle, unsigned FExtra,
218 const BranchProbability &Prediction) const {
219 return TCycle > 0 && FCycle > 0 &&
220 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
224 // blockAlwaysFallThrough - Block ends without a terminator.
225 bool blockAlwaysFallThrough(BBInfo &BBI) const {
226 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
229 // IfcvtTokenCmp - Used to sort if-conversion candidates.
230 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
231 int Incr1 = (C1->Kind == ICDiamond)
232 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
233 int Incr2 = (C2->Kind == ICDiamond)
234 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
237 else if (Incr1 == Incr2) {
238 // Favors subsumption.
239 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
241 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
242 // Favors diamond over triangle, etc.
243 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
245 else if (C1->Kind == C2->Kind)
246 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
253 char IfConverter::ID = 0;
256 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
257 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
258 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
260 FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
262 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
263 TLI = MF.getTarget().getTargetLowering();
264 TII = MF.getTarget().getInstrInfo();
265 TRI = MF.getTarget().getRegisterInfo();
266 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
267 InstrItins = MF.getTarget().getInstrItineraryData();
268 if (!TII) return false;
270 // Tail merge tend to expose more if-conversion opportunities.
271 BranchFolder BF(true, false);
272 bool BFChange = BF.OptimizeFunction(MF, TII,
273 MF.getTarget().getRegisterInfo(),
274 getAnalysisIfAvailable<MachineModuleInfo>());
276 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
277 << MF.getFunction()->getName() << "\'");
279 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
280 DEBUG(dbgs() << " skipped\n");
283 DEBUG(dbgs() << "\n");
286 BBAnalysis.resize(MF.getNumBlockIDs());
288 std::vector<IfcvtToken*> Tokens;
290 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
291 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
292 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
293 // Do an initial analysis for each basic block and find all the potential
294 // candidates to perform if-conversion.
296 AnalyzeBlocks(MF, Tokens);
297 while (!Tokens.empty()) {
298 IfcvtToken *Token = Tokens.back();
300 BBInfo &BBI = Token->BBI;
301 IfcvtKind Kind = Token->Kind;
302 unsigned NumDups = Token->NumDups;
303 unsigned NumDups2 = Token->NumDups2;
307 // If the block has been evicted out of the queue or it has already been
308 // marked dead (due to it being predicated), then skip it.
310 BBI.IsEnqueued = false;
314 BBI.IsEnqueued = false;
318 default: assert(false && "Unexpected!");
321 case ICSimpleFalse: {
322 bool isFalse = Kind == ICSimpleFalse;
323 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
324 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
326 << "): BB#" << BBI.BB->getNumber() << " ("
327 << ((Kind == ICSimpleFalse)
328 ? BBI.FalseBB->getNumber()
329 : BBI.TrueBB->getNumber()) << ") ");
330 RetVal = IfConvertSimple(BBI, Kind);
331 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
333 if (isFalse) ++NumSimpleFalse;
340 case ICTriangleFalse:
341 case ICTriangleFRev: {
342 bool isFalse = Kind == ICTriangleFalse;
343 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
344 if (DisableTriangle && !isFalse && !isRev) break;
345 if (DisableTriangleR && !isFalse && isRev) break;
346 if (DisableTriangleF && isFalse && !isRev) break;
347 if (DisableTriangleFR && isFalse && isRev) break;
348 DEBUG(dbgs() << "Ifcvt (Triangle");
350 DEBUG(dbgs() << " false");
352 DEBUG(dbgs() << " rev");
353 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
354 << BBI.TrueBB->getNumber() << ",F:"
355 << BBI.FalseBB->getNumber() << ") ");
356 RetVal = IfConvertTriangle(BBI, Kind);
357 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
360 if (isRev) ++NumTriangleFRev;
361 else ++NumTriangleFalse;
363 if (isRev) ++NumTriangleRev;
370 if (DisableDiamond) break;
371 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
372 << BBI.TrueBB->getNumber() << ",F:"
373 << BBI.FalseBB->getNumber() << ") ");
374 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
375 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
376 if (RetVal) ++NumDiamonds;
383 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
384 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
385 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
391 MadeChange |= Change;
394 // Delete tokens in case of early exit.
395 while (!Tokens.empty()) {
396 IfcvtToken *Token = Tokens.back();
404 if (MadeChange && IfCvtBranchFold) {
405 BranchFolder BF(false, false);
406 BF.OptimizeFunction(MF, TII,
407 MF.getTarget().getRegisterInfo(),
408 getAnalysisIfAvailable<MachineModuleInfo>());
411 MadeChange |= BFChange;
415 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
416 /// its 'true' successor.
417 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
418 MachineBasicBlock *TrueBB) {
419 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
420 E = BB->succ_end(); SI != E; ++SI) {
421 MachineBasicBlock *SuccBB = *SI;
422 if (SuccBB != TrueBB)
428 /// ReverseBranchCondition - Reverse the condition of the end of the block
429 /// branch. Swap block's 'true' and 'false' successors.
430 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
431 DebugLoc dl; // FIXME: this is nowhere
432 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
433 TII->RemoveBranch(*BBI.BB);
434 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
435 std::swap(BBI.TrueBB, BBI.FalseBB);
441 /// getNextBlock - Returns the next block in the function blocks ordering. If
442 /// it is the end, returns NULL.
443 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
444 MachineFunction::iterator I = BB;
445 MachineFunction::iterator E = BB->getParent()->end();
451 /// ValidSimple - Returns true if the 'true' block (along with its
452 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
453 /// number of instructions that the ifcvt would need to duplicate if performed
455 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
456 const BranchProbability &Prediction) const {
458 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
461 if (TrueBBI.IsBrAnalyzable)
464 if (TrueBBI.BB->pred_size() > 1) {
465 if (TrueBBI.CannotBeCopied ||
466 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
469 Dups = TrueBBI.NonPredSize;
475 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
476 /// with their common predecessor) forms a valid triangle shape for ifcvt.
477 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
478 /// branches to the 'false' block rather than the other way around. It also
479 /// returns the number of instructions that the ifcvt would need to duplicate
480 /// if performed in 'Dups'.
481 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
482 bool FalseBranch, unsigned &Dups,
483 const BranchProbability &Prediction) const {
485 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
488 if (TrueBBI.BB->pred_size() > 1) {
489 if (TrueBBI.CannotBeCopied)
492 unsigned Size = TrueBBI.NonPredSize;
493 if (TrueBBI.IsBrAnalyzable) {
494 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
495 // Ends with an unconditional branch. It will be removed.
498 MachineBasicBlock *FExit = FalseBranch
499 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
501 // Require a conditional branch
505 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
510 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
511 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
512 MachineFunction::iterator I = TrueBBI.BB;
513 if (++I == TrueBBI.BB->getParent()->end())
517 return TExit && TExit == FalseBBI.BB;
520 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
521 /// with their common predecessor) forms a valid diamond shape for ifcvt.
522 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
523 unsigned &Dups1, unsigned &Dups2) const {
525 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
526 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
529 MachineBasicBlock *TT = TrueBBI.TrueBB;
530 MachineBasicBlock *FT = FalseBBI.TrueBB;
532 if (!TT && blockAlwaysFallThrough(TrueBBI))
533 TT = getNextBlock(TrueBBI.BB);
534 if (!FT && blockAlwaysFallThrough(FalseBBI))
535 FT = getNextBlock(FalseBBI.BB);
538 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
540 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
543 // FIXME: Allow true block to have an early exit?
544 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
545 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
548 // Count duplicate instructions at the beginning of the true and false blocks.
549 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
550 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
551 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
552 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
553 while (TIB != TIE && FIB != FIE) {
554 // Skip dbg_value instructions. These do not count.
555 if (TIB->isDebugValue()) {
556 while (TIB != TIE && TIB->isDebugValue())
561 if (FIB->isDebugValue()) {
562 while (FIB != FIE && FIB->isDebugValue())
567 if (!TIB->isIdenticalTo(FIB))
574 // Now, in preparation for counting duplicate instructions at the ends of the
575 // blocks, move the end iterators up past any branch instructions.
578 if (!TIE->isBranch())
583 if (!FIE->isBranch())
587 // If Dups1 includes all of a block, then don't count duplicate
588 // instructions at the end of the blocks.
589 if (TIB == TIE || FIB == FIE)
592 // Count duplicate instructions at the ends of the blocks.
593 while (TIE != TIB && FIE != FIB) {
594 // Skip dbg_value instructions. These do not count.
595 if (TIE->isDebugValue()) {
596 while (TIE != TIB && TIE->isDebugValue())
601 if (FIE->isDebugValue()) {
602 while (FIE != FIB && FIE->isDebugValue())
607 if (!TIE->isIdenticalTo(FIE))
617 /// ScanInstructions - Scan all the instructions in the block to determine if
618 /// the block is predicable. In most cases, that means all the instructions
619 /// in the block are isPredicable(). Also checks if the block contains any
620 /// instruction which can clobber a predicate (e.g. condition code register).
621 /// If so, the block is not predicable unless it's the last instruction.
622 void IfConverter::ScanInstructions(BBInfo &BBI) {
626 bool AlreadyPredicated = BBI.Predicate.size() > 0;
627 // First analyze the end of BB branches.
628 BBI.TrueBB = BBI.FalseBB = NULL;
631 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
632 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
634 if (BBI.BrCond.size()) {
635 // No false branch. This BB must end with a conditional branch and a
638 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
640 // Malformed bcc? True and false blocks are the same?
641 BBI.IsUnpredicable = true;
646 // Then scan all the instructions.
650 BBI.ClobbersPred = false;
651 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
653 if (I->isDebugValue())
656 if (I->isNotDuplicable())
657 BBI.CannotBeCopied = true;
659 bool isPredicated = TII->isPredicated(I);
660 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
665 unsigned ExtraPredCost = 0;
666 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
669 BBI.ExtraCost += NumCycles-1;
670 BBI.ExtraCost2 += ExtraPredCost;
671 } else if (!AlreadyPredicated) {
672 // FIXME: This instruction is already predicated before the
673 // if-conversion pass. It's probably something like a conditional move.
674 // Mark this block unpredicable for now.
675 BBI.IsUnpredicable = true;
680 if (BBI.ClobbersPred && !isPredicated) {
681 // Predicate modification instruction should end the block (except for
682 // already predicated instructions and end of block branches).
684 // A conditional branch is not predicable, but it may be eliminated.
688 // Predicate may have been modified, the subsequent (currently)
689 // unpredicated instructions cannot be correctly predicated.
690 BBI.IsUnpredicable = true;
694 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
695 // still potentially predicable.
696 std::vector<MachineOperand> PredDefs;
697 if (TII->DefinesPredicate(I, PredDefs))
698 BBI.ClobbersPred = true;
700 if (!TII->isPredicable(I)) {
701 BBI.IsUnpredicable = true;
707 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
708 /// predicated by the specified predicate.
709 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
710 SmallVectorImpl<MachineOperand> &Pred,
711 bool isTriangle, bool RevBranch) {
712 // If the block is dead or unpredicable, then it cannot be predicated.
713 if (BBI.IsDone || BBI.IsUnpredicable)
716 // If it is already predicated, check if its predicate subsumes the new
718 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
721 if (BBI.BrCond.size()) {
725 // Test predicate subsumption.
726 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
727 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
729 if (TII->ReverseBranchCondition(Cond))
732 if (TII->ReverseBranchCondition(RevPred) ||
733 !TII->SubsumesPredicate(Cond, RevPred))
740 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
741 /// the specified block. Record its successors and whether it looks like an
742 /// if-conversion candidate.
743 IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
744 std::vector<IfcvtToken*> &Tokens) {
745 BBInfo &BBI = BBAnalysis[BB->getNumber()];
747 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
751 BBI.IsBeingAnalyzed = true;
753 ScanInstructions(BBI);
755 // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
756 // considered for ifcvt anymore.
757 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
758 BBI.IsBeingAnalyzed = false;
759 BBI.IsAnalyzed = true;
763 // Do not ifcvt if either path is a back edge to the entry block.
764 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
765 BBI.IsBeingAnalyzed = false;
766 BBI.IsAnalyzed = true;
770 // Do not ifcvt if true and false fallthrough blocks are the same.
772 BBI.IsBeingAnalyzed = false;
773 BBI.IsAnalyzed = true;
777 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
778 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
780 if (TrueBBI.IsDone && FalseBBI.IsDone) {
781 BBI.IsBeingAnalyzed = false;
782 BBI.IsAnalyzed = true;
786 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
787 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
791 bool TNeedSub = TrueBBI.Predicate.size() > 0;
792 bool FNeedSub = FalseBBI.Predicate.size() > 0;
793 bool Enqueued = false;
795 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
797 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
798 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
799 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
800 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
801 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
803 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
804 FeasibilityAnalysis(FalseBBI, RevCond)) {
812 // Note TailBB can be empty.
813 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
818 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
819 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
820 TrueBBI.ExtraCost2, Prediction) &&
821 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
829 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
833 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
834 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
835 TrueBBI.ExtraCost2, Prediction) &&
836 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
837 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
841 if (ValidSimple(TrueBBI, Dups, Prediction) &&
842 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
843 TrueBBI.ExtraCost2, Prediction) &&
844 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
845 // Simple (split, no rejoin):
852 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
857 // Try the other path...
858 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
859 Prediction.getCompl()) &&
860 MeetIfcvtSizeLimit(*FalseBBI.BB,
861 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
862 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
863 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
864 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
868 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
869 Prediction.getCompl()) &&
870 MeetIfcvtSizeLimit(*FalseBBI.BB,
871 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
872 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
873 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
874 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
878 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
879 MeetIfcvtSizeLimit(*FalseBBI.BB,
880 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
881 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
882 FeasibilityAnalysis(FalseBBI, RevCond)) {
883 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
888 BBI.IsEnqueued = Enqueued;
889 BBI.IsBeingAnalyzed = false;
890 BBI.IsAnalyzed = true;
894 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
896 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
897 std::vector<IfcvtToken*> &Tokens) {
898 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
899 MachineBasicBlock *BB = I;
900 AnalyzeBlock(BB, Tokens);
903 // Sort to favor more complex ifcvt scheme.
904 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
907 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
908 /// that all the intervening blocks are empty (given BB can fall through to its
910 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
911 MachineFunction::iterator PI = BB;
912 MachineFunction::iterator I = llvm::next(PI);
913 MachineFunction::iterator TI = ToBB;
914 MachineFunction::iterator E = BB->getParent()->end();
916 // Check isSuccessor to avoid case where the next block is empty, but
917 // it's not a successor.
918 if (I == E || !I->empty() || !PI->isSuccessor(I))
925 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
926 /// to determine if it can be if-converted. If predecessor is already enqueued,
928 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
929 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
930 E = BB->pred_end(); PI != E; ++PI) {
931 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
932 if (PBBI.IsDone || PBBI.BB == BB)
934 PBBI.IsAnalyzed = false;
935 PBBI.IsEnqueued = false;
939 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
941 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
942 const TargetInstrInfo *TII) {
943 DebugLoc dl; // FIXME: this is nowhere
944 SmallVector<MachineOperand, 0> NoCond;
945 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
948 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
950 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
951 MachineBasicBlock *TBB = NULL, *FBB = NULL;
952 SmallVector<MachineOperand, 4> Cond;
953 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
954 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
957 /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
958 /// modeled as read + write (sort like two-address instructions). These
959 /// routines track register liveness and add implicit uses to if-converted
960 /// instructions to conform to the model.
961 static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
962 const TargetRegisterInfo *TRI) {
963 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
964 E = BB->livein_end(); I != E; ++I) {
967 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
969 Redefs.insert(*Subreg);
973 static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
974 const TargetRegisterInfo *TRI,
975 bool AddImpUse = false) {
976 SmallVector<unsigned, 4> Defs;
977 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
978 const MachineOperand &MO = MI->getOperand(i);
981 unsigned Reg = MO.getReg();
986 else if (MO.isKill()) {
988 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
992 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
993 unsigned Reg = Defs[i];
994 if (Redefs.count(Reg)) {
996 // Treat predicated update as read + write.
997 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
998 true/*IsImp*/,false/*IsKill*/));
1001 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1007 static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1008 MachineBasicBlock::iterator E,
1009 SmallSet<unsigned,4> &Redefs,
1010 const TargetRegisterInfo *TRI) {
1012 UpdatePredRedefs(I, Redefs, TRI);
1017 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1019 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1020 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1021 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1022 BBInfo *CvtBBI = &TrueBBI;
1023 BBInfo *NextBBI = &FalseBBI;
1025 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1026 if (Kind == ICSimpleFalse)
1027 std::swap(CvtBBI, NextBBI);
1029 if (CvtBBI->IsDone ||
1030 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1031 // Something has changed. It's no longer safe to predicate this block.
1032 BBI.IsAnalyzed = false;
1033 CvtBBI->IsAnalyzed = false;
1037 if (Kind == ICSimpleFalse)
1038 if (TII->ReverseBranchCondition(Cond))
1039 assert(false && "Unable to reverse branch condition!");
1041 // Initialize liveins to the first BB. These are potentiall redefined by
1042 // predicated instructions.
1043 SmallSet<unsigned, 4> Redefs;
1044 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1045 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1047 if (CvtBBI->BB->pred_size() > 1) {
1048 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1049 // Copy instructions in the true block, predicate them, and add them to
1051 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
1053 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1055 // Merge converted block into entry block.
1056 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1057 MergeBlocks(BBI, *CvtBBI);
1060 bool IterIfcvt = true;
1061 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1062 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1063 BBI.HasFallThrough = false;
1064 // Now ifcvt'd block will look like this:
1071 // We cannot further ifcvt this block because the unconditional branch
1072 // will have to be predicated on the new condition, that will not be
1073 // available if cmp executes.
1077 RemoveExtraEdges(BBI);
1079 // Update block info. BB can be iteratively if-converted.
1082 InvalidatePreds(BBI.BB);
1083 CvtBBI->IsDone = true;
1085 // FIXME: Must maintain LiveIns.
1089 /// IfConvertTriangle - If convert a triangle sub-CFG.
1091 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1092 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1093 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1094 BBInfo *CvtBBI = &TrueBBI;
1095 BBInfo *NextBBI = &FalseBBI;
1096 DebugLoc dl; // FIXME: this is nowhere
1098 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1099 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1100 std::swap(CvtBBI, NextBBI);
1102 if (CvtBBI->IsDone ||
1103 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1104 // Something has changed. It's no longer safe to predicate this block.
1105 BBI.IsAnalyzed = false;
1106 CvtBBI->IsAnalyzed = false;
1110 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1111 if (TII->ReverseBranchCondition(Cond))
1112 assert(false && "Unable to reverse branch condition!");
1114 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1115 if (ReverseBranchCondition(*CvtBBI)) {
1116 // BB has been changed, modify its predecessors (except for this
1117 // one) so they don't get ifcvt'ed based on bad intel.
1118 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1119 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1120 MachineBasicBlock *PBB = *PI;
1123 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1124 if (PBBI.IsEnqueued) {
1125 PBBI.IsAnalyzed = false;
1126 PBBI.IsEnqueued = false;
1132 // Initialize liveins to the first BB. These are potentially redefined by
1133 // predicated instructions.
1134 SmallSet<unsigned, 4> Redefs;
1135 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1136 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1138 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
1139 if (CvtBBI->BB->pred_size() > 1) {
1140 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1141 // Copy instructions in the true block, predicate them, and add them to
1143 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
1145 // Predicate the 'true' block after removing its branch.
1146 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1147 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
1149 // Now merge the entry of the triangle with the true block.
1150 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1151 MergeBlocks(BBI, *CvtBBI, false);
1154 // If 'true' block has a 'false' successor, add an exit branch to it.
1156 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1157 CvtBBI->BrCond.end());
1158 if (TII->ReverseBranchCondition(RevCond))
1159 assert(false && "Unable to reverse branch condition!");
1160 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
1161 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1164 // Merge in the 'false' block if the 'false' block has no other
1165 // predecessors. Otherwise, add an unconditional branch to 'false'.
1166 bool FalseBBDead = false;
1167 bool IterIfcvt = true;
1168 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1169 if (!isFallThrough) {
1170 // Only merge them if the true block does not fallthrough to the false
1171 // block. By not merging them, we make it possible to iteratively
1172 // ifcvt the blocks.
1173 if (!HasEarlyExit &&
1174 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
1175 MergeBlocks(BBI, *NextBBI);
1178 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1179 BBI.HasFallThrough = false;
1181 // Mixed predicated and unpredicated code. This cannot be iteratively
1186 RemoveExtraEdges(BBI);
1188 // Update block info. BB can be iteratively if-converted.
1191 InvalidatePreds(BBI.BB);
1192 CvtBBI->IsDone = true;
1194 NextBBI->IsDone = true;
1196 // FIXME: Must maintain LiveIns.
1200 /// IfConvertDiamond - If convert a diamond sub-CFG.
1202 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1203 unsigned NumDups1, unsigned NumDups2) {
1204 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1205 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1206 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1207 // True block must fall through or end with an unanalyzable terminator.
1209 if (blockAlwaysFallThrough(TrueBBI))
1210 TailBB = FalseBBI.TrueBB;
1211 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1214 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1215 TrueBBI.BB->pred_size() > 1 ||
1216 FalseBBI.BB->pred_size() > 1) {
1217 // Something has changed. It's no longer safe to predicate these blocks.
1218 BBI.IsAnalyzed = false;
1219 TrueBBI.IsAnalyzed = false;
1220 FalseBBI.IsAnalyzed = false;
1224 // Put the predicated instructions from the 'true' block before the
1225 // instructions from the 'false' block, unless the true block would clobber
1226 // the predicate, in which case, do the opposite.
1227 BBInfo *BBI1 = &TrueBBI;
1228 BBInfo *BBI2 = &FalseBBI;
1229 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1230 if (TII->ReverseBranchCondition(RevCond))
1231 assert(false && "Unable to reverse branch condition!");
1232 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1233 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1235 // Figure out the more profitable ordering.
1236 bool DoSwap = false;
1237 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1239 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1240 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1244 std::swap(BBI1, BBI2);
1245 std::swap(Cond1, Cond2);
1248 // Remove the conditional branch from entry to the blocks.
1249 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1251 // Initialize liveins to the first BB. These are potentially redefined by
1252 // predicated instructions.
1253 SmallSet<unsigned, 4> Redefs;
1254 InitPredRedefs(BBI1->BB, Redefs, TRI);
1256 // Remove the duplicated instructions at the beginnings of both paths.
1257 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1258 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
1259 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1260 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1261 // Skip dbg_value instructions
1262 while (DI1 != DIE1 && DI1->isDebugValue())
1264 while (DI2 != DIE2 && DI2->isDebugValue())
1266 BBI1->NonPredSize -= NumDups1;
1267 BBI2->NonPredSize -= NumDups1;
1269 // Skip past the dups on each side separately since there may be
1270 // differing dbg_value entries.
1271 for (unsigned i = 0; i < NumDups1; ++DI1) {
1272 if (!DI1->isDebugValue())
1275 while (NumDups1 != 0) {
1277 if (!DI2->isDebugValue())
1281 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
1282 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1283 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1285 // Remove branch from 'true' block and remove duplicated instructions.
1286 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1287 DI1 = BBI1->BB->end();
1288 for (unsigned i = 0; i != NumDups2; ) {
1289 // NumDups2 only counted non-dbg_value instructions, so this won't
1290 // run off the head of the list.
1291 assert (DI1 != BBI1->BB->begin());
1293 // skip dbg_value instructions
1294 if (!DI1->isDebugValue())
1297 BBI1->BB->erase(DI1, BBI1->BB->end());
1299 // Remove 'false' block branch and find the last instruction to predicate.
1300 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1301 DI2 = BBI2->BB->end();
1302 while (NumDups2 != 0) {
1303 // NumDups2 only counted non-dbg_value instructions, so this won't
1304 // run off the head of the list.
1305 assert (DI2 != BBI2->BB->begin());
1307 // skip dbg_value instructions
1308 if (!DI2->isDebugValue())
1312 // Remember which registers would later be defined by the false block.
1313 // This allows us not to predicate instructions in the true block that would
1314 // later be re-defined. That is, rather than
1320 SmallSet<unsigned, 4> RedefsByFalse;
1321 SmallSet<unsigned, 4> ExtUses;
1322 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1323 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1324 if (FI->isDebugValue())
1326 SmallVector<unsigned, 4> Defs;
1327 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1328 const MachineOperand &MO = FI->getOperand(i);
1331 unsigned Reg = MO.getReg();
1335 Defs.push_back(Reg);
1336 } else if (!RedefsByFalse.count(Reg)) {
1337 // These are defined before ctrl flow reach the 'false' instructions.
1338 // They cannot be modified by the 'true' instructions.
1339 ExtUses.insert(Reg);
1340 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1341 ExtUses.insert(*SR);
1345 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1346 unsigned Reg = Defs[i];
1347 if (!ExtUses.count(Reg)) {
1348 RedefsByFalse.insert(Reg);
1349 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1350 RedefsByFalse.insert(*SR);
1356 // Predicate the 'true' block.
1357 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
1359 // Predicate the 'false' block.
1360 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
1362 // Merge the true block into the entry of the diamond.
1363 MergeBlocks(BBI, *BBI1, TailBB == 0);
1364 MergeBlocks(BBI, *BBI2, TailBB == 0);
1366 // If the if-converted block falls through or unconditionally branches into
1367 // the tail block, and the tail block does not have other predecessors, then
1368 // fold the tail block in as well. Otherwise, unless it falls through to the
1369 // tail, add a unconditional branch to it.
1371 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1372 bool CanMergeTail = !TailBBI.HasFallThrough;
1373 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1374 // check if there are any other predecessors besides those.
1375 unsigned NumPreds = TailBB->pred_size();
1377 CanMergeTail = false;
1378 else if (NumPreds == 1 && CanMergeTail) {
1379 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1380 if (*PI != BBI1->BB && *PI != BBI2->BB)
1381 CanMergeTail = false;
1384 MergeBlocks(BBI, TailBBI);
1385 TailBBI.IsDone = true;
1387 BBI.BB->addSuccessor(TailBB);
1388 InsertUncondBranch(BBI.BB, TailBB, TII);
1389 BBI.HasFallThrough = false;
1393 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1394 // which can happen here if TailBB is unanalyzable and is merged, so
1395 // explicitly remove BBI1 and BBI2 as successors.
1396 BBI.BB->removeSuccessor(BBI1->BB);
1397 BBI.BB->removeSuccessor(BBI2->BB);
1398 RemoveExtraEdges(BBI);
1400 // Update block info.
1401 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1402 InvalidatePreds(BBI.BB);
1404 // FIXME: Must maintain LiveIns.
1408 static bool MaySpeculate(const MachineInstr *MI,
1409 SmallSet<unsigned, 4> &LaterRedefs,
1410 const TargetInstrInfo *TII) {
1411 bool SawStore = true;
1412 if (!MI->isSafeToMove(TII, 0, SawStore))
1415 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1416 const MachineOperand &MO = MI->getOperand(i);
1419 unsigned Reg = MO.getReg();
1422 if (MO.isDef() && !LaterRedefs.count(Reg))
1429 /// PredicateBlock - Predicate instructions from the start of the block to the
1430 /// specified end with the specified condition.
1431 void IfConverter::PredicateBlock(BBInfo &BBI,
1432 MachineBasicBlock::iterator E,
1433 SmallVectorImpl<MachineOperand> &Cond,
1434 SmallSet<unsigned, 4> &Redefs,
1435 SmallSet<unsigned, 4> *LaterRedefs) {
1436 bool AnyUnpred = false;
1437 bool MaySpec = LaterRedefs != 0;
1438 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1439 if (I->isDebugValue() || TII->isPredicated(I))
1441 // It may be possible not to predicate an instruction if it's the 'true'
1442 // side of a diamond and the 'false' side may re-define the instruction's
1444 if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
1448 // If any instruction is predicated, then every instruction after it must
1451 if (!TII->PredicateInstruction(I, Cond)) {
1453 dbgs() << "Unable to predicate " << *I << "!\n";
1455 llvm_unreachable(0);
1458 // If the predicated instruction now redefines a register as the result of
1459 // if-conversion, add an implicit kill.
1460 UpdatePredRedefs(I, Redefs, TRI, true);
1463 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1465 BBI.IsAnalyzed = false;
1466 BBI.NonPredSize = 0;
1473 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1474 /// the destination block. Skip end of block branches if IgnoreBr is true.
1475 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1476 SmallVectorImpl<MachineOperand> &Cond,
1477 SmallSet<unsigned, 4> &Redefs,
1479 MachineFunction &MF = *ToBBI.BB->getParent();
1481 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1482 E = FromBBI.BB->end(); I != E; ++I) {
1483 // Do not copy the end of the block branches.
1484 if (IgnoreBr && I->isBranch())
1487 MachineInstr *MI = MF.CloneMachineInstr(I);
1488 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1489 ToBBI.NonPredSize++;
1490 unsigned ExtraPredCost = 0;
1491 unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
1493 ToBBI.ExtraCost += NumCycles-1;
1494 ToBBI.ExtraCost2 += ExtraPredCost;
1496 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1497 if (!TII->PredicateInstruction(MI, Cond)) {
1499 dbgs() << "Unable to predicate " << *I << "!\n";
1501 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(MI, Redefs, TRI, true);
1511 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1512 FromBBI.BB->succ_end());
1513 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1514 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1516 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1517 MachineBasicBlock *Succ = Succs[i];
1518 // Fallthrough edge can't be transferred.
1519 if (Succ == FallThrough)
1521 ToBBI.BB->addSuccessor(Succ);
1525 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1526 std::back_inserter(ToBBI.Predicate));
1527 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1529 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1530 ToBBI.IsAnalyzed = false;
1535 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1536 /// This will leave FromBB as an empty block, so remove all of its
1537 /// successor edges except for the fall-through edge. If AddEdges is true,
1538 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1540 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1541 ToBBI.BB->splice(ToBBI.BB->end(),
1542 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1544 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1545 FromBBI.BB->succ_end());
1546 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1547 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
1549 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1550 MachineBasicBlock *Succ = Succs[i];
1551 // Fallthrough edge can't be transferred.
1552 if (Succ == FallThrough)
1554 FromBBI.BB->removeSuccessor(Succ);
1556 ToBBI.BB->addSuccessor(Succ);
1559 // Now FromBBI always falls through to the next block!
1560 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1561 FromBBI.BB->addSuccessor(NBB);
1563 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1564 std::back_inserter(ToBBI.Predicate));
1565 FromBBI.Predicate.clear();
1567 ToBBI.NonPredSize += FromBBI.NonPredSize;
1568 ToBBI.ExtraCost += FromBBI.ExtraCost;
1569 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1570 FromBBI.NonPredSize = 0;
1571 FromBBI.ExtraCost = 0;
1572 FromBBI.ExtraCost2 = 0;
1574 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1575 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1576 ToBBI.IsAnalyzed = false;
1577 FromBBI.IsAnalyzed = false;