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 #include "llvm/CodeGen/Passes.h"
15 #include "BranchFolding.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/LivePhysRegs.h"
20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
21 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSchedule.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 #define DEBUG_TYPE "ifcvt"
40 // Hidden options for help debugging.
41 static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
42 static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
43 static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
44 static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
45 cl::init(false), cl::Hidden);
46 static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
47 cl::init(false), cl::Hidden);
48 static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
49 cl::init(false), cl::Hidden);
50 static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
51 cl::init(false), cl::Hidden);
52 static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
53 cl::init(false), cl::Hidden);
54 static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
55 cl::init(false), cl::Hidden);
56 static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
57 cl::init(false), cl::Hidden);
58 static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
59 cl::init(true), cl::Hidden);
61 STATISTIC(NumSimple, "Number of simple if-conversions performed");
62 STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
63 STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
64 STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
65 STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
66 STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
67 STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
68 STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
69 STATISTIC(NumDupBBs, "Number of duplicated blocks");
70 STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
73 class IfConverter : public MachineFunctionPass {
75 ICNotClassfied, // BB data valid, but not classified.
76 ICSimpleFalse, // Same as ICSimple, but on the false path.
77 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
78 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
79 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
80 ICTriangleFalse, // Same as ICTriangle, but on the false path.
81 ICTriangle, // BB is entry of a triangle sub-CFG.
82 ICDiamond // BB is entry of a diamond sub-CFG.
85 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
86 /// if-conversion feasibility analysis. This includes results from
87 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
88 /// classification, and common tail block of its successors (if it's a
89 /// diamond shape), its size, whether it's predicable, and whether any
90 /// instruction can clobber the 'would-be' predicate.
92 /// IsDone - True if BB is not to be considered for ifcvt.
93 /// IsBeingAnalyzed - True if BB is currently being analyzed.
94 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
95 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
96 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
97 /// HasFallThrough - True if BB may fallthrough to the following BB.
98 /// IsUnpredicable - True if BB is known to be unpredicable.
99 /// ClobbersPred - True if BB could modify predicates (e.g. has
101 /// NonPredSize - Number of non-predicated instructions.
102 /// ExtraCost - Extra cost for multi-cycle instructions.
103 /// ExtraCost2 - Some instructions are slower when predicated
104 /// BB - Corresponding MachineBasicBlock.
105 /// TrueBB / FalseBB- See AnalyzeBranch().
106 /// BrCond - Conditions for end of block conditional branches.
107 /// Predicate - Predicate used in the BB.
110 bool IsBeingAnalyzed : 1;
113 bool IsBrAnalyzable : 1;
114 bool HasFallThrough : 1;
115 bool IsUnpredicable : 1;
116 bool CannotBeCopied : 1;
117 bool ClobbersPred : 1;
118 unsigned NonPredSize;
121 MachineBasicBlock *BB;
122 MachineBasicBlock *TrueBB;
123 MachineBasicBlock *FalseBB;
124 SmallVector<MachineOperand, 4> BrCond;
125 SmallVector<MachineOperand, 4> Predicate;
126 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
127 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
128 HasFallThrough(false), IsUnpredicable(false),
129 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
130 ExtraCost(0), ExtraCost2(0), BB(nullptr), TrueBB(nullptr),
134 /// IfcvtToken - Record information about pending if-conversions to attempt:
135 /// BBI - Corresponding BBInfo.
136 /// Kind - Type of block. See IfcvtKind.
137 /// NeedSubsumption - True if the to-be-predicated BB has already been
139 /// NumDups - Number of instructions that would be duplicated due
140 /// to this if-conversion. (For diamonds, the number of
141 /// identical instructions at the beginnings of both
143 /// NumDups2 - For diamonds, the number of identical instructions
144 /// at the ends of both paths.
148 bool NeedSubsumption;
151 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
152 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
155 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
156 /// basic block number.
157 std::vector<BBInfo> BBAnalysis;
158 TargetSchedModel SchedModel;
160 const TargetLoweringBase *TLI;
161 const TargetInstrInfo *TII;
162 const TargetRegisterInfo *TRI;
163 const MachineBlockFrequencyInfo *MBFI;
164 const MachineBranchProbabilityInfo *MBPI;
165 MachineRegisterInfo *MRI;
168 LivePhysRegs DontKill;
173 std::function<bool(const Function &)> PredicateFtor;
177 IfConverter(std::function<bool(const Function &)> Ftor = nullptr)
178 : MachineFunctionPass(ID), FnNum(-1), PredicateFtor(Ftor) {
179 initializeIfConverterPass(*PassRegistry::getPassRegistry());
182 void getAnalysisUsage(AnalysisUsage &AU) const override {
183 AU.addRequired<MachineBlockFrequencyInfo>();
184 AU.addRequired<MachineBranchProbabilityInfo>();
185 MachineFunctionPass::getAnalysisUsage(AU);
188 bool runOnMachineFunction(MachineFunction &MF) override;
191 bool ReverseBranchCondition(BBInfo &BBI);
192 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
193 const BranchProbability &Prediction) const;
194 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
195 bool FalseBranch, unsigned &Dups,
196 const BranchProbability &Prediction) const;
197 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
198 unsigned &Dups1, unsigned &Dups2) const;
199 void ScanInstructions(BBInfo &BBI);
200 void AnalyzeBlock(MachineBasicBlock *MBB, std::vector<IfcvtToken*> &Tokens);
201 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
202 bool isTriangle = false, bool RevBranch = false);
203 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
204 void InvalidatePreds(MachineBasicBlock *BB);
205 void RemoveExtraEdges(BBInfo &BBI);
206 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
207 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
208 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
209 unsigned NumDups1, unsigned NumDups2);
210 void PredicateBlock(BBInfo &BBI,
211 MachineBasicBlock::iterator E,
212 SmallVectorImpl<MachineOperand> &Cond,
213 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
214 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
215 SmallVectorImpl<MachineOperand> &Cond,
216 bool IgnoreBr = false);
217 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
219 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
220 unsigned Cycle, unsigned Extra,
221 const BranchProbability &Prediction) const {
222 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
226 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
227 unsigned TCycle, unsigned TExtra,
228 MachineBasicBlock &FBB,
229 unsigned FCycle, unsigned FExtra,
230 const BranchProbability &Prediction) const {
231 return TCycle > 0 && FCycle > 0 &&
232 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
236 // blockAlwaysFallThrough - Block ends without a terminator.
237 bool blockAlwaysFallThrough(BBInfo &BBI) const {
238 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
241 // IfcvtTokenCmp - Used to sort if-conversion candidates.
242 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
243 int Incr1 = (C1->Kind == ICDiamond)
244 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
245 int Incr2 = (C2->Kind == ICDiamond)
246 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
249 else if (Incr1 == Incr2) {
250 // Favors subsumption.
251 if (!C1->NeedSubsumption && C2->NeedSubsumption)
253 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
254 // Favors diamond over triangle, etc.
255 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
257 else if (C1->Kind == C2->Kind)
258 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
265 char IfConverter::ID = 0;
268 char &llvm::IfConverterID = IfConverter::ID;
270 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
271 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
272 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
274 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
275 if (PredicateFtor && !PredicateFtor(*MF.getFunction()))
278 const TargetSubtargetInfo &ST = MF.getSubtarget();
279 TLI = ST.getTargetLowering();
280 TII = ST.getInstrInfo();
281 TRI = ST.getRegisterInfo();
282 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
283 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
284 MRI = &MF.getRegInfo();
285 SchedModel.init(ST.getSchedModel(), &ST, TII);
287 if (!TII) return false;
289 PreRegAlloc = MRI->isSSA();
291 bool BFChange = false;
293 // Tail merge tend to expose more if-conversion opportunities.
294 BranchFolder BF(true, false, *MBFI, *MBPI);
295 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
296 getAnalysisIfAvailable<MachineModuleInfo>());
299 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
300 << MF.getName() << "\'");
302 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
303 DEBUG(dbgs() << " skipped\n");
306 DEBUG(dbgs() << "\n");
309 BBAnalysis.resize(MF.getNumBlockIDs());
311 std::vector<IfcvtToken*> Tokens;
313 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
314 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
315 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
316 // Do an initial analysis for each basic block and find all the potential
317 // candidates to perform if-conversion.
319 AnalyzeBlocks(MF, Tokens);
320 while (!Tokens.empty()) {
321 IfcvtToken *Token = Tokens.back();
323 BBInfo &BBI = Token->BBI;
324 IfcvtKind Kind = Token->Kind;
325 unsigned NumDups = Token->NumDups;
326 unsigned NumDups2 = Token->NumDups2;
330 // If the block has been evicted out of the queue or it has already been
331 // marked dead (due to it being predicated), then skip it.
333 BBI.IsEnqueued = false;
337 BBI.IsEnqueued = false;
341 default: llvm_unreachable("Unexpected!");
343 case ICSimpleFalse: {
344 bool isFalse = Kind == ICSimpleFalse;
345 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
346 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
348 << "): BB#" << BBI.BB->getNumber() << " ("
349 << ((Kind == ICSimpleFalse)
350 ? BBI.FalseBB->getNumber()
351 : BBI.TrueBB->getNumber()) << ") ");
352 RetVal = IfConvertSimple(BBI, Kind);
353 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
355 if (isFalse) ++NumSimpleFalse;
362 case ICTriangleFalse:
363 case ICTriangleFRev: {
364 bool isFalse = Kind == ICTriangleFalse;
365 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
366 if (DisableTriangle && !isFalse && !isRev) break;
367 if (DisableTriangleR && !isFalse && isRev) break;
368 if (DisableTriangleF && isFalse && !isRev) break;
369 if (DisableTriangleFR && isFalse && isRev) break;
370 DEBUG(dbgs() << "Ifcvt (Triangle");
372 DEBUG(dbgs() << " false");
374 DEBUG(dbgs() << " rev");
375 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
376 << BBI.TrueBB->getNumber() << ",F:"
377 << BBI.FalseBB->getNumber() << ") ");
378 RetVal = IfConvertTriangle(BBI, Kind);
379 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
382 if (isRev) ++NumTriangleFRev;
383 else ++NumTriangleFalse;
385 if (isRev) ++NumTriangleRev;
392 if (DisableDiamond) break;
393 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
394 << BBI.TrueBB->getNumber() << ",F:"
395 << BBI.FalseBB->getNumber() << ") ");
396 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
397 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
398 if (RetVal) ++NumDiamonds;
405 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
406 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
407 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
413 MadeChange |= Change;
416 // Delete tokens in case of early exit.
417 while (!Tokens.empty()) {
418 IfcvtToken *Token = Tokens.back();
426 if (MadeChange && IfCvtBranchFold) {
427 BranchFolder BF(false, false, *MBFI, *MBPI);
428 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
429 getAnalysisIfAvailable<MachineModuleInfo>());
432 MadeChange |= BFChange;
436 /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
437 /// its 'true' successor.
438 static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
439 MachineBasicBlock *TrueBB) {
440 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
441 E = BB->succ_end(); SI != E; ++SI) {
442 MachineBasicBlock *SuccBB = *SI;
443 if (SuccBB != TrueBB)
449 /// ReverseBranchCondition - Reverse the condition of the end of the block
450 /// branch. Swap block's 'true' and 'false' successors.
451 bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
452 DebugLoc dl; // FIXME: this is nowhere
453 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
454 TII->RemoveBranch(*BBI.BB);
455 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
456 std::swap(BBI.TrueBB, BBI.FalseBB);
462 /// getNextBlock - Returns the next block in the function blocks ordering. If
463 /// it is the end, returns NULL.
464 static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
465 MachineFunction::iterator I = BB;
466 MachineFunction::iterator E = BB->getParent()->end();
472 /// ValidSimple - Returns true if the 'true' block (along with its
473 /// predecessor) forms a valid simple shape for ifcvt. It also returns the
474 /// number of instructions that the ifcvt would need to duplicate if performed
476 bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
477 const BranchProbability &Prediction) const {
479 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
482 if (TrueBBI.IsBrAnalyzable)
485 if (TrueBBI.BB->pred_size() > 1) {
486 if (TrueBBI.CannotBeCopied ||
487 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
490 Dups = TrueBBI.NonPredSize;
496 /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
497 /// with their common predecessor) forms a valid triangle shape for ifcvt.
498 /// If 'FalseBranch' is true, it checks if 'true' block's false branch
499 /// branches to the 'false' block rather than the other way around. It also
500 /// returns the number of instructions that the ifcvt would need to duplicate
501 /// if performed in 'Dups'.
502 bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
503 bool FalseBranch, unsigned &Dups,
504 const BranchProbability &Prediction) const {
506 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
509 if (TrueBBI.BB->pred_size() > 1) {
510 if (TrueBBI.CannotBeCopied)
513 unsigned Size = TrueBBI.NonPredSize;
514 if (TrueBBI.IsBrAnalyzable) {
515 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
516 // Ends with an unconditional branch. It will be removed.
519 MachineBasicBlock *FExit = FalseBranch
520 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
522 // Require a conditional branch
526 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
531 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
532 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
533 MachineFunction::iterator I = TrueBBI.BB;
534 if (++I == TrueBBI.BB->getParent()->end())
538 return TExit && TExit == FalseBBI.BB;
541 /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
542 /// with their common predecessor) forms a valid diamond shape for ifcvt.
543 bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
544 unsigned &Dups1, unsigned &Dups2) const {
546 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
547 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
550 MachineBasicBlock *TT = TrueBBI.TrueBB;
551 MachineBasicBlock *FT = FalseBBI.TrueBB;
553 if (!TT && blockAlwaysFallThrough(TrueBBI))
554 TT = getNextBlock(TrueBBI.BB);
555 if (!FT && blockAlwaysFallThrough(FalseBBI))
556 FT = getNextBlock(FalseBBI.BB);
559 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
561 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
564 // FIXME: Allow true block to have an early exit?
565 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
566 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
569 // Count duplicate instructions at the beginning of the true and false blocks.
570 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
571 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
572 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
573 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
574 while (TIB != TIE && FIB != FIE) {
575 // Skip dbg_value instructions. These do not count.
576 if (TIB->isDebugValue()) {
577 while (TIB != TIE && TIB->isDebugValue())
582 if (FIB->isDebugValue()) {
583 while (FIB != FIE && FIB->isDebugValue())
588 if (!TIB->isIdenticalTo(FIB))
595 // Now, in preparation for counting duplicate instructions at the ends of the
596 // blocks, move the end iterators up past any branch instructions.
599 if (!TIE->isBranch())
604 if (!FIE->isBranch())
608 // If Dups1 includes all of a block, then don't count duplicate
609 // instructions at the end of the blocks.
610 if (TIB == TIE || FIB == FIE)
613 // Count duplicate instructions at the ends of the blocks.
614 while (TIE != TIB && FIE != FIB) {
615 // Skip dbg_value instructions. These do not count.
616 if (TIE->isDebugValue()) {
617 while (TIE != TIB && TIE->isDebugValue())
622 if (FIE->isDebugValue()) {
623 while (FIE != FIB && FIE->isDebugValue())
628 if (!TIE->isIdenticalTo(FIE))
638 /// ScanInstructions - Scan all the instructions in the block to determine if
639 /// the block is predicable. In most cases, that means all the instructions
640 /// in the block are isPredicable(). Also checks if the block contains any
641 /// instruction which can clobber a predicate (e.g. condition code register).
642 /// If so, the block is not predicable unless it's the last instruction.
643 void IfConverter::ScanInstructions(BBInfo &BBI) {
647 bool AlreadyPredicated = !BBI.Predicate.empty();
648 // First analyze the end of BB branches.
649 BBI.TrueBB = BBI.FalseBB = nullptr;
652 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
653 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
655 if (BBI.BrCond.size()) {
656 // No false branch. This BB must end with a conditional branch and a
659 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
661 // Malformed bcc? True and false blocks are the same?
662 BBI.IsUnpredicable = true;
667 // Then scan all the instructions.
671 BBI.ClobbersPred = false;
672 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
674 if (I->isDebugValue())
677 if (I->isNotDuplicable())
678 BBI.CannotBeCopied = true;
680 bool isPredicated = TII->isPredicated(I);
681 bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
683 // A conditional branch is not predicable, but it may be eliminated.
689 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
690 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
692 BBI.ExtraCost += NumCycles-1;
693 BBI.ExtraCost2 += ExtraPredCost;
694 } else if (!AlreadyPredicated) {
695 // FIXME: This instruction is already predicated before the
696 // if-conversion pass. It's probably something like a conditional move.
697 // Mark this block unpredicable for now.
698 BBI.IsUnpredicable = true;
702 if (BBI.ClobbersPred && !isPredicated) {
703 // Predicate modification instruction should end the block (except for
704 // already predicated instructions and end of block branches).
705 // Predicate may have been modified, the subsequent (currently)
706 // unpredicated instructions cannot be correctly predicated.
707 BBI.IsUnpredicable = true;
711 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
712 // still potentially predicable.
713 std::vector<MachineOperand> PredDefs;
714 if (TII->DefinesPredicate(I, PredDefs))
715 BBI.ClobbersPred = true;
717 if (!TII->isPredicable(I)) {
718 BBI.IsUnpredicable = true;
724 /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
725 /// predicated by the specified predicate.
726 bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
727 SmallVectorImpl<MachineOperand> &Pred,
728 bool isTriangle, bool RevBranch) {
729 // If the block is dead or unpredicable, then it cannot be predicated.
730 if (BBI.IsDone || BBI.IsUnpredicable)
733 // If it is already predicated but we couldn't analyze its terminator, the
734 // latter might fallthrough, but we can't determine where to.
735 // Conservatively avoid if-converting again.
736 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
739 // If it is already predicated, check if the new predicate subsumes
741 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
744 if (BBI.BrCond.size()) {
748 // Test predicate subsumption.
749 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
750 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
752 if (TII->ReverseBranchCondition(Cond))
755 if (TII->ReverseBranchCondition(RevPred) ||
756 !TII->SubsumesPredicate(Cond, RevPred))
763 /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
764 /// the specified block. Record its successors and whether it looks like an
765 /// if-conversion candidate.
766 void IfConverter::AnalyzeBlock(MachineBasicBlock *MBB,
767 std::vector<IfcvtToken*> &Tokens) {
769 BBState(MachineBasicBlock *BB) : MBB(BB), SuccsAnalyzed(false) {}
770 MachineBasicBlock *MBB;
772 /// This flag is true if MBB's successors have been analyzed.
776 // Push MBB to the stack.
777 SmallVector<BBState, 16> BBStack(1, MBB);
779 while (!BBStack.empty()) {
780 BBState &State = BBStack.back();
781 MachineBasicBlock *BB = State.MBB;
782 BBInfo &BBI = BBAnalysis[BB->getNumber()];
784 if (!State.SuccsAnalyzed) {
785 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
791 BBI.IsBeingAnalyzed = true;
793 ScanInstructions(BBI);
795 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
796 // not considered for ifcvt anymore.
797 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
798 BBI.IsBeingAnalyzed = false;
799 BBI.IsAnalyzed = true;
804 // Do not ifcvt if either path is a back edge to the entry block.
805 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
806 BBI.IsBeingAnalyzed = false;
807 BBI.IsAnalyzed = true;
812 // Do not ifcvt if true and false fallthrough blocks are the same.
814 BBI.IsBeingAnalyzed = false;
815 BBI.IsAnalyzed = true;
820 // Push the False and True blocks to the stack.
821 State.SuccsAnalyzed = true;
822 BBStack.push_back(BBI.FalseBB);
823 BBStack.push_back(BBI.TrueBB);
827 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
828 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
830 if (TrueBBI.IsDone && FalseBBI.IsDone) {
831 BBI.IsBeingAnalyzed = false;
832 BBI.IsAnalyzed = true;
837 SmallVector<MachineOperand, 4>
838 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
839 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
843 bool TNeedSub = !TrueBBI.Predicate.empty();
844 bool FNeedSub = !FalseBBI.Predicate.empty();
845 bool Enqueued = false;
847 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
849 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
850 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
851 TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
852 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
853 FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
855 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
856 FeasibilityAnalysis(FalseBBI, RevCond)) {
864 // Note TailBB can be empty.
865 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
870 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
871 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
872 TrueBBI.ExtraCost2, Prediction) &&
873 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
881 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
885 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
886 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
887 TrueBBI.ExtraCost2, Prediction) &&
888 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
889 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
893 if (ValidSimple(TrueBBI, Dups, Prediction) &&
894 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
895 TrueBBI.ExtraCost2, Prediction) &&
896 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
897 // Simple (split, no rejoin):
904 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
909 // Try the other path...
910 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
911 Prediction.getCompl()) &&
912 MeetIfcvtSizeLimit(*FalseBBI.BB,
913 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
914 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
915 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
916 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
920 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
921 Prediction.getCompl()) &&
922 MeetIfcvtSizeLimit(*FalseBBI.BB,
923 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
924 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
925 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
926 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
930 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
931 MeetIfcvtSizeLimit(*FalseBBI.BB,
932 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
933 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
934 FeasibilityAnalysis(FalseBBI, RevCond)) {
935 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
940 BBI.IsEnqueued = Enqueued;
941 BBI.IsBeingAnalyzed = false;
942 BBI.IsAnalyzed = true;
947 /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
949 void IfConverter::AnalyzeBlocks(MachineFunction &MF,
950 std::vector<IfcvtToken*> &Tokens) {
951 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
952 MachineBasicBlock *BB = I;
953 AnalyzeBlock(BB, Tokens);
956 // Sort to favor more complex ifcvt scheme.
957 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
960 /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
961 /// that all the intervening blocks are empty (given BB can fall through to its
963 static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
964 MachineFunction::iterator PI = BB;
965 MachineFunction::iterator I = std::next(PI);
966 MachineFunction::iterator TI = ToBB;
967 MachineFunction::iterator E = BB->getParent()->end();
969 // Check isSuccessor to avoid case where the next block is empty, but
970 // it's not a successor.
971 if (I == E || !I->empty() || !PI->isSuccessor(I))
978 /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
979 /// to determine if it can be if-converted. If predecessor is already enqueued,
981 void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
982 for (const auto &Predecessor : BB->predecessors()) {
983 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
984 if (PBBI.IsDone || PBBI.BB == BB)
986 PBBI.IsAnalyzed = false;
987 PBBI.IsEnqueued = false;
991 /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
993 static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
994 const TargetInstrInfo *TII) {
995 DebugLoc dl; // FIXME: this is nowhere
996 SmallVector<MachineOperand, 0> NoCond;
997 TII->InsertBranch(*BB, ToBB, nullptr, NoCond, dl);
1000 /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
1002 void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
1003 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1004 SmallVector<MachineOperand, 4> Cond;
1005 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
1006 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
1009 /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
1010 /// values defined in MI which are not live/used by MI.
1011 static void UpdatePredRedefs(MachineInstr *MI, LivePhysRegs &Redefs) {
1012 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
1013 Redefs.stepForward(*MI, Clobbers);
1015 // Now add the implicit uses for each of the clobbered values.
1016 for (auto Reg : Clobbers) {
1017 // FIXME: Const cast here is nasty, but better than making StepForward
1018 // take a mutable instruction instead of const.
1019 MachineOperand &Op = const_cast<MachineOperand&>(*Reg.second);
1020 MachineInstr *OpMI = Op.getParent();
1021 MachineInstrBuilder MIB(*OpMI->getParent()->getParent(), OpMI);
1022 if (Op.isRegMask()) {
1023 // First handle regmasks. They clobber any entries in the mask which
1024 // means that we need a def for those registers.
1025 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1027 // We also need to add an implicit def of this register for the later
1028 // use to read from.
1029 // For the register allocator to have allocated a register clobbered
1030 // by the call which is used later, it must be the case that
1031 // the call doesn't return.
1032 MIB.addReg(Reg.first, RegState::Implicit | RegState::Define);
1035 assert(Op.isReg() && "Register operand required");
1037 // If we found a dead def, but it needs to be live, then remove the dead
1039 if (Redefs.contains(Op.getReg()))
1040 Op.setIsDead(false);
1042 MIB.addReg(Reg.first, RegState::Implicit | RegState::Undef);
1047 * Remove kill flags from operands with a registers in the @p DontKill set.
1049 static void RemoveKills(MachineInstr &MI, const LivePhysRegs &DontKill) {
1050 for (MIBundleOperands O(&MI); O.isValid(); ++O) {
1051 if (!O->isReg() || !O->isKill())
1053 if (DontKill.contains(O->getReg()))
1054 O->setIsKill(false);
1059 * Walks a range of machine instructions and removes kill flags for registers
1060 * in the @p DontKill set.
1062 static void RemoveKills(MachineBasicBlock::iterator I,
1063 MachineBasicBlock::iterator E,
1064 const LivePhysRegs &DontKill,
1065 const MCRegisterInfo &MCRI) {
1066 for ( ; I != E; ++I)
1067 RemoveKills(*I, DontKill);
1070 /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
1072 bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1073 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1074 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1075 BBInfo *CvtBBI = &TrueBBI;
1076 BBInfo *NextBBI = &FalseBBI;
1078 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1079 if (Kind == ICSimpleFalse)
1080 std::swap(CvtBBI, NextBBI);
1082 if (CvtBBI->IsDone ||
1083 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1084 // Something has changed. It's no longer safe to predicate this block.
1085 BBI.IsAnalyzed = false;
1086 CvtBBI->IsAnalyzed = false;
1090 if (CvtBBI->BB->hasAddressTaken())
1091 // Conservatively abort if-conversion if BB's address is taken.
1094 if (Kind == ICSimpleFalse)
1095 if (TII->ReverseBranchCondition(Cond))
1096 llvm_unreachable("Unable to reverse branch condition!");
1098 // Initialize liveins to the first BB. These are potentiall redefined by
1099 // predicated instructions.
1101 Redefs.addLiveIns(CvtBBI->BB);
1102 Redefs.addLiveIns(NextBBI->BB);
1104 // Compute a set of registers which must not be killed by instructions in
1105 // BB1: This is everything live-in to BB2.
1107 DontKill.addLiveIns(NextBBI->BB);
1109 if (CvtBBI->BB->pred_size() > 1) {
1110 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1111 // Copy instructions in the true block, predicate them, and add them to
1113 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
1115 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1116 // explicitly remove CvtBBI as a successor.
1117 BBI.BB->removeSuccessor(CvtBBI->BB);
1119 RemoveKills(CvtBBI->BB->begin(), CvtBBI->BB->end(), DontKill, *TRI);
1120 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1122 // Merge converted block into entry block.
1123 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1124 MergeBlocks(BBI, *CvtBBI);
1127 bool IterIfcvt = true;
1128 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
1129 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1130 BBI.HasFallThrough = false;
1131 // Now ifcvt'd block will look like this:
1138 // We cannot further ifcvt this block because the unconditional branch
1139 // will have to be predicated on the new condition, that will not be
1140 // available if cmp executes.
1144 RemoveExtraEdges(BBI);
1146 // Update block info. BB can be iteratively if-converted.
1149 InvalidatePreds(BBI.BB);
1150 CvtBBI->IsDone = true;
1152 // FIXME: Must maintain LiveIns.
1156 /// Scale down weights to fit into uint32_t. NewTrue is the new weight
1157 /// for successor TrueBB, and NewFalse is the new weight for successor
1159 static void ScaleWeights(uint64_t NewTrue, uint64_t NewFalse,
1160 MachineBasicBlock *MBB,
1161 const MachineBasicBlock *TrueBB,
1162 const MachineBasicBlock *FalseBB,
1163 const MachineBranchProbabilityInfo *MBPI) {
1164 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1165 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1166 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1167 SE = MBB->succ_end();
1170 MBB->setSuccWeight(SI, (uint32_t)(NewTrue / Scale));
1171 else if (*SI == FalseBB)
1172 MBB->setSuccWeight(SI, (uint32_t)(NewFalse / Scale));
1174 MBB->setSuccWeight(SI, MBPI->getEdgeWeight(MBB, SI) / Scale);
1178 /// IfConvertTriangle - If convert a triangle sub-CFG.
1180 bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1181 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1182 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1183 BBInfo *CvtBBI = &TrueBBI;
1184 BBInfo *NextBBI = &FalseBBI;
1185 DebugLoc dl; // FIXME: this is nowhere
1187 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1188 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1189 std::swap(CvtBBI, NextBBI);
1191 if (CvtBBI->IsDone ||
1192 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
1193 // Something has changed. It's no longer safe to predicate this block.
1194 BBI.IsAnalyzed = false;
1195 CvtBBI->IsAnalyzed = false;
1199 if (CvtBBI->BB->hasAddressTaken())
1200 // Conservatively abort if-conversion if BB's address is taken.
1203 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1204 if (TII->ReverseBranchCondition(Cond))
1205 llvm_unreachable("Unable to reverse branch condition!");
1207 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1208 if (ReverseBranchCondition(*CvtBBI)) {
1209 // BB has been changed, modify its predecessors (except for this
1210 // one) so they don't get ifcvt'ed based on bad intel.
1211 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1212 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1213 MachineBasicBlock *PBB = *PI;
1216 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1217 if (PBBI.IsEnqueued) {
1218 PBBI.IsAnalyzed = false;
1219 PBBI.IsEnqueued = false;
1225 // Initialize liveins to the first BB. These are potentially redefined by
1226 // predicated instructions.
1228 Redefs.addLiveIns(CvtBBI->BB);
1229 Redefs.addLiveIns(NextBBI->BB);
1233 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
1234 uint64_t CvtNext = 0, CvtFalse = 0, BBNext = 0, BBCvt = 0, SumWeight = 0;
1235 uint32_t WeightScale = 0;
1238 // Get weights before modifying CvtBBI->BB and BBI.BB.
1239 CvtNext = MBPI->getEdgeWeight(CvtBBI->BB, NextBBI->BB);
1240 CvtFalse = MBPI->getEdgeWeight(CvtBBI->BB, CvtBBI->FalseBB);
1241 BBNext = MBPI->getEdgeWeight(BBI.BB, NextBBI->BB);
1242 BBCvt = MBPI->getEdgeWeight(BBI.BB, CvtBBI->BB);
1243 SumWeight = MBPI->getSumForBlock(CvtBBI->BB, WeightScale);
1246 if (CvtBBI->BB->pred_size() > 1) {
1247 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1248 // Copy instructions in the true block, predicate them, and add them to
1250 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
1252 // RemoveExtraEdges won't work if the block has an unanalyzable branch, so
1253 // explicitly remove CvtBBI as a successor.
1254 BBI.BB->removeSuccessor(CvtBBI->BB);
1256 // Predicate the 'true' block after removing its branch.
1257 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
1258 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond);
1260 // Now merge the entry of the triangle with the true block.
1261 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1262 MergeBlocks(BBI, *CvtBBI, false);
1265 // If 'true' block has a 'false' successor, add an exit branch to it.
1267 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1268 CvtBBI->BrCond.end());
1269 if (TII->ReverseBranchCondition(RevCond))
1270 llvm_unreachable("Unable to reverse branch condition!");
1271 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
1272 BBI.BB->addSuccessor(CvtBBI->FalseBB);
1273 // Update the edge weight for both CvtBBI->FalseBB and NextBBI.
1274 // New_Weight(BBI.BB, NextBBI->BB) =
1275 // Weight(BBI.BB, NextBBI->BB) * getSumForBlock(CvtBBI->BB) +
1276 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, NextBBI->BB)
1277 // New_Weight(BBI.BB, CvtBBI->FalseBB) =
1278 // Weight(BBI.BB, CvtBBI->BB) * Weight(CvtBBI->BB, CvtBBI->FalseBB)
1280 uint64_t NewNext = BBNext * SumWeight + (BBCvt * CvtNext) / WeightScale;
1281 uint64_t NewFalse = (BBCvt * CvtFalse) / WeightScale;
1282 // We need to scale down all weights of BBI.BB to fit uint32_t.
1283 // Here BBI.BB is connected to CvtBBI->FalseBB and will fall through to
1285 ScaleWeights(NewNext, NewFalse, BBI.BB, getNextBlock(BBI.BB),
1286 CvtBBI->FalseBB, MBPI);
1289 // Merge in the 'false' block if the 'false' block has no other
1290 // predecessors. Otherwise, add an unconditional branch to 'false'.
1291 bool FalseBBDead = false;
1292 bool IterIfcvt = true;
1293 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
1294 if (!isFallThrough) {
1295 // Only merge them if the true block does not fallthrough to the false
1296 // block. By not merging them, we make it possible to iteratively
1297 // ifcvt the blocks.
1298 if (!HasEarlyExit &&
1299 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough &&
1300 !NextBBI->BB->hasAddressTaken()) {
1301 MergeBlocks(BBI, *NextBBI);
1304 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1305 BBI.HasFallThrough = false;
1307 // Mixed predicated and unpredicated code. This cannot be iteratively
1312 RemoveExtraEdges(BBI);
1314 // Update block info. BB can be iteratively if-converted.
1317 InvalidatePreds(BBI.BB);
1318 CvtBBI->IsDone = true;
1320 NextBBI->IsDone = true;
1322 // FIXME: Must maintain LiveIns.
1326 /// IfConvertDiamond - If convert a diamond sub-CFG.
1328 bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1329 unsigned NumDups1, unsigned NumDups2) {
1330 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1331 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1332 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1333 // True block must fall through or end with an unanalyzable terminator.
1335 if (blockAlwaysFallThrough(TrueBBI))
1336 TailBB = FalseBBI.TrueBB;
1337 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1340 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1341 TrueBBI.BB->pred_size() > 1 ||
1342 FalseBBI.BB->pred_size() > 1) {
1343 // Something has changed. It's no longer safe to predicate these blocks.
1344 BBI.IsAnalyzed = false;
1345 TrueBBI.IsAnalyzed = false;
1346 FalseBBI.IsAnalyzed = false;
1350 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1351 // Conservatively abort if-conversion if either BB has its address taken.
1354 // Put the predicated instructions from the 'true' block before the
1355 // instructions from the 'false' block, unless the true block would clobber
1356 // the predicate, in which case, do the opposite.
1357 BBInfo *BBI1 = &TrueBBI;
1358 BBInfo *BBI2 = &FalseBBI;
1359 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1360 if (TII->ReverseBranchCondition(RevCond))
1361 llvm_unreachable("Unable to reverse branch condition!");
1362 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1363 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1365 // Figure out the more profitable ordering.
1366 bool DoSwap = false;
1367 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1369 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
1370 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1374 std::swap(BBI1, BBI2);
1375 std::swap(Cond1, Cond2);
1378 // Remove the conditional branch from entry to the blocks.
1379 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1381 // Initialize liveins to the first BB. These are potentially redefined by
1382 // predicated instructions.
1384 Redefs.addLiveIns(BBI1->BB);
1386 // Remove the duplicated instructions at the beginnings of both paths.
1387 // Skip dbg_value instructions
1388 MachineBasicBlock::iterator DI1 = BBI1->BB->getFirstNonDebugInstr();
1389 MachineBasicBlock::iterator DI2 = BBI2->BB->getFirstNonDebugInstr();
1390 BBI1->NonPredSize -= NumDups1;
1391 BBI2->NonPredSize -= NumDups1;
1393 // Skip past the dups on each side separately since there may be
1394 // differing dbg_value entries.
1395 for (unsigned i = 0; i < NumDups1; ++DI1) {
1396 if (!DI1->isDebugValue())
1399 while (NumDups1 != 0) {
1401 if (!DI2->isDebugValue())
1405 // Compute a set of registers which must not be killed by instructions in BB1:
1406 // This is everything used+live in BB2 after the duplicated instructions. We
1407 // can compute this set by simulating liveness backwards from the end of BB2.
1409 for (MachineBasicBlock::reverse_iterator I = BBI2->BB->rbegin(),
1410 E = MachineBasicBlock::reverse_iterator(DI2); I != E; ++I) {
1411 DontKill.stepBackward(*I);
1414 for (MachineBasicBlock::const_iterator I = BBI1->BB->begin(), E = DI1; I != E;
1416 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> IgnoredClobbers;
1417 Redefs.stepForward(*I, IgnoredClobbers);
1419 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1420 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1422 // Remove branch from 'true' block and remove duplicated instructions.
1423 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
1424 DI1 = BBI1->BB->end();
1425 for (unsigned i = 0; i != NumDups2; ) {
1426 // NumDups2 only counted non-dbg_value instructions, so this won't
1427 // run off the head of the list.
1428 assert (DI1 != BBI1->BB->begin());
1430 // skip dbg_value instructions
1431 if (!DI1->isDebugValue())
1434 BBI1->BB->erase(DI1, BBI1->BB->end());
1436 // Kill flags in the true block for registers living into the false block
1438 RemoveKills(BBI1->BB->begin(), BBI1->BB->end(), DontKill, *TRI);
1440 // Remove 'false' block branch and find the last instruction to predicate.
1441 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1442 DI2 = BBI2->BB->end();
1443 while (NumDups2 != 0) {
1444 // NumDups2 only counted non-dbg_value instructions, so this won't
1445 // run off the head of the list.
1446 assert (DI2 != BBI2->BB->begin());
1448 // skip dbg_value instructions
1449 if (!DI2->isDebugValue())
1453 // Remember which registers would later be defined by the false block.
1454 // This allows us not to predicate instructions in the true block that would
1455 // later be re-defined. That is, rather than
1461 SmallSet<unsigned, 4> RedefsByFalse;
1462 SmallSet<unsigned, 4> ExtUses;
1463 if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
1464 for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
1465 if (FI->isDebugValue())
1467 SmallVector<unsigned, 4> Defs;
1468 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
1469 const MachineOperand &MO = FI->getOperand(i);
1472 unsigned Reg = MO.getReg();
1476 Defs.push_back(Reg);
1477 } else if (!RedefsByFalse.count(Reg)) {
1478 // These are defined before ctrl flow reach the 'false' instructions.
1479 // They cannot be modified by the 'true' instructions.
1480 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1481 SubRegs.isValid(); ++SubRegs)
1482 ExtUses.insert(*SubRegs);
1486 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1487 unsigned Reg = Defs[i];
1488 if (!ExtUses.count(Reg)) {
1489 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1490 SubRegs.isValid(); ++SubRegs)
1491 RedefsByFalse.insert(*SubRegs);
1497 // Predicate the 'true' block.
1498 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, &RedefsByFalse);
1500 // Predicate the 'false' block.
1501 PredicateBlock(*BBI2, DI2, *Cond2);
1503 // Merge the true block into the entry of the diamond.
1504 MergeBlocks(BBI, *BBI1, TailBB == nullptr);
1505 MergeBlocks(BBI, *BBI2, TailBB == nullptr);
1507 // If the if-converted block falls through or unconditionally branches into
1508 // the tail block, and the tail block does not have other predecessors, then
1509 // fold the tail block in as well. Otherwise, unless it falls through to the
1510 // tail, add a unconditional branch to it.
1512 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
1513 bool CanMergeTail = !TailBBI.HasFallThrough &&
1514 !TailBBI.BB->hasAddressTaken();
1515 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1516 // check if there are any other predecessors besides those.
1517 unsigned NumPreds = TailBB->pred_size();
1519 CanMergeTail = false;
1520 else if (NumPreds == 1 && CanMergeTail) {
1521 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1522 if (*PI != BBI1->BB && *PI != BBI2->BB)
1523 CanMergeTail = false;
1526 MergeBlocks(BBI, TailBBI);
1527 TailBBI.IsDone = true;
1529 BBI.BB->addSuccessor(TailBB);
1530 InsertUncondBranch(BBI.BB, TailBB, TII);
1531 BBI.HasFallThrough = false;
1535 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1536 // which can happen here if TailBB is unanalyzable and is merged, so
1537 // explicitly remove BBI1 and BBI2 as successors.
1538 BBI.BB->removeSuccessor(BBI1->BB);
1539 BBI.BB->removeSuccessor(BBI2->BB);
1540 RemoveExtraEdges(BBI);
1542 // Update block info.
1543 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1544 InvalidatePreds(BBI.BB);
1546 // FIXME: Must maintain LiveIns.
1550 static bool MaySpeculate(const MachineInstr *MI,
1551 SmallSet<unsigned, 4> &LaterRedefs) {
1552 bool SawStore = true;
1553 if (!MI->isSafeToMove(nullptr, SawStore))
1556 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1557 const MachineOperand &MO = MI->getOperand(i);
1560 unsigned Reg = MO.getReg();
1563 if (MO.isDef() && !LaterRedefs.count(Reg))
1570 /// PredicateBlock - Predicate instructions from the start of the block to the
1571 /// specified end with the specified condition.
1572 void IfConverter::PredicateBlock(BBInfo &BBI,
1573 MachineBasicBlock::iterator E,
1574 SmallVectorImpl<MachineOperand> &Cond,
1575 SmallSet<unsigned, 4> *LaterRedefs) {
1576 bool AnyUnpred = false;
1577 bool MaySpec = LaterRedefs != nullptr;
1578 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
1579 if (I->isDebugValue() || TII->isPredicated(I))
1581 // It may be possible not to predicate an instruction if it's the 'true'
1582 // side of a diamond and the 'false' side may re-define the instruction's
1584 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
1588 // If any instruction is predicated, then every instruction after it must
1591 if (!TII->PredicateInstruction(I, Cond)) {
1593 dbgs() << "Unable to predicate " << *I << "!\n";
1595 llvm_unreachable(nullptr);
1598 // If the predicated instruction now redefines a register as the result of
1599 // if-conversion, add an implicit kill.
1600 UpdatePredRedefs(I, Redefs);
1603 BBI.Predicate.append(Cond.begin(), Cond.end());
1605 BBI.IsAnalyzed = false;
1606 BBI.NonPredSize = 0;
1613 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1614 /// the destination block. Skip end of block branches if IgnoreBr is true.
1615 void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
1616 SmallVectorImpl<MachineOperand> &Cond,
1618 MachineFunction &MF = *ToBBI.BB->getParent();
1620 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1621 E = FromBBI.BB->end(); I != E; ++I) {
1622 // Do not copy the end of the block branches.
1623 if (IgnoreBr && I->isBranch())
1626 MachineInstr *MI = MF.CloneMachineInstr(I);
1627 ToBBI.BB->insert(ToBBI.BB->end(), MI);
1628 ToBBI.NonPredSize++;
1629 unsigned ExtraPredCost = TII->getPredicationCost(&*I);
1630 unsigned NumCycles = SchedModel.computeInstrLatency(&*I, false);
1632 ToBBI.ExtraCost += NumCycles-1;
1633 ToBBI.ExtraCost2 += ExtraPredCost;
1635 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
1636 if (!TII->PredicateInstruction(MI, Cond)) {
1638 dbgs() << "Unable to predicate " << *I << "!\n";
1640 llvm_unreachable(nullptr);
1644 // If the predicated instruction now redefines a register as the result of
1645 // if-conversion, add an implicit kill.
1646 UpdatePredRedefs(MI, Redefs);
1648 // Some kill flags may not be correct anymore.
1649 if (!DontKill.empty())
1650 RemoveKills(*MI, DontKill);
1654 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1655 FromBBI.BB->succ_end());
1656 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1657 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1659 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1660 MachineBasicBlock *Succ = Succs[i];
1661 // Fallthrough edge can't be transferred.
1662 if (Succ == FallThrough)
1664 ToBBI.BB->addSuccessor(Succ);
1668 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1669 ToBBI.Predicate.append(Cond.begin(), Cond.end());
1671 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1672 ToBBI.IsAnalyzed = false;
1677 /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
1678 /// This will leave FromBB as an empty block, so remove all of its
1679 /// successor edges except for the fall-through edge. If AddEdges is true,
1680 /// i.e., when FromBBI's branch is being moved, add those successor edges to
1682 void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
1683 assert(!FromBBI.BB->hasAddressTaken() &&
1684 "Removing a BB whose address is taken!");
1686 ToBBI.BB->splice(ToBBI.BB->end(),
1687 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
1689 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1690 FromBBI.BB->succ_end());
1691 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1692 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
1694 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1695 MachineBasicBlock *Succ = Succs[i];
1696 // Fallthrough edge can't be transferred.
1697 if (Succ == FallThrough)
1699 FromBBI.BB->removeSuccessor(Succ);
1700 if (AddEdges && !ToBBI.BB->isSuccessor(Succ))
1701 ToBBI.BB->addSuccessor(Succ);
1704 // Now FromBBI always falls through to the next block!
1705 if (NBB && !FromBBI.BB->isSuccessor(NBB))
1706 FromBBI.BB->addSuccessor(NBB);
1708 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
1709 FromBBI.Predicate.clear();
1711 ToBBI.NonPredSize += FromBBI.NonPredSize;
1712 ToBBI.ExtraCost += FromBBI.ExtraCost;
1713 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
1714 FromBBI.NonPredSize = 0;
1715 FromBBI.ExtraCost = 0;
1716 FromBBI.ExtraCost2 = 0;
1718 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1719 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
1720 ToBBI.IsAnalyzed = false;
1721 FromBBI.IsAnalyzed = false;
1725 llvm::createIfConverter(std::function<bool(const Function &)> Ftor) {
1726 return new IfConverter(Ftor);