10b57cec5SDimitry Andric //===- IfConversion.cpp - Machine code if conversion pass -----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the machine instruction level if-conversion pass, which
100b57cec5SDimitry Andric // tries to convert conditional branches into predicated instructions.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric
140b57cec5SDimitry Andric #include "BranchFolding.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SparseSet.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
210b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
22480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
2481ad6265SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
390b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
40480093f4SDimitry Andric #include "llvm/InitializePasses.h"
410b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
420b57cec5SDimitry Andric #include "llvm/Pass.h"
430b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
440b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
450b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
460b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
470b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
480b57cec5SDimitry Andric #include <algorithm>
490b57cec5SDimitry Andric #include <cassert>
500b57cec5SDimitry Andric #include <functional>
510b57cec5SDimitry Andric #include <iterator>
520b57cec5SDimitry Andric #include <memory>
530b57cec5SDimitry Andric #include <utility>
540b57cec5SDimitry Andric #include <vector>
550b57cec5SDimitry Andric
560b57cec5SDimitry Andric using namespace llvm;
570b57cec5SDimitry Andric
580b57cec5SDimitry Andric #define DEBUG_TYPE "if-converter"
590b57cec5SDimitry Andric
600b57cec5SDimitry Andric // Hidden options for help debugging.
610b57cec5SDimitry Andric static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
620b57cec5SDimitry Andric static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
630b57cec5SDimitry Andric static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
640b57cec5SDimitry Andric static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
650b57cec5SDimitry Andric cl::init(false), cl::Hidden);
660b57cec5SDimitry Andric static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
670b57cec5SDimitry Andric cl::init(false), cl::Hidden);
680b57cec5SDimitry Andric static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
690b57cec5SDimitry Andric cl::init(false), cl::Hidden);
700b57cec5SDimitry Andric static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
710b57cec5SDimitry Andric cl::init(false), cl::Hidden);
720b57cec5SDimitry Andric static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
730b57cec5SDimitry Andric cl::init(false), cl::Hidden);
740b57cec5SDimitry Andric static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
750b57cec5SDimitry Andric cl::init(false), cl::Hidden);
760b57cec5SDimitry Andric static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
770b57cec5SDimitry Andric cl::init(false), cl::Hidden);
780b57cec5SDimitry Andric static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
790b57cec5SDimitry Andric cl::init(true), cl::Hidden);
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric STATISTIC(NumSimple, "Number of simple if-conversions performed");
820b57cec5SDimitry Andric STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
830b57cec5SDimitry Andric STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
840b57cec5SDimitry Andric STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
850b57cec5SDimitry Andric STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
860b57cec5SDimitry Andric STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
870b57cec5SDimitry Andric STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
880b57cec5SDimitry Andric STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
890b57cec5SDimitry Andric STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
900b57cec5SDimitry Andric STATISTIC(NumDupBBs, "Number of duplicated blocks");
910b57cec5SDimitry Andric STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
920b57cec5SDimitry Andric
930b57cec5SDimitry Andric namespace {
940b57cec5SDimitry Andric
950b57cec5SDimitry Andric class IfConverter : public MachineFunctionPass {
960b57cec5SDimitry Andric enum IfcvtKind {
970b57cec5SDimitry Andric ICNotClassfied, // BB data valid, but not classified.
980b57cec5SDimitry Andric ICSimpleFalse, // Same as ICSimple, but on the false path.
990b57cec5SDimitry Andric ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
1000b57cec5SDimitry Andric ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
1010b57cec5SDimitry Andric ICTriangleRev, // Same as ICTriangle, but true path rev condition.
1020b57cec5SDimitry Andric ICTriangleFalse, // Same as ICTriangle, but on the false path.
1030b57cec5SDimitry Andric ICTriangle, // BB is entry of a triangle sub-CFG.
1040b57cec5SDimitry Andric ICDiamond, // BB is entry of a diamond sub-CFG.
1050b57cec5SDimitry Andric ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
1060b57cec5SDimitry Andric // common tail that can be shared.
1070b57cec5SDimitry Andric };
1080b57cec5SDimitry Andric
1090b57cec5SDimitry Andric /// One per MachineBasicBlock, this is used to cache the result
1100b57cec5SDimitry Andric /// if-conversion feasibility analysis. This includes results from
1110b57cec5SDimitry Andric /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
1120b57cec5SDimitry Andric /// classification, and common tail block of its successors (if it's a
1130b57cec5SDimitry Andric /// diamond shape), its size, whether it's predicable, and whether any
1140b57cec5SDimitry Andric /// instruction can clobber the 'would-be' predicate.
1150b57cec5SDimitry Andric ///
1160b57cec5SDimitry Andric /// IsDone - True if BB is not to be considered for ifcvt.
1170b57cec5SDimitry Andric /// IsBeingAnalyzed - True if BB is currently being analyzed.
1180b57cec5SDimitry Andric /// IsAnalyzed - True if BB has been analyzed (info is still valid).
1190b57cec5SDimitry Andric /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
1200b57cec5SDimitry Andric /// IsBrAnalyzable - True if analyzeBranch() returns false.
1210b57cec5SDimitry Andric /// HasFallThrough - True if BB may fallthrough to the following BB.
1220b57cec5SDimitry Andric /// IsUnpredicable - True if BB is known to be unpredicable.
1230b57cec5SDimitry Andric /// ClobbersPred - True if BB could modify predicates (e.g. has
1240b57cec5SDimitry Andric /// cmp, call, etc.)
1250b57cec5SDimitry Andric /// NonPredSize - Number of non-predicated instructions.
1260b57cec5SDimitry Andric /// ExtraCost - Extra cost for multi-cycle instructions.
1270b57cec5SDimitry Andric /// ExtraCost2 - Some instructions are slower when predicated
1280b57cec5SDimitry Andric /// BB - Corresponding MachineBasicBlock.
1290b57cec5SDimitry Andric /// TrueBB / FalseBB- See analyzeBranch().
1300b57cec5SDimitry Andric /// BrCond - Conditions for end of block conditional branches.
1310b57cec5SDimitry Andric /// Predicate - Predicate used in the BB.
1320b57cec5SDimitry Andric struct BBInfo {
1330b57cec5SDimitry Andric bool IsDone : 1;
1340b57cec5SDimitry Andric bool IsBeingAnalyzed : 1;
1350b57cec5SDimitry Andric bool IsAnalyzed : 1;
1360b57cec5SDimitry Andric bool IsEnqueued : 1;
1370b57cec5SDimitry Andric bool IsBrAnalyzable : 1;
1380b57cec5SDimitry Andric bool IsBrReversible : 1;
1390b57cec5SDimitry Andric bool HasFallThrough : 1;
1400b57cec5SDimitry Andric bool IsUnpredicable : 1;
1410b57cec5SDimitry Andric bool CannotBeCopied : 1;
1420b57cec5SDimitry Andric bool ClobbersPred : 1;
1430b57cec5SDimitry Andric unsigned NonPredSize = 0;
1440b57cec5SDimitry Andric unsigned ExtraCost = 0;
1450b57cec5SDimitry Andric unsigned ExtraCost2 = 0;
1460b57cec5SDimitry Andric MachineBasicBlock *BB = nullptr;
1470b57cec5SDimitry Andric MachineBasicBlock *TrueBB = nullptr;
1480b57cec5SDimitry Andric MachineBasicBlock *FalseBB = nullptr;
1490b57cec5SDimitry Andric SmallVector<MachineOperand, 4> BrCond;
1500b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Predicate;
1510b57cec5SDimitry Andric
BBInfo__anon4149301f0111::IfConverter::BBInfo1520b57cec5SDimitry Andric BBInfo() : IsDone(false), IsBeingAnalyzed(false),
1530b57cec5SDimitry Andric IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
1540b57cec5SDimitry Andric IsBrReversible(false), HasFallThrough(false),
1550b57cec5SDimitry Andric IsUnpredicable(false), CannotBeCopied(false),
1560b57cec5SDimitry Andric ClobbersPred(false) {}
1570b57cec5SDimitry Andric };
1580b57cec5SDimitry Andric
1590b57cec5SDimitry Andric /// Record information about pending if-conversions to attempt:
1600b57cec5SDimitry Andric /// BBI - Corresponding BBInfo.
1610b57cec5SDimitry Andric /// Kind - Type of block. See IfcvtKind.
1620b57cec5SDimitry Andric /// NeedSubsumption - True if the to-be-predicated BB has already been
1630b57cec5SDimitry Andric /// predicated.
1640b57cec5SDimitry Andric /// NumDups - Number of instructions that would be duplicated due
1650b57cec5SDimitry Andric /// to this if-conversion. (For diamonds, the number of
1660b57cec5SDimitry Andric /// identical instructions at the beginnings of both
1670b57cec5SDimitry Andric /// paths).
1680b57cec5SDimitry Andric /// NumDups2 - For diamonds, the number of identical instructions
1690b57cec5SDimitry Andric /// at the ends of both paths.
1700b57cec5SDimitry Andric struct IfcvtToken {
1710b57cec5SDimitry Andric BBInfo &BBI;
1720b57cec5SDimitry Andric IfcvtKind Kind;
1730b57cec5SDimitry Andric unsigned NumDups;
1740b57cec5SDimitry Andric unsigned NumDups2;
1750b57cec5SDimitry Andric bool NeedSubsumption : 1;
1760b57cec5SDimitry Andric bool TClobbersPred : 1;
1770b57cec5SDimitry Andric bool FClobbersPred : 1;
1780b57cec5SDimitry Andric
IfcvtToken__anon4149301f0111::IfConverter::IfcvtToken1790b57cec5SDimitry Andric IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
1800b57cec5SDimitry Andric bool tc = false, bool fc = false)
1810b57cec5SDimitry Andric : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
1820b57cec5SDimitry Andric TClobbersPred(tc), FClobbersPred(fc) {}
1830b57cec5SDimitry Andric };
1840b57cec5SDimitry Andric
1850b57cec5SDimitry Andric /// Results of if-conversion feasibility analysis indexed by basic block
1860b57cec5SDimitry Andric /// number.
1870b57cec5SDimitry Andric std::vector<BBInfo> BBAnalysis;
1880b57cec5SDimitry Andric TargetSchedModel SchedModel;
1890b57cec5SDimitry Andric
190fe013be4SDimitry Andric const TargetLoweringBase *TLI = nullptr;
191fe013be4SDimitry Andric const TargetInstrInfo *TII = nullptr;
192fe013be4SDimitry Andric const TargetRegisterInfo *TRI = nullptr;
193fe013be4SDimitry Andric const MachineBranchProbabilityInfo *MBPI = nullptr;
194fe013be4SDimitry Andric MachineRegisterInfo *MRI = nullptr;
1950b57cec5SDimitry Andric
1960b57cec5SDimitry Andric LivePhysRegs Redefs;
1970b57cec5SDimitry Andric
198fe013be4SDimitry Andric bool PreRegAlloc = true;
199fe013be4SDimitry Andric bool MadeChange = false;
2000b57cec5SDimitry Andric int FnNum = -1;
2010b57cec5SDimitry Andric std::function<bool(const MachineFunction &)> PredicateFtor;
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric public:
2040b57cec5SDimitry Andric static char ID;
2050b57cec5SDimitry Andric
IfConverter(std::function<bool (const MachineFunction &)> Ftor=nullptr)2060b57cec5SDimitry Andric IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
2070b57cec5SDimitry Andric : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
2080b57cec5SDimitry Andric initializeIfConverterPass(*PassRegistry::getPassRegistry());
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const2110b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
2120b57cec5SDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>();
2130b57cec5SDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>();
214480093f4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>();
2150b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override;
2190b57cec5SDimitry Andric
getRequiredProperties() const2200b57cec5SDimitry Andric MachineFunctionProperties getRequiredProperties() const override {
2210b57cec5SDimitry Andric return MachineFunctionProperties().set(
2220b57cec5SDimitry Andric MachineFunctionProperties::Property::NoVRegs);
2230b57cec5SDimitry Andric }
2240b57cec5SDimitry Andric
2250b57cec5SDimitry Andric private:
2260b57cec5SDimitry Andric bool reverseBranchCondition(BBInfo &BBI) const;
2270b57cec5SDimitry Andric bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
2280b57cec5SDimitry Andric BranchProbability Prediction) const;
2290b57cec5SDimitry Andric bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
2300b57cec5SDimitry Andric bool FalseBranch, unsigned &Dups,
2310b57cec5SDimitry Andric BranchProbability Prediction) const;
2320b57cec5SDimitry Andric bool CountDuplicatedInstructions(
2330b57cec5SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
2340b57cec5SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
2350b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
2360b57cec5SDimitry Andric MachineBasicBlock &TBB, MachineBasicBlock &FBB,
2370b57cec5SDimitry Andric bool SkipUnconditionalBranches) const;
2380b57cec5SDimitry Andric bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
2390b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
2400b57cec5SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
2410b57cec5SDimitry Andric bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
2420b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
2430b57cec5SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
2440b57cec5SDimitry Andric void AnalyzeBranches(BBInfo &BBI);
2450b57cec5SDimitry Andric void ScanInstructions(BBInfo &BBI,
2460b57cec5SDimitry Andric MachineBasicBlock::iterator &Begin,
2470b57cec5SDimitry Andric MachineBasicBlock::iterator &End,
2480b57cec5SDimitry Andric bool BranchUnpredicable = false) const;
2490b57cec5SDimitry Andric bool RescanInstructions(
2500b57cec5SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
2510b57cec5SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
2520b57cec5SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI) const;
2530b57cec5SDimitry Andric void AnalyzeBlock(MachineBasicBlock &MBB,
2540b57cec5SDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
2550b57cec5SDimitry Andric bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
2560b57cec5SDimitry Andric bool isTriangle = false, bool RevBranch = false,
2570b57cec5SDimitry Andric bool hasCommonTail = false);
2580b57cec5SDimitry Andric void AnalyzeBlocks(MachineFunction &MF,
2590b57cec5SDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
2600b57cec5SDimitry Andric void InvalidatePreds(MachineBasicBlock &MBB);
2610b57cec5SDimitry Andric bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
2620b57cec5SDimitry Andric bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
2630b57cec5SDimitry Andric bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
2640b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
2650b57cec5SDimitry Andric bool TClobbersPred, bool FClobbersPred,
2660b57cec5SDimitry Andric bool RemoveBranch, bool MergeAddEdges);
2670b57cec5SDimitry Andric bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
2680b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
2690b57cec5SDimitry Andric bool TClobbers, bool FClobbers);
2700b57cec5SDimitry Andric bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
2710b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
2720b57cec5SDimitry Andric bool TClobbers, bool FClobbers);
2730b57cec5SDimitry Andric void PredicateBlock(BBInfo &BBI,
2740b57cec5SDimitry Andric MachineBasicBlock::iterator E,
2750b57cec5SDimitry Andric SmallVectorImpl<MachineOperand> &Cond,
2760b57cec5SDimitry Andric SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
2770b57cec5SDimitry Andric void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
2780b57cec5SDimitry Andric SmallVectorImpl<MachineOperand> &Cond,
2790b57cec5SDimitry Andric bool IgnoreBr = false);
2800b57cec5SDimitry Andric void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
2810b57cec5SDimitry Andric
MeetIfcvtSizeLimit(MachineBasicBlock & BB,unsigned Cycle,unsigned Extra,BranchProbability Prediction) const2820b57cec5SDimitry Andric bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
2830b57cec5SDimitry Andric unsigned Cycle, unsigned Extra,
2840b57cec5SDimitry Andric BranchProbability Prediction) const {
2850b57cec5SDimitry Andric return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
2860b57cec5SDimitry Andric Prediction);
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric
MeetIfcvtSizeLimit(BBInfo & TBBInfo,BBInfo & FBBInfo,MachineBasicBlock & CommBB,unsigned Dups,BranchProbability Prediction,bool Forked) const2898bcb0991SDimitry Andric bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
2908bcb0991SDimitry Andric MachineBasicBlock &CommBB, unsigned Dups,
2918bcb0991SDimitry Andric BranchProbability Prediction, bool Forked) const {
2928bcb0991SDimitry Andric const MachineFunction &MF = *TBBInfo.BB->getParent();
2938bcb0991SDimitry Andric if (MF.getFunction().hasMinSize()) {
2948bcb0991SDimitry Andric MachineBasicBlock::iterator TIB = TBBInfo.BB->begin();
2958bcb0991SDimitry Andric MachineBasicBlock::iterator FIB = FBBInfo.BB->begin();
2968bcb0991SDimitry Andric MachineBasicBlock::iterator TIE = TBBInfo.BB->end();
2978bcb0991SDimitry Andric MachineBasicBlock::iterator FIE = FBBInfo.BB->end();
2988bcb0991SDimitry Andric
299fe6060f1SDimitry Andric unsigned Dups1 = 0, Dups2 = 0;
3008bcb0991SDimitry Andric if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
3018bcb0991SDimitry Andric *TBBInfo.BB, *FBBInfo.BB,
3028bcb0991SDimitry Andric /*SkipUnconditionalBranches*/ true))
3038bcb0991SDimitry Andric llvm_unreachable("should already have been checked by ValidDiamond");
3048bcb0991SDimitry Andric
3058bcb0991SDimitry Andric unsigned BranchBytes = 0;
3068bcb0991SDimitry Andric unsigned CommonBytes = 0;
3078bcb0991SDimitry Andric
3088bcb0991SDimitry Andric // Count common instructions at the start of the true and false blocks.
3098bcb0991SDimitry Andric for (auto &I : make_range(TBBInfo.BB->begin(), TIB)) {
3108bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3118bcb0991SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3128bcb0991SDimitry Andric }
3138bcb0991SDimitry Andric for (auto &I : make_range(FBBInfo.BB->begin(), FIB)) {
3148bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3158bcb0991SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3168bcb0991SDimitry Andric }
3178bcb0991SDimitry Andric
3188bcb0991SDimitry Andric // Count instructions at the end of the true and false blocks, after
3198bcb0991SDimitry Andric // the ones we plan to predicate. Analyzable branches will be removed
3208bcb0991SDimitry Andric // (unless this is a forked diamond), and all other instructions are
3218bcb0991SDimitry Andric // common between the two blocks.
3228bcb0991SDimitry Andric for (auto &I : make_range(TIE, TBBInfo.BB->end())) {
3238bcb0991SDimitry Andric if (I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
3248bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3258bcb0991SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3268bcb0991SDimitry Andric } else {
3278bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3288bcb0991SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3298bcb0991SDimitry Andric }
3308bcb0991SDimitry Andric }
3318bcb0991SDimitry Andric for (auto &I : make_range(FIE, FBBInfo.BB->end())) {
3328bcb0991SDimitry Andric if (I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
3338bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3348bcb0991SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3358bcb0991SDimitry Andric } else {
3368bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Common inst: " << I);
3378bcb0991SDimitry Andric CommonBytes += TII->getInstSizeInBytes(I);
3388bcb0991SDimitry Andric }
3398bcb0991SDimitry Andric }
3408bcb0991SDimitry Andric for (auto &I : CommBB.terminators()) {
3418bcb0991SDimitry Andric if (I.isBranch()) {
3428bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Saving branch: " << I);
3438bcb0991SDimitry Andric BranchBytes += TII->predictBranchSizeForIfCvt(I);
3448bcb0991SDimitry Andric }
3458bcb0991SDimitry Andric }
3468bcb0991SDimitry Andric
3478bcb0991SDimitry Andric // The common instructions in one branch will be eliminated, halving
3488bcb0991SDimitry Andric // their code size.
3498bcb0991SDimitry Andric CommonBytes /= 2;
3508bcb0991SDimitry Andric
3518bcb0991SDimitry Andric // Count the instructions which we need to predicate.
3528bcb0991SDimitry Andric unsigned NumPredicatedInstructions = 0;
3538bcb0991SDimitry Andric for (auto &I : make_range(TIB, TIE)) {
3548bcb0991SDimitry Andric if (!I.isDebugInstr()) {
3558bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Predicating: " << I);
3568bcb0991SDimitry Andric NumPredicatedInstructions++;
3578bcb0991SDimitry Andric }
3588bcb0991SDimitry Andric }
3598bcb0991SDimitry Andric for (auto &I : make_range(FIB, FIE)) {
3608bcb0991SDimitry Andric if (!I.isDebugInstr()) {
3618bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Predicating: " << I);
3628bcb0991SDimitry Andric NumPredicatedInstructions++;
3638bcb0991SDimitry Andric }
3648bcb0991SDimitry Andric }
3658bcb0991SDimitry Andric
3668bcb0991SDimitry Andric // Even though we're optimising for size at the expense of performance,
3678bcb0991SDimitry Andric // avoid creating really long predicated blocks.
3688bcb0991SDimitry Andric if (NumPredicatedInstructions > 15)
3698bcb0991SDimitry Andric return false;
3708bcb0991SDimitry Andric
3718bcb0991SDimitry Andric // Some targets (e.g. Thumb2) need to insert extra instructions to
3728bcb0991SDimitry Andric // start predicated blocks.
3738bcb0991SDimitry Andric unsigned ExtraPredicateBytes = TII->extraSizeToPredicateInstructions(
3748bcb0991SDimitry Andric MF, NumPredicatedInstructions);
3758bcb0991SDimitry Andric
3768bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
3778bcb0991SDimitry Andric << ", CommonBytes=" << CommonBytes
3788bcb0991SDimitry Andric << ", NumPredicatedInstructions="
3798bcb0991SDimitry Andric << NumPredicatedInstructions
3808bcb0991SDimitry Andric << ", ExtraPredicateBytes=" << ExtraPredicateBytes
3818bcb0991SDimitry Andric << ")\n");
3828bcb0991SDimitry Andric return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
3838bcb0991SDimitry Andric } else {
3848bcb0991SDimitry Andric unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
3858bcb0991SDimitry Andric unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
3868bcb0991SDimitry Andric bool Res = TCycle > 0 && FCycle > 0 &&
3878bcb0991SDimitry Andric TII->isProfitableToIfCvt(
3888bcb0991SDimitry Andric *TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
3898bcb0991SDimitry Andric FCycle, FBBInfo.ExtraCost2, Prediction);
3908bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle
3918bcb0991SDimitry Andric << ", FCycle=" << FCycle
3928bcb0991SDimitry Andric << ", TExtra=" << TBBInfo.ExtraCost2 << ", FExtra="
3938bcb0991SDimitry Andric << FBBInfo.ExtraCost2 << ") = " << Res << "\n");
3948bcb0991SDimitry Andric return Res;
3958bcb0991SDimitry Andric }
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric
3980b57cec5SDimitry Andric /// Returns true if Block ends without a terminator.
blockAlwaysFallThrough(BBInfo & BBI) const3990b57cec5SDimitry Andric bool blockAlwaysFallThrough(BBInfo &BBI) const {
4000b57cec5SDimitry Andric return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric /// Used to sort if-conversion candidates.
IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> & C1,const std::unique_ptr<IfcvtToken> & C2)4040b57cec5SDimitry Andric static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
4050b57cec5SDimitry Andric const std::unique_ptr<IfcvtToken> &C2) {
4060b57cec5SDimitry Andric int Incr1 = (C1->Kind == ICDiamond)
4070b57cec5SDimitry Andric ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
4080b57cec5SDimitry Andric int Incr2 = (C2->Kind == ICDiamond)
4090b57cec5SDimitry Andric ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
4100b57cec5SDimitry Andric if (Incr1 > Incr2)
4110b57cec5SDimitry Andric return true;
4120b57cec5SDimitry Andric else if (Incr1 == Incr2) {
4130b57cec5SDimitry Andric // Favors subsumption.
4140b57cec5SDimitry Andric if (!C1->NeedSubsumption && C2->NeedSubsumption)
4150b57cec5SDimitry Andric return true;
4160b57cec5SDimitry Andric else if (C1->NeedSubsumption == C2->NeedSubsumption) {
4170b57cec5SDimitry Andric // Favors diamond over triangle, etc.
4180b57cec5SDimitry Andric if ((unsigned)C1->Kind < (unsigned)C2->Kind)
4190b57cec5SDimitry Andric return true;
4200b57cec5SDimitry Andric else if (C1->Kind == C2->Kind)
4210b57cec5SDimitry Andric return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
4220b57cec5SDimitry Andric }
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric return false;
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric };
4270b57cec5SDimitry Andric
4280b57cec5SDimitry Andric } // end anonymous namespace
4290b57cec5SDimitry Andric
4300b57cec5SDimitry Andric char IfConverter::ID = 0;
4310b57cec5SDimitry Andric
4320b57cec5SDimitry Andric char &llvm::IfConverterID = IfConverter::ID;
4330b57cec5SDimitry Andric
4340b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)4350b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
436480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
4370b57cec5SDimitry Andric INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
4380b57cec5SDimitry Andric
4390b57cec5SDimitry Andric bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
4400b57cec5SDimitry Andric if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
4410b57cec5SDimitry Andric return false;
4420b57cec5SDimitry Andric
4430b57cec5SDimitry Andric const TargetSubtargetInfo &ST = MF.getSubtarget();
4440b57cec5SDimitry Andric TLI = ST.getTargetLowering();
4450b57cec5SDimitry Andric TII = ST.getInstrInfo();
4460b57cec5SDimitry Andric TRI = ST.getRegisterInfo();
4475ffd83dbSDimitry Andric MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
4480b57cec5SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
449480093f4SDimitry Andric ProfileSummaryInfo *PSI =
450480093f4SDimitry Andric &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
4510b57cec5SDimitry Andric MRI = &MF.getRegInfo();
4520b57cec5SDimitry Andric SchedModel.init(&ST);
4530b57cec5SDimitry Andric
4540b57cec5SDimitry Andric if (!TII) return false;
4550b57cec5SDimitry Andric
4560b57cec5SDimitry Andric PreRegAlloc = MRI->isSSA();
4570b57cec5SDimitry Andric
4580b57cec5SDimitry Andric bool BFChange = false;
4590b57cec5SDimitry Andric if (!PreRegAlloc) {
4600b57cec5SDimitry Andric // Tail merge tend to expose more if-conversion opportunities.
461480093f4SDimitry Andric BranchFolder BF(true, false, MBFI, *MBPI, PSI);
4625ffd83dbSDimitry Andric BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo());
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
4660b57cec5SDimitry Andric << MF.getName() << "\'");
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
4690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " skipped\n");
4700b57cec5SDimitry Andric return false;
4710b57cec5SDimitry Andric }
4720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\n");
4730b57cec5SDimitry Andric
4740b57cec5SDimitry Andric MF.RenumberBlocks();
4750b57cec5SDimitry Andric BBAnalysis.resize(MF.getNumBlockIDs());
4760b57cec5SDimitry Andric
4770b57cec5SDimitry Andric std::vector<std::unique_ptr<IfcvtToken>> Tokens;
4780b57cec5SDimitry Andric MadeChange = false;
4790b57cec5SDimitry Andric unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
4800b57cec5SDimitry Andric NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
4810b57cec5SDimitry Andric while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
4820b57cec5SDimitry Andric // Do an initial analysis for each basic block and find all the potential
4830b57cec5SDimitry Andric // candidates to perform if-conversion.
4840b57cec5SDimitry Andric bool Change = false;
4850b57cec5SDimitry Andric AnalyzeBlocks(MF, Tokens);
4860b57cec5SDimitry Andric while (!Tokens.empty()) {
4870b57cec5SDimitry Andric std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
4880b57cec5SDimitry Andric Tokens.pop_back();
4890b57cec5SDimitry Andric BBInfo &BBI = Token->BBI;
4900b57cec5SDimitry Andric IfcvtKind Kind = Token->Kind;
4910b57cec5SDimitry Andric unsigned NumDups = Token->NumDups;
4920b57cec5SDimitry Andric unsigned NumDups2 = Token->NumDups2;
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric // If the block has been evicted out of the queue or it has already been
4950b57cec5SDimitry Andric // marked dead (due to it being predicated), then skip it.
4960b57cec5SDimitry Andric if (BBI.IsDone)
4970b57cec5SDimitry Andric BBI.IsEnqueued = false;
4980b57cec5SDimitry Andric if (!BBI.IsEnqueued)
4990b57cec5SDimitry Andric continue;
5000b57cec5SDimitry Andric
5010b57cec5SDimitry Andric BBI.IsEnqueued = false;
5020b57cec5SDimitry Andric
5030b57cec5SDimitry Andric bool RetVal = false;
5040b57cec5SDimitry Andric switch (Kind) {
5050b57cec5SDimitry Andric default: llvm_unreachable("Unexpected!");
5060b57cec5SDimitry Andric case ICSimple:
5070b57cec5SDimitry Andric case ICSimpleFalse: {
5080b57cec5SDimitry Andric bool isFalse = Kind == ICSimpleFalse;
5090b57cec5SDimitry Andric if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
5100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
5110b57cec5SDimitry Andric << (Kind == ICSimpleFalse ? " false" : "")
5120b57cec5SDimitry Andric << "): " << printMBBReference(*BBI.BB) << " ("
5130b57cec5SDimitry Andric << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
5140b57cec5SDimitry Andric : BBI.TrueBB->getNumber())
5150b57cec5SDimitry Andric << ") ");
5160b57cec5SDimitry Andric RetVal = IfConvertSimple(BBI, Kind);
5170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5180b57cec5SDimitry Andric if (RetVal) {
5190b57cec5SDimitry Andric if (isFalse) ++NumSimpleFalse;
5200b57cec5SDimitry Andric else ++NumSimple;
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric break;
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric case ICTriangle:
5250b57cec5SDimitry Andric case ICTriangleRev:
5260b57cec5SDimitry Andric case ICTriangleFalse:
5270b57cec5SDimitry Andric case ICTriangleFRev: {
5280b57cec5SDimitry Andric bool isFalse = Kind == ICTriangleFalse;
5290b57cec5SDimitry Andric bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
5300b57cec5SDimitry Andric if (DisableTriangle && !isFalse && !isRev) break;
5310b57cec5SDimitry Andric if (DisableTriangleR && !isFalse && isRev) break;
5320b57cec5SDimitry Andric if (DisableTriangleF && isFalse && !isRev) break;
5330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
5340b57cec5SDimitry Andric if (isFalse)
5350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " false");
5360b57cec5SDimitry Andric if (isRev)
5370b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " rev");
5380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
5390b57cec5SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
5400b57cec5SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
5410b57cec5SDimitry Andric RetVal = IfConvertTriangle(BBI, Kind);
5420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5430b57cec5SDimitry Andric if (RetVal) {
544*c9157d92SDimitry Andric if (isFalse)
545*c9157d92SDimitry Andric ++NumTriangleFalse;
546*c9157d92SDimitry Andric else if (isRev)
547*c9157d92SDimitry Andric ++NumTriangleRev;
548*c9157d92SDimitry Andric else
549*c9157d92SDimitry Andric ++NumTriangle;
5500b57cec5SDimitry Andric }
5510b57cec5SDimitry Andric break;
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric case ICDiamond:
5540b57cec5SDimitry Andric if (DisableDiamond) break;
5550b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
5560b57cec5SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
5570b57cec5SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
5580b57cec5SDimitry Andric RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
5590b57cec5SDimitry Andric Token->TClobbersPred,
5600b57cec5SDimitry Andric Token->FClobbersPred);
5610b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5620b57cec5SDimitry Andric if (RetVal) ++NumDiamonds;
5630b57cec5SDimitry Andric break;
5640b57cec5SDimitry Andric case ICForkedDiamond:
5650b57cec5SDimitry Andric if (DisableForkedDiamond) break;
5660b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
5670b57cec5SDimitry Andric << printMBBReference(*BBI.BB)
5680b57cec5SDimitry Andric << " (T:" << BBI.TrueBB->getNumber()
5690b57cec5SDimitry Andric << ",F:" << BBI.FalseBB->getNumber() << ") ");
5700b57cec5SDimitry Andric RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
5710b57cec5SDimitry Andric Token->TClobbersPred,
5720b57cec5SDimitry Andric Token->FClobbersPred);
5730b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
5740b57cec5SDimitry Andric if (RetVal) ++NumForkedDiamonds;
5750b57cec5SDimitry Andric break;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric
5780b57cec5SDimitry Andric if (RetVal && MRI->tracksLiveness())
5790b57cec5SDimitry Andric recomputeLivenessFlags(*BBI.BB);
5800b57cec5SDimitry Andric
5810b57cec5SDimitry Andric Change |= RetVal;
5820b57cec5SDimitry Andric
5830b57cec5SDimitry Andric NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
5840b57cec5SDimitry Andric NumTriangleFalse + NumTriangleFRev + NumDiamonds;
5850b57cec5SDimitry Andric if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
5860b57cec5SDimitry Andric break;
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric
5890b57cec5SDimitry Andric if (!Change)
5900b57cec5SDimitry Andric break;
5910b57cec5SDimitry Andric MadeChange |= Change;
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric
5940b57cec5SDimitry Andric Tokens.clear();
5950b57cec5SDimitry Andric BBAnalysis.clear();
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric if (MadeChange && IfCvtBranchFold) {
598480093f4SDimitry Andric BranchFolder BF(false, false, MBFI, *MBPI, PSI);
5995ffd83dbSDimitry Andric BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo());
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric
6020b57cec5SDimitry Andric MadeChange |= BFChange;
6030b57cec5SDimitry Andric return MadeChange;
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric
6060b57cec5SDimitry Andric /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
findFalseBlock(MachineBasicBlock * BB,MachineBasicBlock * TrueBB)6070b57cec5SDimitry Andric static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
6080b57cec5SDimitry Andric MachineBasicBlock *TrueBB) {
6090b57cec5SDimitry Andric for (MachineBasicBlock *SuccBB : BB->successors()) {
6100b57cec5SDimitry Andric if (SuccBB != TrueBB)
6110b57cec5SDimitry Andric return SuccBB;
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric return nullptr;
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric
6160b57cec5SDimitry Andric /// Reverse the condition of the end of the block branch. Swap block's 'true'
6170b57cec5SDimitry Andric /// and 'false' successors.
reverseBranchCondition(BBInfo & BBI) const6180b57cec5SDimitry Andric bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
6190b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere
6200b57cec5SDimitry Andric if (!TII->reverseBranchCondition(BBI.BrCond)) {
6210b57cec5SDimitry Andric TII->removeBranch(*BBI.BB);
6220b57cec5SDimitry Andric TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
6230b57cec5SDimitry Andric std::swap(BBI.TrueBB, BBI.FalseBB);
6240b57cec5SDimitry Andric return true;
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric return false;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric
6290b57cec5SDimitry Andric /// Returns the next block in the function blocks ordering. If it is the end,
6300b57cec5SDimitry Andric /// returns NULL.
getNextBlock(MachineBasicBlock & MBB)6310b57cec5SDimitry Andric static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
6320b57cec5SDimitry Andric MachineFunction::iterator I = MBB.getIterator();
6330b57cec5SDimitry Andric MachineFunction::iterator E = MBB.getParent()->end();
6340b57cec5SDimitry Andric if (++I == E)
6350b57cec5SDimitry Andric return nullptr;
6360b57cec5SDimitry Andric return &*I;
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric
6390b57cec5SDimitry Andric /// Returns true if the 'true' block (along with its predecessor) forms a valid
6400b57cec5SDimitry Andric /// simple shape for ifcvt. It also returns the number of instructions that the
6410b57cec5SDimitry Andric /// ifcvt would need to duplicate if performed in Dups.
ValidSimple(BBInfo & TrueBBI,unsigned & Dups,BranchProbability Prediction) const6420b57cec5SDimitry Andric bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
6430b57cec5SDimitry Andric BranchProbability Prediction) const {
6440b57cec5SDimitry Andric Dups = 0;
6450b57cec5SDimitry Andric if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
6460b57cec5SDimitry Andric return false;
6470b57cec5SDimitry Andric
6480b57cec5SDimitry Andric if (TrueBBI.IsBrAnalyzable)
6490b57cec5SDimitry Andric return false;
6500b57cec5SDimitry Andric
6510b57cec5SDimitry Andric if (TrueBBI.BB->pred_size() > 1) {
6520b57cec5SDimitry Andric if (TrueBBI.CannotBeCopied ||
6530b57cec5SDimitry Andric !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
6540b57cec5SDimitry Andric Prediction))
6550b57cec5SDimitry Andric return false;
6560b57cec5SDimitry Andric Dups = TrueBBI.NonPredSize;
6570b57cec5SDimitry Andric }
6580b57cec5SDimitry Andric
6590b57cec5SDimitry Andric return true;
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric
6620b57cec5SDimitry Andric /// Returns true if the 'true' and 'false' blocks (along with their common
6630b57cec5SDimitry Andric /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
6640b57cec5SDimitry Andric /// true, it checks if 'true' block's false branch branches to the 'false' block
6650b57cec5SDimitry Andric /// rather than the other way around. It also returns the number of instructions
6660b57cec5SDimitry Andric /// that the ifcvt would need to duplicate if performed in 'Dups'.
ValidTriangle(BBInfo & TrueBBI,BBInfo & FalseBBI,bool FalseBranch,unsigned & Dups,BranchProbability Prediction) const6670b57cec5SDimitry Andric bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
6680b57cec5SDimitry Andric bool FalseBranch, unsigned &Dups,
6690b57cec5SDimitry Andric BranchProbability Prediction) const {
6700b57cec5SDimitry Andric Dups = 0;
6718bcb0991SDimitry Andric if (TrueBBI.BB == FalseBBI.BB)
6728bcb0991SDimitry Andric return false;
6738bcb0991SDimitry Andric
6740b57cec5SDimitry Andric if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
6750b57cec5SDimitry Andric return false;
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric if (TrueBBI.BB->pred_size() > 1) {
6780b57cec5SDimitry Andric if (TrueBBI.CannotBeCopied)
6790b57cec5SDimitry Andric return false;
6800b57cec5SDimitry Andric
6810b57cec5SDimitry Andric unsigned Size = TrueBBI.NonPredSize;
6820b57cec5SDimitry Andric if (TrueBBI.IsBrAnalyzable) {
6830b57cec5SDimitry Andric if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
6840b57cec5SDimitry Andric // Ends with an unconditional branch. It will be removed.
6850b57cec5SDimitry Andric --Size;
6860b57cec5SDimitry Andric else {
6870b57cec5SDimitry Andric MachineBasicBlock *FExit = FalseBranch
6880b57cec5SDimitry Andric ? TrueBBI.TrueBB : TrueBBI.FalseBB;
6890b57cec5SDimitry Andric if (FExit)
6900b57cec5SDimitry Andric // Require a conditional branch
6910b57cec5SDimitry Andric ++Size;
6920b57cec5SDimitry Andric }
6930b57cec5SDimitry Andric }
6940b57cec5SDimitry Andric if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
6950b57cec5SDimitry Andric return false;
6960b57cec5SDimitry Andric Dups = Size;
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric
6990b57cec5SDimitry Andric MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
7000b57cec5SDimitry Andric if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
7010b57cec5SDimitry Andric MachineFunction::iterator I = TrueBBI.BB->getIterator();
7020b57cec5SDimitry Andric if (++I == TrueBBI.BB->getParent()->end())
7030b57cec5SDimitry Andric return false;
7040b57cec5SDimitry Andric TExit = &*I;
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric return TExit && TExit == FalseBBI.BB;
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric
7090b57cec5SDimitry Andric /// Count duplicated instructions and move the iterators to show where they
7100b57cec5SDimitry Andric /// are.
7110b57cec5SDimitry Andric /// @param TIB True Iterator Begin
7120b57cec5SDimitry Andric /// @param FIB False Iterator Begin
7130b57cec5SDimitry Andric /// These two iterators initially point to the first instruction of the two
7140b57cec5SDimitry Andric /// blocks, and finally point to the first non-shared instruction.
7150b57cec5SDimitry Andric /// @param TIE True Iterator End
7160b57cec5SDimitry Andric /// @param FIE False Iterator End
7170b57cec5SDimitry Andric /// These two iterators initially point to End() for the two blocks() and
7180b57cec5SDimitry Andric /// finally point to the first shared instruction in the tail.
7190b57cec5SDimitry Andric /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
7200b57cec5SDimitry Andric /// two blocks.
7210b57cec5SDimitry Andric /// @param Dups1 count of duplicated instructions at the beginning of the 2
7220b57cec5SDimitry Andric /// blocks.
7230b57cec5SDimitry Andric /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
7240b57cec5SDimitry Andric /// @param SkipUnconditionalBranches if true, Don't make sure that
7250b57cec5SDimitry Andric /// unconditional branches at the end of the blocks are the same. True is
7260b57cec5SDimitry Andric /// passed when the blocks are analyzable to allow for fallthrough to be
7270b57cec5SDimitry Andric /// handled.
7280b57cec5SDimitry Andric /// @return false if the shared portion prevents if conversion.
CountDuplicatedInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,unsigned & Dups1,unsigned & Dups2,MachineBasicBlock & TBB,MachineBasicBlock & FBB,bool SkipUnconditionalBranches) const7290b57cec5SDimitry Andric bool IfConverter::CountDuplicatedInstructions(
7300b57cec5SDimitry Andric MachineBasicBlock::iterator &TIB,
7310b57cec5SDimitry Andric MachineBasicBlock::iterator &FIB,
7320b57cec5SDimitry Andric MachineBasicBlock::iterator &TIE,
7330b57cec5SDimitry Andric MachineBasicBlock::iterator &FIE,
7340b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
7350b57cec5SDimitry Andric MachineBasicBlock &TBB, MachineBasicBlock &FBB,
7360b57cec5SDimitry Andric bool SkipUnconditionalBranches) const {
7370b57cec5SDimitry Andric while (TIB != TIE && FIB != FIE) {
7380b57cec5SDimitry Andric // Skip dbg_value instructions. These do not count.
739fe6060f1SDimitry Andric TIB = skipDebugInstructionsForward(TIB, TIE, false);
740fe6060f1SDimitry Andric FIB = skipDebugInstructionsForward(FIB, FIE, false);
7410b57cec5SDimitry Andric if (TIB == TIE || FIB == FIE)
7420b57cec5SDimitry Andric break;
7430b57cec5SDimitry Andric if (!TIB->isIdenticalTo(*FIB))
7440b57cec5SDimitry Andric break;
7450b57cec5SDimitry Andric // A pred-clobbering instruction in the shared portion prevents
7460b57cec5SDimitry Andric // if-conversion.
7470b57cec5SDimitry Andric std::vector<MachineOperand> PredDefs;
748e8d8bef9SDimitry Andric if (TII->ClobbersPredicate(*TIB, PredDefs, false))
7490b57cec5SDimitry Andric return false;
7500b57cec5SDimitry Andric // If we get all the way to the branch instructions, don't count them.
7510b57cec5SDimitry Andric if (!TIB->isBranch())
7520b57cec5SDimitry Andric ++Dups1;
7530b57cec5SDimitry Andric ++TIB;
7540b57cec5SDimitry Andric ++FIB;
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric
7570b57cec5SDimitry Andric // Check for already containing all of the block.
7580b57cec5SDimitry Andric if (TIB == TIE || FIB == FIE)
7590b57cec5SDimitry Andric return true;
7600b57cec5SDimitry Andric // Now, in preparation for counting duplicate instructions at the ends of the
7610b57cec5SDimitry Andric // blocks, switch to reverse_iterators. Note that getReverse() returns an
7620b57cec5SDimitry Andric // iterator that points to the same instruction, unlike std::reverse_iterator.
7630b57cec5SDimitry Andric // We have to do our own shifting so that we get the same range.
7640b57cec5SDimitry Andric MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
7650b57cec5SDimitry Andric MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
7660b57cec5SDimitry Andric const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
7670b57cec5SDimitry Andric const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
7680b57cec5SDimitry Andric
7690b57cec5SDimitry Andric if (!TBB.succ_empty() || !FBB.succ_empty()) {
7700b57cec5SDimitry Andric if (SkipUnconditionalBranches) {
7710b57cec5SDimitry Andric while (RTIE != RTIB && RTIE->isUnconditionalBranch())
7720b57cec5SDimitry Andric ++RTIE;
7730b57cec5SDimitry Andric while (RFIE != RFIB && RFIE->isUnconditionalBranch())
7740b57cec5SDimitry Andric ++RFIE;
7750b57cec5SDimitry Andric }
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric
7780b57cec5SDimitry Andric // Count duplicate instructions at the ends of the blocks.
7790b57cec5SDimitry Andric while (RTIE != RTIB && RFIE != RFIB) {
7800b57cec5SDimitry Andric // Skip dbg_value instructions. These do not count.
7810b57cec5SDimitry Andric // Note that these are reverse iterators going forward.
782fe6060f1SDimitry Andric RTIE = skipDebugInstructionsForward(RTIE, RTIB, false);
783fe6060f1SDimitry Andric RFIE = skipDebugInstructionsForward(RFIE, RFIB, false);
7840b57cec5SDimitry Andric if (RTIE == RTIB || RFIE == RFIB)
7850b57cec5SDimitry Andric break;
7860b57cec5SDimitry Andric if (!RTIE->isIdenticalTo(*RFIE))
7870b57cec5SDimitry Andric break;
7880b57cec5SDimitry Andric // We have to verify that any branch instructions are the same, and then we
7890b57cec5SDimitry Andric // don't count them toward the # of duplicate instructions.
7900b57cec5SDimitry Andric if (!RTIE->isBranch())
7910b57cec5SDimitry Andric ++Dups2;
7920b57cec5SDimitry Andric ++RTIE;
7930b57cec5SDimitry Andric ++RFIE;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric TIE = std::next(RTIE.getReverse());
7960b57cec5SDimitry Andric FIE = std::next(RFIE.getReverse());
7970b57cec5SDimitry Andric return true;
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric
8000b57cec5SDimitry Andric /// RescanInstructions - Run ScanInstructions on a pair of blocks.
8010b57cec5SDimitry Andric /// @param TIB - True Iterator Begin, points to first non-shared instruction
8020b57cec5SDimitry Andric /// @param FIB - False Iterator Begin, points to first non-shared instruction
8030b57cec5SDimitry Andric /// @param TIE - True Iterator End, points past last non-shared instruction
8040b57cec5SDimitry Andric /// @param FIE - False Iterator End, points past last non-shared instruction
8050b57cec5SDimitry Andric /// @param TrueBBI - BBInfo to update for the true block.
8060b57cec5SDimitry Andric /// @param FalseBBI - BBInfo to update for the false block.
8070b57cec5SDimitry Andric /// @returns - false if either block cannot be predicated or if both blocks end
8080b57cec5SDimitry Andric /// with a predicate-clobbering instruction.
RescanInstructions(MachineBasicBlock::iterator & TIB,MachineBasicBlock::iterator & FIB,MachineBasicBlock::iterator & TIE,MachineBasicBlock::iterator & FIE,BBInfo & TrueBBI,BBInfo & FalseBBI) const8090b57cec5SDimitry Andric bool IfConverter::RescanInstructions(
8100b57cec5SDimitry Andric MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
8110b57cec5SDimitry Andric MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
8120b57cec5SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI) const {
8130b57cec5SDimitry Andric bool BranchUnpredicable = true;
8140b57cec5SDimitry Andric TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
8150b57cec5SDimitry Andric ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
8160b57cec5SDimitry Andric if (TrueBBI.IsUnpredicable)
8170b57cec5SDimitry Andric return false;
8180b57cec5SDimitry Andric ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
8190b57cec5SDimitry Andric if (FalseBBI.IsUnpredicable)
8200b57cec5SDimitry Andric return false;
8210b57cec5SDimitry Andric if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
8220b57cec5SDimitry Andric return false;
8230b57cec5SDimitry Andric return true;
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric
8260b57cec5SDimitry Andric #ifndef NDEBUG
verifySameBranchInstructions(MachineBasicBlock * MBB1,MachineBasicBlock * MBB2)8270b57cec5SDimitry Andric static void verifySameBranchInstructions(
8280b57cec5SDimitry Andric MachineBasicBlock *MBB1,
8290b57cec5SDimitry Andric MachineBasicBlock *MBB2) {
8300b57cec5SDimitry Andric const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
8310b57cec5SDimitry Andric const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
8320b57cec5SDimitry Andric MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
8330b57cec5SDimitry Andric MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
8340b57cec5SDimitry Andric while (E1 != B1 && E2 != B2) {
835fe6060f1SDimitry Andric skipDebugInstructionsForward(E1, B1, false);
836fe6060f1SDimitry Andric skipDebugInstructionsForward(E2, B2, false);
8370b57cec5SDimitry Andric if (E1 == B1 && E2 == B2)
8380b57cec5SDimitry Andric break;
8390b57cec5SDimitry Andric
8400b57cec5SDimitry Andric if (E1 == B1) {
8410b57cec5SDimitry Andric assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
8420b57cec5SDimitry Andric break;
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric if (E2 == B2) {
8450b57cec5SDimitry Andric assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
8460b57cec5SDimitry Andric break;
8470b57cec5SDimitry Andric }
8480b57cec5SDimitry Andric
8490b57cec5SDimitry Andric if (E1->isBranch() || E2->isBranch())
8500b57cec5SDimitry Andric assert(E1->isIdenticalTo(*E2) &&
8510b57cec5SDimitry Andric "Branch mis-match, branch instructions don't match.");
8520b57cec5SDimitry Andric else
8530b57cec5SDimitry Andric break;
8540b57cec5SDimitry Andric ++E1;
8550b57cec5SDimitry Andric ++E2;
8560b57cec5SDimitry Andric }
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric #endif
8590b57cec5SDimitry Andric
8600b57cec5SDimitry Andric /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
8610b57cec5SDimitry Andric /// with their common predecessor) form a diamond if a common tail block is
8620b57cec5SDimitry Andric /// extracted.
8630b57cec5SDimitry Andric /// While not strictly a diamond, this pattern would form a diamond if
8640b57cec5SDimitry Andric /// tail-merging had merged the shared tails.
8650b57cec5SDimitry Andric /// EBB
8660b57cec5SDimitry Andric /// _/ \_
8670b57cec5SDimitry Andric /// | |
8680b57cec5SDimitry Andric /// TBB FBB
8690b57cec5SDimitry Andric /// / \ / \
8700b57cec5SDimitry Andric /// FalseBB TrueBB FalseBB
8710b57cec5SDimitry Andric /// Currently only handles analyzable branches.
8720b57cec5SDimitry Andric /// Specifically excludes actual diamonds to avoid overlap.
ValidForkedDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const8730b57cec5SDimitry Andric bool IfConverter::ValidForkedDiamond(
8740b57cec5SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI,
8750b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
8760b57cec5SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
8770b57cec5SDimitry Andric Dups1 = Dups2 = 0;
8780b57cec5SDimitry Andric if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
8790b57cec5SDimitry Andric FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
8800b57cec5SDimitry Andric return false;
8810b57cec5SDimitry Andric
8820b57cec5SDimitry Andric if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
8830b57cec5SDimitry Andric return false;
8840b57cec5SDimitry Andric // Don't IfConvert blocks that can't be folded into their predecessor.
8850b57cec5SDimitry Andric if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
8860b57cec5SDimitry Andric return false;
8870b57cec5SDimitry Andric
8880b57cec5SDimitry Andric // This function is specifically looking for conditional tails, as
8890b57cec5SDimitry Andric // unconditional tails are already handled by the standard diamond case.
8900b57cec5SDimitry Andric if (TrueBBI.BrCond.size() == 0 ||
8910b57cec5SDimitry Andric FalseBBI.BrCond.size() == 0)
8920b57cec5SDimitry Andric return false;
8930b57cec5SDimitry Andric
8940b57cec5SDimitry Andric MachineBasicBlock *TT = TrueBBI.TrueBB;
8950b57cec5SDimitry Andric MachineBasicBlock *TF = TrueBBI.FalseBB;
8960b57cec5SDimitry Andric MachineBasicBlock *FT = FalseBBI.TrueBB;
8970b57cec5SDimitry Andric MachineBasicBlock *FF = FalseBBI.FalseBB;
8980b57cec5SDimitry Andric
8990b57cec5SDimitry Andric if (!TT)
9000b57cec5SDimitry Andric TT = getNextBlock(*TrueBBI.BB);
9010b57cec5SDimitry Andric if (!TF)
9020b57cec5SDimitry Andric TF = getNextBlock(*TrueBBI.BB);
9030b57cec5SDimitry Andric if (!FT)
9040b57cec5SDimitry Andric FT = getNextBlock(*FalseBBI.BB);
9050b57cec5SDimitry Andric if (!FF)
9060b57cec5SDimitry Andric FF = getNextBlock(*FalseBBI.BB);
9070b57cec5SDimitry Andric
9080b57cec5SDimitry Andric if (!TT || !TF)
9090b57cec5SDimitry Andric return false;
9100b57cec5SDimitry Andric
9110b57cec5SDimitry Andric // Check successors. If they don't match, bail.
9120b57cec5SDimitry Andric if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
9130b57cec5SDimitry Andric return false;
9140b57cec5SDimitry Andric
9150b57cec5SDimitry Andric bool FalseReversed = false;
9160b57cec5SDimitry Andric if (TF == FT && TT == FF) {
9170b57cec5SDimitry Andric // If the branches are opposing, but we can't reverse, don't do it.
9180b57cec5SDimitry Andric if (!FalseBBI.IsBrReversible)
9190b57cec5SDimitry Andric return false;
9200b57cec5SDimitry Andric FalseReversed = true;
9210b57cec5SDimitry Andric reverseBranchCondition(FalseBBI);
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric auto UnReverseOnExit = make_scope_exit([&]() {
9240b57cec5SDimitry Andric if (FalseReversed)
9250b57cec5SDimitry Andric reverseBranchCondition(FalseBBI);
9260b57cec5SDimitry Andric });
9270b57cec5SDimitry Andric
9280b57cec5SDimitry Andric // Count duplicate instructions at the beginning of the true and false blocks.
9290b57cec5SDimitry Andric MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
9300b57cec5SDimitry Andric MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
9310b57cec5SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
9320b57cec5SDimitry Andric MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
9330b57cec5SDimitry Andric if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
9340b57cec5SDimitry Andric *TrueBBI.BB, *FalseBBI.BB,
9350b57cec5SDimitry Andric /* SkipUnconditionalBranches */ true))
9360b57cec5SDimitry Andric return false;
9370b57cec5SDimitry Andric
9380b57cec5SDimitry Andric TrueBBICalc.BB = TrueBBI.BB;
9390b57cec5SDimitry Andric FalseBBICalc.BB = FalseBBI.BB;
9408bcb0991SDimitry Andric TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
9418bcb0991SDimitry Andric FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
9420b57cec5SDimitry Andric if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
9430b57cec5SDimitry Andric return false;
9440b57cec5SDimitry Andric
9450b57cec5SDimitry Andric // The size is used to decide whether to if-convert, and the shared portions
9460b57cec5SDimitry Andric // are subtracted off. Because of the subtraction, we just use the size that
9470b57cec5SDimitry Andric // was calculated by the original ScanInstructions, as it is correct.
9480b57cec5SDimitry Andric TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
9490b57cec5SDimitry Andric FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
9500b57cec5SDimitry Andric return true;
9510b57cec5SDimitry Andric }
9520b57cec5SDimitry Andric
9530b57cec5SDimitry Andric /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
9540b57cec5SDimitry Andric /// with their common predecessor) forms a valid diamond shape for ifcvt.
ValidDiamond(BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned & Dups1,unsigned & Dups2,BBInfo & TrueBBICalc,BBInfo & FalseBBICalc) const9550b57cec5SDimitry Andric bool IfConverter::ValidDiamond(
9560b57cec5SDimitry Andric BBInfo &TrueBBI, BBInfo &FalseBBI,
9570b57cec5SDimitry Andric unsigned &Dups1, unsigned &Dups2,
9580b57cec5SDimitry Andric BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
9590b57cec5SDimitry Andric Dups1 = Dups2 = 0;
9600b57cec5SDimitry Andric if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
9610b57cec5SDimitry Andric FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
9620b57cec5SDimitry Andric return false;
9630b57cec5SDimitry Andric
9645ffd83dbSDimitry Andric // If the True and False BBs are equal we're dealing with a degenerate case
9655ffd83dbSDimitry Andric // that we don't treat as a diamond.
9665ffd83dbSDimitry Andric if (TrueBBI.BB == FalseBBI.BB)
9675ffd83dbSDimitry Andric return false;
9685ffd83dbSDimitry Andric
9690b57cec5SDimitry Andric MachineBasicBlock *TT = TrueBBI.TrueBB;
9700b57cec5SDimitry Andric MachineBasicBlock *FT = FalseBBI.TrueBB;
9710b57cec5SDimitry Andric
9720b57cec5SDimitry Andric if (!TT && blockAlwaysFallThrough(TrueBBI))
9730b57cec5SDimitry Andric TT = getNextBlock(*TrueBBI.BB);
9740b57cec5SDimitry Andric if (!FT && blockAlwaysFallThrough(FalseBBI))
9750b57cec5SDimitry Andric FT = getNextBlock(*FalseBBI.BB);
9760b57cec5SDimitry Andric if (TT != FT)
9770b57cec5SDimitry Andric return false;
9780b57cec5SDimitry Andric if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
9790b57cec5SDimitry Andric return false;
9800b57cec5SDimitry Andric if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
9810b57cec5SDimitry Andric return false;
9820b57cec5SDimitry Andric
9830b57cec5SDimitry Andric // FIXME: Allow true block to have an early exit?
9840b57cec5SDimitry Andric if (TrueBBI.FalseBB || FalseBBI.FalseBB)
9850b57cec5SDimitry Andric return false;
9860b57cec5SDimitry Andric
9870b57cec5SDimitry Andric // Count duplicate instructions at the beginning and end of the true and
9880b57cec5SDimitry Andric // false blocks.
9890b57cec5SDimitry Andric // Skip unconditional branches only if we are considering an analyzable
9900b57cec5SDimitry Andric // diamond. Otherwise the branches must be the same.
9910b57cec5SDimitry Andric bool SkipUnconditionalBranches =
9920b57cec5SDimitry Andric TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
9930b57cec5SDimitry Andric MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
9940b57cec5SDimitry Andric MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
9950b57cec5SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
9960b57cec5SDimitry Andric MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
9970b57cec5SDimitry Andric if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
9980b57cec5SDimitry Andric *TrueBBI.BB, *FalseBBI.BB,
9990b57cec5SDimitry Andric SkipUnconditionalBranches))
10000b57cec5SDimitry Andric return false;
10010b57cec5SDimitry Andric
10020b57cec5SDimitry Andric TrueBBICalc.BB = TrueBBI.BB;
10030b57cec5SDimitry Andric FalseBBICalc.BB = FalseBBI.BB;
10048bcb0991SDimitry Andric TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
10058bcb0991SDimitry Andric FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
10060b57cec5SDimitry Andric if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
10070b57cec5SDimitry Andric return false;
10080b57cec5SDimitry Andric // The size is used to decide whether to if-convert, and the shared portions
10090b57cec5SDimitry Andric // are subtracted off. Because of the subtraction, we just use the size that
10100b57cec5SDimitry Andric // was calculated by the original ScanInstructions, as it is correct.
10110b57cec5SDimitry Andric TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
10120b57cec5SDimitry Andric FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
10130b57cec5SDimitry Andric return true;
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric
10160b57cec5SDimitry Andric /// AnalyzeBranches - Look at the branches at the end of a block to determine if
10170b57cec5SDimitry Andric /// the block is predicable.
AnalyzeBranches(BBInfo & BBI)10180b57cec5SDimitry Andric void IfConverter::AnalyzeBranches(BBInfo &BBI) {
10190b57cec5SDimitry Andric if (BBI.IsDone)
10200b57cec5SDimitry Andric return;
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric BBI.TrueBB = BBI.FalseBB = nullptr;
10230b57cec5SDimitry Andric BBI.BrCond.clear();
10240b57cec5SDimitry Andric BBI.IsBrAnalyzable =
10250b57cec5SDimitry Andric !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
10260b57cec5SDimitry Andric if (!BBI.IsBrAnalyzable) {
10270b57cec5SDimitry Andric BBI.TrueBB = nullptr;
10280b57cec5SDimitry Andric BBI.FalseBB = nullptr;
10290b57cec5SDimitry Andric BBI.BrCond.clear();
10300b57cec5SDimitry Andric }
10310b57cec5SDimitry Andric
10320b57cec5SDimitry Andric SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
10330b57cec5SDimitry Andric BBI.IsBrReversible = (RevCond.size() == 0) ||
10340b57cec5SDimitry Andric !TII->reverseBranchCondition(RevCond);
10350b57cec5SDimitry Andric BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
10360b57cec5SDimitry Andric
10370b57cec5SDimitry Andric if (BBI.BrCond.size()) {
10380b57cec5SDimitry Andric // No false branch. This BB must end with a conditional branch and a
10390b57cec5SDimitry Andric // fallthrough.
10400b57cec5SDimitry Andric if (!BBI.FalseBB)
10410b57cec5SDimitry Andric BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
10420b57cec5SDimitry Andric if (!BBI.FalseBB) {
10430b57cec5SDimitry Andric // Malformed bcc? True and false blocks are the same?
10440b57cec5SDimitry Andric BBI.IsUnpredicable = true;
10450b57cec5SDimitry Andric }
10460b57cec5SDimitry Andric }
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric
10490b57cec5SDimitry Andric /// ScanInstructions - Scan all the instructions in the block to determine if
10500b57cec5SDimitry Andric /// the block is predicable. In most cases, that means all the instructions
10510b57cec5SDimitry Andric /// in the block are isPredicable(). Also checks if the block contains any
10520b57cec5SDimitry Andric /// instruction which can clobber a predicate (e.g. condition code register).
10530b57cec5SDimitry Andric /// If so, the block is not predicable unless it's the last instruction.
ScanInstructions(BBInfo & BBI,MachineBasicBlock::iterator & Begin,MachineBasicBlock::iterator & End,bool BranchUnpredicable) const10540b57cec5SDimitry Andric void IfConverter::ScanInstructions(BBInfo &BBI,
10550b57cec5SDimitry Andric MachineBasicBlock::iterator &Begin,
10560b57cec5SDimitry Andric MachineBasicBlock::iterator &End,
10570b57cec5SDimitry Andric bool BranchUnpredicable) const {
10580b57cec5SDimitry Andric if (BBI.IsDone || BBI.IsUnpredicable)
10590b57cec5SDimitry Andric return;
10600b57cec5SDimitry Andric
10610b57cec5SDimitry Andric bool AlreadyPredicated = !BBI.Predicate.empty();
10620b57cec5SDimitry Andric
10630b57cec5SDimitry Andric BBI.NonPredSize = 0;
10640b57cec5SDimitry Andric BBI.ExtraCost = 0;
10650b57cec5SDimitry Andric BBI.ExtraCost2 = 0;
10660b57cec5SDimitry Andric BBI.ClobbersPred = false;
10670b57cec5SDimitry Andric for (MachineInstr &MI : make_range(Begin, End)) {
10680b57cec5SDimitry Andric if (MI.isDebugInstr())
10690b57cec5SDimitry Andric continue;
10700b57cec5SDimitry Andric
10710b57cec5SDimitry Andric // It's unsafe to duplicate convergent instructions in this context, so set
10720b57cec5SDimitry Andric // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
10730b57cec5SDimitry Andric // following CFG, which is subject to our "simple" transformation.
10740b57cec5SDimitry Andric //
10750b57cec5SDimitry Andric // BB0 // if (c1) goto BB1; else goto BB2;
10760b57cec5SDimitry Andric // / \
10770b57cec5SDimitry Andric // BB1 |
10780b57cec5SDimitry Andric // | BB2 // if (c2) goto TBB; else goto FBB;
10790b57cec5SDimitry Andric // | / |
10800b57cec5SDimitry Andric // | / |
10810b57cec5SDimitry Andric // TBB |
10820b57cec5SDimitry Andric // | |
10830b57cec5SDimitry Andric // | FBB
10840b57cec5SDimitry Andric // |
10850b57cec5SDimitry Andric // exit
10860b57cec5SDimitry Andric //
10870b57cec5SDimitry Andric // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
10880b57cec5SDimitry Andric // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
10890b57cec5SDimitry Andric // TBB contains a convergent instruction. This is safe iff doing so does
10900b57cec5SDimitry Andric // not add a control-flow dependency to the convergent instruction -- i.e.,
10910b57cec5SDimitry Andric // it's safe iff the set of control flows that leads us to the convergent
10920b57cec5SDimitry Andric // instruction does not get smaller after the transformation.
10930b57cec5SDimitry Andric //
10940b57cec5SDimitry Andric // Originally we executed TBB if c1 || c2. After the transformation, there
10950b57cec5SDimitry Andric // are two copies of TBB's instructions. We get to the first if c1, and we
10960b57cec5SDimitry Andric // get to the second if !c1 && c2.
10970b57cec5SDimitry Andric //
10980b57cec5SDimitry Andric // There are clearly fewer ways to satisfy the condition "c1" than
10990b57cec5SDimitry Andric // "c1 || c2". Since we've shrunk the set of control flows which lead to
11000b57cec5SDimitry Andric // our convergent instruction, the transformation is unsafe.
11010b57cec5SDimitry Andric if (MI.isNotDuplicable() || MI.isConvergent())
11020b57cec5SDimitry Andric BBI.CannotBeCopied = true;
11030b57cec5SDimitry Andric
11040b57cec5SDimitry Andric bool isPredicated = TII->isPredicated(MI);
11050b57cec5SDimitry Andric bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
11060b57cec5SDimitry Andric
11070b57cec5SDimitry Andric if (BranchUnpredicable && MI.isBranch()) {
11080b57cec5SDimitry Andric BBI.IsUnpredicable = true;
11090b57cec5SDimitry Andric return;
11100b57cec5SDimitry Andric }
11110b57cec5SDimitry Andric
11120b57cec5SDimitry Andric // A conditional branch is not predicable, but it may be eliminated.
11130b57cec5SDimitry Andric if (isCondBr)
11140b57cec5SDimitry Andric continue;
11150b57cec5SDimitry Andric
11160b57cec5SDimitry Andric if (!isPredicated) {
11170b57cec5SDimitry Andric BBI.NonPredSize++;
11180b57cec5SDimitry Andric unsigned ExtraPredCost = TII->getPredicationCost(MI);
11190b57cec5SDimitry Andric unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
11200b57cec5SDimitry Andric if (NumCycles > 1)
11210b57cec5SDimitry Andric BBI.ExtraCost += NumCycles-1;
11220b57cec5SDimitry Andric BBI.ExtraCost2 += ExtraPredCost;
11230b57cec5SDimitry Andric } else if (!AlreadyPredicated) {
11240b57cec5SDimitry Andric // FIXME: This instruction is already predicated before the
11250b57cec5SDimitry Andric // if-conversion pass. It's probably something like a conditional move.
11260b57cec5SDimitry Andric // Mark this block unpredicable for now.
11270b57cec5SDimitry Andric BBI.IsUnpredicable = true;
11280b57cec5SDimitry Andric return;
11290b57cec5SDimitry Andric }
11300b57cec5SDimitry Andric
11310b57cec5SDimitry Andric if (BBI.ClobbersPred && !isPredicated) {
11320b57cec5SDimitry Andric // Predicate modification instruction should end the block (except for
11330b57cec5SDimitry Andric // already predicated instructions and end of block branches).
11340b57cec5SDimitry Andric // Predicate may have been modified, the subsequent (currently)
11350b57cec5SDimitry Andric // unpredicated instructions cannot be correctly predicated.
11360b57cec5SDimitry Andric BBI.IsUnpredicable = true;
11370b57cec5SDimitry Andric return;
11380b57cec5SDimitry Andric }
11390b57cec5SDimitry Andric
11400b57cec5SDimitry Andric // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
11410b57cec5SDimitry Andric // still potentially predicable.
11420b57cec5SDimitry Andric std::vector<MachineOperand> PredDefs;
1143e8d8bef9SDimitry Andric if (TII->ClobbersPredicate(MI, PredDefs, true))
11440b57cec5SDimitry Andric BBI.ClobbersPred = true;
11450b57cec5SDimitry Andric
11460b57cec5SDimitry Andric if (!TII->isPredicable(MI)) {
11470b57cec5SDimitry Andric BBI.IsUnpredicable = true;
11480b57cec5SDimitry Andric return;
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric }
11520b57cec5SDimitry Andric
11530b57cec5SDimitry Andric /// Determine if the block is a suitable candidate to be predicated by the
11540b57cec5SDimitry Andric /// specified predicate.
11550b57cec5SDimitry Andric /// @param BBI BBInfo for the block to check
11560b57cec5SDimitry Andric /// @param Pred Predicate array for the branch that leads to BBI
11570b57cec5SDimitry Andric /// @param isTriangle true if the Analysis is for a triangle
11580b57cec5SDimitry Andric /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
11590b57cec5SDimitry Andric /// case
11600b57cec5SDimitry Andric /// @param hasCommonTail true if BBI shares a tail with a sibling block that
11610b57cec5SDimitry Andric /// contains any instruction that would make the block unpredicable.
FeasibilityAnalysis(BBInfo & BBI,SmallVectorImpl<MachineOperand> & Pred,bool isTriangle,bool RevBranch,bool hasCommonTail)11620b57cec5SDimitry Andric bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
11630b57cec5SDimitry Andric SmallVectorImpl<MachineOperand> &Pred,
11640b57cec5SDimitry Andric bool isTriangle, bool RevBranch,
11650b57cec5SDimitry Andric bool hasCommonTail) {
11660b57cec5SDimitry Andric // If the block is dead or unpredicable, then it cannot be predicated.
11670b57cec5SDimitry Andric // Two blocks may share a common unpredicable tail, but this doesn't prevent
11680b57cec5SDimitry Andric // them from being if-converted. The non-shared portion is assumed to have
11690b57cec5SDimitry Andric // been checked
11700b57cec5SDimitry Andric if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
11710b57cec5SDimitry Andric return false;
11720b57cec5SDimitry Andric
11730b57cec5SDimitry Andric // If it is already predicated but we couldn't analyze its terminator, the
11740b57cec5SDimitry Andric // latter might fallthrough, but we can't determine where to.
11750b57cec5SDimitry Andric // Conservatively avoid if-converting again.
11760b57cec5SDimitry Andric if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
11770b57cec5SDimitry Andric return false;
11780b57cec5SDimitry Andric
11790b57cec5SDimitry Andric // If it is already predicated, check if the new predicate subsumes
11800b57cec5SDimitry Andric // its predicate.
11810b57cec5SDimitry Andric if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
11820b57cec5SDimitry Andric return false;
11830b57cec5SDimitry Andric
11840b57cec5SDimitry Andric if (!hasCommonTail && BBI.BrCond.size()) {
11850b57cec5SDimitry Andric if (!isTriangle)
11860b57cec5SDimitry Andric return false;
11870b57cec5SDimitry Andric
11880b57cec5SDimitry Andric // Test predicate subsumption.
11890b57cec5SDimitry Andric SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
11900b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
11910b57cec5SDimitry Andric if (RevBranch) {
11920b57cec5SDimitry Andric if (TII->reverseBranchCondition(Cond))
11930b57cec5SDimitry Andric return false;
11940b57cec5SDimitry Andric }
11950b57cec5SDimitry Andric if (TII->reverseBranchCondition(RevPred) ||
11960b57cec5SDimitry Andric !TII->SubsumesPredicate(Cond, RevPred))
11970b57cec5SDimitry Andric return false;
11980b57cec5SDimitry Andric }
11990b57cec5SDimitry Andric
12000b57cec5SDimitry Andric return true;
12010b57cec5SDimitry Andric }
12020b57cec5SDimitry Andric
12030b57cec5SDimitry Andric /// Analyze the structure of the sub-CFG starting from the specified block.
12040b57cec5SDimitry Andric /// Record its successors and whether it looks like an if-conversion candidate.
AnalyzeBlock(MachineBasicBlock & MBB,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)12050b57cec5SDimitry Andric void IfConverter::AnalyzeBlock(
12060b57cec5SDimitry Andric MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
12070b57cec5SDimitry Andric struct BBState {
12081fd87a68SDimitry Andric BBState(MachineBasicBlock &MBB) : MBB(&MBB) {}
12090b57cec5SDimitry Andric MachineBasicBlock *MBB;
12100b57cec5SDimitry Andric
12110b57cec5SDimitry Andric /// This flag is true if MBB's successors have been analyzed.
12121fd87a68SDimitry Andric bool SuccsAnalyzed = false;
12130b57cec5SDimitry Andric };
12140b57cec5SDimitry Andric
12150b57cec5SDimitry Andric // Push MBB to the stack.
12160b57cec5SDimitry Andric SmallVector<BBState, 16> BBStack(1, MBB);
12170b57cec5SDimitry Andric
12180b57cec5SDimitry Andric while (!BBStack.empty()) {
12190b57cec5SDimitry Andric BBState &State = BBStack.back();
12200b57cec5SDimitry Andric MachineBasicBlock *BB = State.MBB;
12210b57cec5SDimitry Andric BBInfo &BBI = BBAnalysis[BB->getNumber()];
12220b57cec5SDimitry Andric
12230b57cec5SDimitry Andric if (!State.SuccsAnalyzed) {
12240b57cec5SDimitry Andric if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
12250b57cec5SDimitry Andric BBStack.pop_back();
12260b57cec5SDimitry Andric continue;
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric
12290b57cec5SDimitry Andric BBI.BB = BB;
12300b57cec5SDimitry Andric BBI.IsBeingAnalyzed = true;
12310b57cec5SDimitry Andric
12320b57cec5SDimitry Andric AnalyzeBranches(BBI);
12330b57cec5SDimitry Andric MachineBasicBlock::iterator Begin = BBI.BB->begin();
12340b57cec5SDimitry Andric MachineBasicBlock::iterator End = BBI.BB->end();
12350b57cec5SDimitry Andric ScanInstructions(BBI, Begin, End);
12360b57cec5SDimitry Andric
12370b57cec5SDimitry Andric // Unanalyzable or ends with fallthrough or unconditional branch, or if is
12380b57cec5SDimitry Andric // not considered for ifcvt anymore.
12390b57cec5SDimitry Andric if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
12400b57cec5SDimitry Andric BBI.IsBeingAnalyzed = false;
12410b57cec5SDimitry Andric BBI.IsAnalyzed = true;
12420b57cec5SDimitry Andric BBStack.pop_back();
12430b57cec5SDimitry Andric continue;
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric
12460b57cec5SDimitry Andric // Do not ifcvt if either path is a back edge to the entry block.
12470b57cec5SDimitry Andric if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
12480b57cec5SDimitry Andric BBI.IsBeingAnalyzed = false;
12490b57cec5SDimitry Andric BBI.IsAnalyzed = true;
12500b57cec5SDimitry Andric BBStack.pop_back();
12510b57cec5SDimitry Andric continue;
12520b57cec5SDimitry Andric }
12530b57cec5SDimitry Andric
12540b57cec5SDimitry Andric // Do not ifcvt if true and false fallthrough blocks are the same.
12550b57cec5SDimitry Andric if (!BBI.FalseBB) {
12560b57cec5SDimitry Andric BBI.IsBeingAnalyzed = false;
12570b57cec5SDimitry Andric BBI.IsAnalyzed = true;
12580b57cec5SDimitry Andric BBStack.pop_back();
12590b57cec5SDimitry Andric continue;
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric
12620b57cec5SDimitry Andric // Push the False and True blocks to the stack.
12630b57cec5SDimitry Andric State.SuccsAnalyzed = true;
12640b57cec5SDimitry Andric BBStack.push_back(*BBI.FalseBB);
12650b57cec5SDimitry Andric BBStack.push_back(*BBI.TrueBB);
12660b57cec5SDimitry Andric continue;
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric
12690b57cec5SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
12700b57cec5SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
12710b57cec5SDimitry Andric
12720b57cec5SDimitry Andric if (TrueBBI.IsDone && FalseBBI.IsDone) {
12730b57cec5SDimitry Andric BBI.IsBeingAnalyzed = false;
12740b57cec5SDimitry Andric BBI.IsAnalyzed = true;
12750b57cec5SDimitry Andric BBStack.pop_back();
12760b57cec5SDimitry Andric continue;
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric
12790b57cec5SDimitry Andric SmallVector<MachineOperand, 4>
12800b57cec5SDimitry Andric RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
12810b57cec5SDimitry Andric bool CanRevCond = !TII->reverseBranchCondition(RevCond);
12820b57cec5SDimitry Andric
12830b57cec5SDimitry Andric unsigned Dups = 0;
12840b57cec5SDimitry Andric unsigned Dups2 = 0;
12850b57cec5SDimitry Andric bool TNeedSub = !TrueBBI.Predicate.empty();
12860b57cec5SDimitry Andric bool FNeedSub = !FalseBBI.Predicate.empty();
12870b57cec5SDimitry Andric bool Enqueued = false;
12880b57cec5SDimitry Andric
12890b57cec5SDimitry Andric BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
12900b57cec5SDimitry Andric
12910b57cec5SDimitry Andric if (CanRevCond) {
12920b57cec5SDimitry Andric BBInfo TrueBBICalc, FalseBBICalc;
12938bcb0991SDimitry Andric auto feasibleDiamond = [&](bool Forked) {
12948bcb0991SDimitry Andric bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
12958bcb0991SDimitry Andric Dups + Dups2, Prediction, Forked);
12960b57cec5SDimitry Andric bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
12970b57cec5SDimitry Andric /* IsTriangle */ false, /* RevCond */ false,
12980b57cec5SDimitry Andric /* hasCommonTail */ true);
12990b57cec5SDimitry Andric bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
13000b57cec5SDimitry Andric /* IsTriangle */ false, /* RevCond */ false,
13010b57cec5SDimitry Andric /* hasCommonTail */ true);
13020b57cec5SDimitry Andric return MeetsSize && TrueFeasible && FalseFeasible;
13030b57cec5SDimitry Andric };
13040b57cec5SDimitry Andric
13050b57cec5SDimitry Andric if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
13060b57cec5SDimitry Andric TrueBBICalc, FalseBBICalc)) {
13078bcb0991SDimitry Andric if (feasibleDiamond(false)) {
13080b57cec5SDimitry Andric // Diamond:
13090b57cec5SDimitry Andric // EBB
13100b57cec5SDimitry Andric // / \_
13110b57cec5SDimitry Andric // | |
13120b57cec5SDimitry Andric // TBB FBB
13130b57cec5SDimitry Andric // \ /
13140b57cec5SDimitry Andric // TailBB
13150b57cec5SDimitry Andric // Note TailBB can be empty.
13168bcb0991SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(
13170b57cec5SDimitry Andric BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
13180b57cec5SDimitry Andric (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
13190b57cec5SDimitry Andric Enqueued = true;
13200b57cec5SDimitry Andric }
13210b57cec5SDimitry Andric } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
13220b57cec5SDimitry Andric TrueBBICalc, FalseBBICalc)) {
13238bcb0991SDimitry Andric if (feasibleDiamond(true)) {
13240b57cec5SDimitry Andric // ForkedDiamond:
13250b57cec5SDimitry Andric // if TBB and FBB have a common tail that includes their conditional
13260b57cec5SDimitry Andric // branch instructions, then we can If Convert this pattern.
13270b57cec5SDimitry Andric // EBB
13280b57cec5SDimitry Andric // _/ \_
13290b57cec5SDimitry Andric // | |
13300b57cec5SDimitry Andric // TBB FBB
13310b57cec5SDimitry Andric // / \ / \
13320b57cec5SDimitry Andric // FalseBB TrueBB FalseBB
13330b57cec5SDimitry Andric //
13348bcb0991SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(
13350b57cec5SDimitry Andric BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
13360b57cec5SDimitry Andric (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
13370b57cec5SDimitry Andric Enqueued = true;
13380b57cec5SDimitry Andric }
13390b57cec5SDimitry Andric }
13400b57cec5SDimitry Andric }
13410b57cec5SDimitry Andric
13420b57cec5SDimitry Andric if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
13430b57cec5SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13440b57cec5SDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
13450b57cec5SDimitry Andric FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
13460b57cec5SDimitry Andric // Triangle:
13470b57cec5SDimitry Andric // EBB
13480b57cec5SDimitry Andric // | \_
13490b57cec5SDimitry Andric // | |
13500b57cec5SDimitry Andric // | TBB
13510b57cec5SDimitry Andric // | /
13520b57cec5SDimitry Andric // FBB
13530b57cec5SDimitry Andric Tokens.push_back(
13548bcb0991SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
13550b57cec5SDimitry Andric Enqueued = true;
13560b57cec5SDimitry Andric }
13570b57cec5SDimitry Andric
13580b57cec5SDimitry Andric if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
13590b57cec5SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13600b57cec5SDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
13610b57cec5SDimitry Andric FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
13620b57cec5SDimitry Andric Tokens.push_back(
13638bcb0991SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
13640b57cec5SDimitry Andric Enqueued = true;
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric
13670b57cec5SDimitry Andric if (ValidSimple(TrueBBI, Dups, Prediction) &&
13680b57cec5SDimitry Andric MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
13690b57cec5SDimitry Andric TrueBBI.ExtraCost2, Prediction) &&
13700b57cec5SDimitry Andric FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
13710b57cec5SDimitry Andric // Simple (split, no rejoin):
13720b57cec5SDimitry Andric // EBB
13730b57cec5SDimitry Andric // | \_
13740b57cec5SDimitry Andric // | |
13750b57cec5SDimitry Andric // | TBB---> exit
13760b57cec5SDimitry Andric // |
13770b57cec5SDimitry Andric // FBB
13780b57cec5SDimitry Andric Tokens.push_back(
13798bcb0991SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
13800b57cec5SDimitry Andric Enqueued = true;
13810b57cec5SDimitry Andric }
13820b57cec5SDimitry Andric
13830b57cec5SDimitry Andric if (CanRevCond) {
13840b57cec5SDimitry Andric // Try the other path...
13850b57cec5SDimitry Andric if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
13860b57cec5SDimitry Andric Prediction.getCompl()) &&
13870b57cec5SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
13880b57cec5SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
13890b57cec5SDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
13900b57cec5SDimitry Andric FeasibilityAnalysis(FalseBBI, RevCond, true)) {
13918bcb0991SDimitry Andric Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
13920b57cec5SDimitry Andric FNeedSub, Dups));
13930b57cec5SDimitry Andric Enqueued = true;
13940b57cec5SDimitry Andric }
13950b57cec5SDimitry Andric
13960b57cec5SDimitry Andric if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
13970b57cec5SDimitry Andric Prediction.getCompl()) &&
13980b57cec5SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
13990b57cec5SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
14000b57cec5SDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
14010b57cec5SDimitry Andric FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
14020b57cec5SDimitry Andric Tokens.push_back(
14038bcb0991SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
14040b57cec5SDimitry Andric Enqueued = true;
14050b57cec5SDimitry Andric }
14060b57cec5SDimitry Andric
14070b57cec5SDimitry Andric if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
14080b57cec5SDimitry Andric MeetIfcvtSizeLimit(*FalseBBI.BB,
14090b57cec5SDimitry Andric FalseBBI.NonPredSize + FalseBBI.ExtraCost,
14100b57cec5SDimitry Andric FalseBBI.ExtraCost2, Prediction.getCompl()) &&
14110b57cec5SDimitry Andric FeasibilityAnalysis(FalseBBI, RevCond)) {
14120b57cec5SDimitry Andric Tokens.push_back(
14138bcb0991SDimitry Andric std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
14140b57cec5SDimitry Andric Enqueued = true;
14150b57cec5SDimitry Andric }
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric
14180b57cec5SDimitry Andric BBI.IsEnqueued = Enqueued;
14190b57cec5SDimitry Andric BBI.IsBeingAnalyzed = false;
14200b57cec5SDimitry Andric BBI.IsAnalyzed = true;
14210b57cec5SDimitry Andric BBStack.pop_back();
14220b57cec5SDimitry Andric }
14230b57cec5SDimitry Andric }
14240b57cec5SDimitry Andric
14250b57cec5SDimitry Andric /// Analyze all blocks and find entries for all if-conversion candidates.
AnalyzeBlocks(MachineFunction & MF,std::vector<std::unique_ptr<IfcvtToken>> & Tokens)14260b57cec5SDimitry Andric void IfConverter::AnalyzeBlocks(
14270b57cec5SDimitry Andric MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
14280b57cec5SDimitry Andric for (MachineBasicBlock &MBB : MF)
14290b57cec5SDimitry Andric AnalyzeBlock(MBB, Tokens);
14300b57cec5SDimitry Andric
14310b57cec5SDimitry Andric // Sort to favor more complex ifcvt scheme.
14320b57cec5SDimitry Andric llvm::stable_sort(Tokens, IfcvtTokenCmp);
14330b57cec5SDimitry Andric }
14340b57cec5SDimitry Andric
14350b57cec5SDimitry Andric /// Returns true either if ToMBB is the next block after MBB or that all the
14360b57cec5SDimitry Andric /// intervening blocks are empty (given MBB can fall through to its next block).
canFallThroughTo(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB)14370b57cec5SDimitry Andric static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
14380b57cec5SDimitry Andric MachineFunction::iterator PI = MBB.getIterator();
14390b57cec5SDimitry Andric MachineFunction::iterator I = std::next(PI);
14400b57cec5SDimitry Andric MachineFunction::iterator TI = ToMBB.getIterator();
14410b57cec5SDimitry Andric MachineFunction::iterator E = MBB.getParent()->end();
14420b57cec5SDimitry Andric while (I != TI) {
14430b57cec5SDimitry Andric // Check isSuccessor to avoid case where the next block is empty, but
14440b57cec5SDimitry Andric // it's not a successor.
14450b57cec5SDimitry Andric if (I == E || !I->empty() || !PI->isSuccessor(&*I))
14460b57cec5SDimitry Andric return false;
14470b57cec5SDimitry Andric PI = I++;
14480b57cec5SDimitry Andric }
14490b57cec5SDimitry Andric // Finally see if the last I is indeed a successor to PI.
14500b57cec5SDimitry Andric return PI->isSuccessor(&*I);
14510b57cec5SDimitry Andric }
14520b57cec5SDimitry Andric
14530b57cec5SDimitry Andric /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
14540b57cec5SDimitry Andric /// can be if-converted. If predecessor is already enqueued, dequeue it!
InvalidatePreds(MachineBasicBlock & MBB)14550b57cec5SDimitry Andric void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
14560b57cec5SDimitry Andric for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
14570b57cec5SDimitry Andric BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
14580b57cec5SDimitry Andric if (PBBI.IsDone || PBBI.BB == &MBB)
14590b57cec5SDimitry Andric continue;
14600b57cec5SDimitry Andric PBBI.IsAnalyzed = false;
14610b57cec5SDimitry Andric PBBI.IsEnqueued = false;
14620b57cec5SDimitry Andric }
14630b57cec5SDimitry Andric }
14640b57cec5SDimitry Andric
14650b57cec5SDimitry Andric /// Inserts an unconditional branch from \p MBB to \p ToMBB.
InsertUncondBranch(MachineBasicBlock & MBB,MachineBasicBlock & ToMBB,const TargetInstrInfo * TII)14660b57cec5SDimitry Andric static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
14670b57cec5SDimitry Andric const TargetInstrInfo *TII) {
14680b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere
14690b57cec5SDimitry Andric SmallVector<MachineOperand, 0> NoCond;
14700b57cec5SDimitry Andric TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric
14730b57cec5SDimitry Andric /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
14740b57cec5SDimitry Andric /// values defined in MI which are also live/used by MI.
UpdatePredRedefs(MachineInstr & MI,LivePhysRegs & Redefs)14750b57cec5SDimitry Andric static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
14760b57cec5SDimitry Andric const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
14770b57cec5SDimitry Andric
14780b57cec5SDimitry Andric // Before stepping forward past MI, remember which regs were live
14790b57cec5SDimitry Andric // before MI. This is needed to set the Undef flag only when reg is
14800b57cec5SDimitry Andric // dead.
14810b57cec5SDimitry Andric SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
14820b57cec5SDimitry Andric LiveBeforeMI.setUniverse(TRI->getNumRegs());
14830b57cec5SDimitry Andric for (unsigned Reg : Redefs)
14840b57cec5SDimitry Andric LiveBeforeMI.insert(Reg);
14850b57cec5SDimitry Andric
14860b57cec5SDimitry Andric SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
14870b57cec5SDimitry Andric Redefs.stepForward(MI, Clobbers);
14880b57cec5SDimitry Andric
14890b57cec5SDimitry Andric // Now add the implicit uses for each of the clobbered values.
14900b57cec5SDimitry Andric for (auto Clobber : Clobbers) {
14910b57cec5SDimitry Andric // FIXME: Const cast here is nasty, but better than making StepForward
14920b57cec5SDimitry Andric // take a mutable instruction instead of const.
14930b57cec5SDimitry Andric unsigned Reg = Clobber.first;
14940b57cec5SDimitry Andric MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
14950b57cec5SDimitry Andric MachineInstr *OpMI = Op.getParent();
14960b57cec5SDimitry Andric MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
14970b57cec5SDimitry Andric if (Op.isRegMask()) {
14980b57cec5SDimitry Andric // First handle regmasks. They clobber any entries in the mask which
14990b57cec5SDimitry Andric // means that we need a def for those registers.
15000b57cec5SDimitry Andric if (LiveBeforeMI.count(Reg))
15010b57cec5SDimitry Andric MIB.addReg(Reg, RegState::Implicit);
15020b57cec5SDimitry Andric
15030b57cec5SDimitry Andric // We also need to add an implicit def of this register for the later
15040b57cec5SDimitry Andric // use to read from.
15050b57cec5SDimitry Andric // For the register allocator to have allocated a register clobbered
15060b57cec5SDimitry Andric // by the call which is used later, it must be the case that
15070b57cec5SDimitry Andric // the call doesn't return.
15080b57cec5SDimitry Andric MIB.addReg(Reg, RegState::Implicit | RegState::Define);
15090b57cec5SDimitry Andric continue;
15100b57cec5SDimitry Andric }
1511fe013be4SDimitry Andric if (any_of(TRI->subregs_inclusive(Reg),
1512fe013be4SDimitry Andric [&](MCPhysReg S) { return LiveBeforeMI.count(S); }))
15130b57cec5SDimitry Andric MIB.addReg(Reg, RegState::Implicit);
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric }
15160b57cec5SDimitry Andric
15170b57cec5SDimitry Andric /// If convert a simple (split, no rejoin) sub-CFG.
IfConvertSimple(BBInfo & BBI,IfcvtKind Kind)15180b57cec5SDimitry Andric bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
15190b57cec5SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
15200b57cec5SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
15210b57cec5SDimitry Andric BBInfo *CvtBBI = &TrueBBI;
15220b57cec5SDimitry Andric BBInfo *NextBBI = &FalseBBI;
15230b57cec5SDimitry Andric
15240b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
15250b57cec5SDimitry Andric if (Kind == ICSimpleFalse)
15260b57cec5SDimitry Andric std::swap(CvtBBI, NextBBI);
15270b57cec5SDimitry Andric
15280b57cec5SDimitry Andric MachineBasicBlock &CvtMBB = *CvtBBI->BB;
15290b57cec5SDimitry Andric MachineBasicBlock &NextMBB = *NextBBI->BB;
15300b57cec5SDimitry Andric if (CvtBBI->IsDone ||
15310b57cec5SDimitry Andric (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
15320b57cec5SDimitry Andric // Something has changed. It's no longer safe to predicate this block.
15330b57cec5SDimitry Andric BBI.IsAnalyzed = false;
15340b57cec5SDimitry Andric CvtBBI->IsAnalyzed = false;
15350b57cec5SDimitry Andric return false;
15360b57cec5SDimitry Andric }
15370b57cec5SDimitry Andric
15380b57cec5SDimitry Andric if (CvtMBB.hasAddressTaken())
15390b57cec5SDimitry Andric // Conservatively abort if-conversion if BB's address is taken.
15400b57cec5SDimitry Andric return false;
15410b57cec5SDimitry Andric
15420b57cec5SDimitry Andric if (Kind == ICSimpleFalse)
15430b57cec5SDimitry Andric if (TII->reverseBranchCondition(Cond))
15440b57cec5SDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
15450b57cec5SDimitry Andric
15460b57cec5SDimitry Andric Redefs.init(*TRI);
15470b57cec5SDimitry Andric
15480b57cec5SDimitry Andric if (MRI->tracksLiveness()) {
15490b57cec5SDimitry Andric // Initialize liveins to the first BB. These are potentially redefined by
15500b57cec5SDimitry Andric // predicated instructions.
1551fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(CvtMBB);
1552fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(NextMBB);
15530b57cec5SDimitry Andric }
15540b57cec5SDimitry Andric
15550b57cec5SDimitry Andric // Remove the branches from the entry so we can add the contents of the true
15560b57cec5SDimitry Andric // block to it.
15570b57cec5SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
15580b57cec5SDimitry Andric
15590b57cec5SDimitry Andric if (CvtMBB.pred_size() > 1) {
15600b57cec5SDimitry Andric // Copy instructions in the true block, predicate them, and add them to
15610b57cec5SDimitry Andric // the entry block.
15620b57cec5SDimitry Andric CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
15630b57cec5SDimitry Andric
15640b57cec5SDimitry Andric // Keep the CFG updated.
15650b57cec5SDimitry Andric BBI.BB->removeSuccessor(&CvtMBB, true);
15660b57cec5SDimitry Andric } else {
15670b57cec5SDimitry Andric // Predicate the instructions in the true block.
15680b57cec5SDimitry Andric PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric // Merge converted block into entry block. The BB to Cvt edge is removed
15710b57cec5SDimitry Andric // by MergeBlocks.
15720b57cec5SDimitry Andric MergeBlocks(BBI, *CvtBBI);
15730b57cec5SDimitry Andric }
15740b57cec5SDimitry Andric
15750b57cec5SDimitry Andric bool IterIfcvt = true;
15760b57cec5SDimitry Andric if (!canFallThroughTo(*BBI.BB, NextMBB)) {
15770b57cec5SDimitry Andric InsertUncondBranch(*BBI.BB, NextMBB, TII);
15780b57cec5SDimitry Andric BBI.HasFallThrough = false;
15790b57cec5SDimitry Andric // Now ifcvt'd block will look like this:
15800b57cec5SDimitry Andric // BB:
15810b57cec5SDimitry Andric // ...
15820b57cec5SDimitry Andric // t, f = cmp
15830b57cec5SDimitry Andric // if t op
15840b57cec5SDimitry Andric // b BBf
15850b57cec5SDimitry Andric //
15860b57cec5SDimitry Andric // We cannot further ifcvt this block because the unconditional branch
15870b57cec5SDimitry Andric // will have to be predicated on the new condition, that will not be
15880b57cec5SDimitry Andric // available if cmp executes.
15890b57cec5SDimitry Andric IterIfcvt = false;
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric
15920b57cec5SDimitry Andric // Update block info. BB can be iteratively if-converted.
15930b57cec5SDimitry Andric if (!IterIfcvt)
15940b57cec5SDimitry Andric BBI.IsDone = true;
15950b57cec5SDimitry Andric InvalidatePreds(*BBI.BB);
15960b57cec5SDimitry Andric CvtBBI->IsDone = true;
15970b57cec5SDimitry Andric
15980b57cec5SDimitry Andric // FIXME: Must maintain LiveIns.
15990b57cec5SDimitry Andric return true;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric
16020b57cec5SDimitry Andric /// If convert a triangle sub-CFG.
IfConvertTriangle(BBInfo & BBI,IfcvtKind Kind)16030b57cec5SDimitry Andric bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
16040b57cec5SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
16050b57cec5SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
16060b57cec5SDimitry Andric BBInfo *CvtBBI = &TrueBBI;
16070b57cec5SDimitry Andric BBInfo *NextBBI = &FalseBBI;
16080b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere
16090b57cec5SDimitry Andric
16100b57cec5SDimitry Andric SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
16110b57cec5SDimitry Andric if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
16120b57cec5SDimitry Andric std::swap(CvtBBI, NextBBI);
16130b57cec5SDimitry Andric
16140b57cec5SDimitry Andric MachineBasicBlock &CvtMBB = *CvtBBI->BB;
16150b57cec5SDimitry Andric MachineBasicBlock &NextMBB = *NextBBI->BB;
16160b57cec5SDimitry Andric if (CvtBBI->IsDone ||
16170b57cec5SDimitry Andric (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
16180b57cec5SDimitry Andric // Something has changed. It's no longer safe to predicate this block.
16190b57cec5SDimitry Andric BBI.IsAnalyzed = false;
16200b57cec5SDimitry Andric CvtBBI->IsAnalyzed = false;
16210b57cec5SDimitry Andric return false;
16220b57cec5SDimitry Andric }
16230b57cec5SDimitry Andric
16240b57cec5SDimitry Andric if (CvtMBB.hasAddressTaken())
16250b57cec5SDimitry Andric // Conservatively abort if-conversion if BB's address is taken.
16260b57cec5SDimitry Andric return false;
16270b57cec5SDimitry Andric
16280b57cec5SDimitry Andric if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
16290b57cec5SDimitry Andric if (TII->reverseBranchCondition(Cond))
16300b57cec5SDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
16310b57cec5SDimitry Andric
16320b57cec5SDimitry Andric if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
16330b57cec5SDimitry Andric if (reverseBranchCondition(*CvtBBI)) {
16340b57cec5SDimitry Andric // BB has been changed, modify its predecessors (except for this
16350b57cec5SDimitry Andric // one) so they don't get ifcvt'ed based on bad intel.
16360b57cec5SDimitry Andric for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
16370b57cec5SDimitry Andric if (PBB == BBI.BB)
16380b57cec5SDimitry Andric continue;
16390b57cec5SDimitry Andric BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
16400b57cec5SDimitry Andric if (PBBI.IsEnqueued) {
16410b57cec5SDimitry Andric PBBI.IsAnalyzed = false;
16420b57cec5SDimitry Andric PBBI.IsEnqueued = false;
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric }
16450b57cec5SDimitry Andric }
16460b57cec5SDimitry Andric }
16470b57cec5SDimitry Andric
16480b57cec5SDimitry Andric // Initialize liveins to the first BB. These are potentially redefined by
16490b57cec5SDimitry Andric // predicated instructions.
16500b57cec5SDimitry Andric Redefs.init(*TRI);
16510b57cec5SDimitry Andric if (MRI->tracksLiveness()) {
1652fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(CvtMBB);
1653fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(NextMBB);
16540b57cec5SDimitry Andric }
16550b57cec5SDimitry Andric
16560b57cec5SDimitry Andric bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
16570b57cec5SDimitry Andric BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
16580b57cec5SDimitry Andric
16590b57cec5SDimitry Andric if (HasEarlyExit) {
16600b57cec5SDimitry Andric // Get probabilities before modifying CvtMBB and BBI.BB.
16610b57cec5SDimitry Andric CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
16620b57cec5SDimitry Andric CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
16630b57cec5SDimitry Andric BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
16640b57cec5SDimitry Andric BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
16650b57cec5SDimitry Andric }
16660b57cec5SDimitry Andric
16670b57cec5SDimitry Andric // Remove the branches from the entry so we can add the contents of the true
16680b57cec5SDimitry Andric // block to it.
16690b57cec5SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
16700b57cec5SDimitry Andric
16710b57cec5SDimitry Andric if (CvtMBB.pred_size() > 1) {
16720b57cec5SDimitry Andric // Copy instructions in the true block, predicate them, and add them to
16730b57cec5SDimitry Andric // the entry block.
16740b57cec5SDimitry Andric CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
16750b57cec5SDimitry Andric } else {
16760b57cec5SDimitry Andric // Predicate the 'true' block after removing its branch.
16770b57cec5SDimitry Andric CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
16780b57cec5SDimitry Andric PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
16790b57cec5SDimitry Andric
16800b57cec5SDimitry Andric // Now merge the entry of the triangle with the true block.
16810b57cec5SDimitry Andric MergeBlocks(BBI, *CvtBBI, false);
16820b57cec5SDimitry Andric }
16830b57cec5SDimitry Andric
16840b57cec5SDimitry Andric // Keep the CFG updated.
16850b57cec5SDimitry Andric BBI.BB->removeSuccessor(&CvtMBB, true);
16860b57cec5SDimitry Andric
16870b57cec5SDimitry Andric // If 'true' block has a 'false' successor, add an exit branch to it.
16880b57cec5SDimitry Andric if (HasEarlyExit) {
16890b57cec5SDimitry Andric SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
16900b57cec5SDimitry Andric CvtBBI->BrCond.end());
16910b57cec5SDimitry Andric if (TII->reverseBranchCondition(RevCond))
16920b57cec5SDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
16930b57cec5SDimitry Andric
16940b57cec5SDimitry Andric // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
16950b57cec5SDimitry Andric // NewNext = New_Prob(BBI.BB, NextMBB) =
16960b57cec5SDimitry Andric // Prob(BBI.BB, NextMBB) +
16970b57cec5SDimitry Andric // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
16980b57cec5SDimitry Andric // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
16990b57cec5SDimitry Andric // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
17000b57cec5SDimitry Andric auto NewTrueBB = getNextBlock(*BBI.BB);
17010b57cec5SDimitry Andric auto NewNext = BBNext + BBCvt * CvtNext;
17020b57cec5SDimitry Andric auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
17030b57cec5SDimitry Andric if (NewTrueBBIter != BBI.BB->succ_end())
17040b57cec5SDimitry Andric BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
17050b57cec5SDimitry Andric
17060b57cec5SDimitry Andric auto NewFalse = BBCvt * CvtFalse;
17070b57cec5SDimitry Andric TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
17080b57cec5SDimitry Andric BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
17090b57cec5SDimitry Andric }
17100b57cec5SDimitry Andric
17110b57cec5SDimitry Andric // Merge in the 'false' block if the 'false' block has no other
17120b57cec5SDimitry Andric // predecessors. Otherwise, add an unconditional branch to 'false'.
17130b57cec5SDimitry Andric bool FalseBBDead = false;
17140b57cec5SDimitry Andric bool IterIfcvt = true;
17150b57cec5SDimitry Andric bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
17160b57cec5SDimitry Andric if (!isFallThrough) {
17170b57cec5SDimitry Andric // Only merge them if the true block does not fallthrough to the false
17180b57cec5SDimitry Andric // block. By not merging them, we make it possible to iteratively
17190b57cec5SDimitry Andric // ifcvt the blocks.
17200b57cec5SDimitry Andric if (!HasEarlyExit &&
17210b57cec5SDimitry Andric NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
17220b57cec5SDimitry Andric !NextMBB.hasAddressTaken()) {
17230b57cec5SDimitry Andric MergeBlocks(BBI, *NextBBI);
17240b57cec5SDimitry Andric FalseBBDead = true;
17250b57cec5SDimitry Andric } else {
17260b57cec5SDimitry Andric InsertUncondBranch(*BBI.BB, NextMBB, TII);
17270b57cec5SDimitry Andric BBI.HasFallThrough = false;
17280b57cec5SDimitry Andric }
17290b57cec5SDimitry Andric // Mixed predicated and unpredicated code. This cannot be iteratively
17300b57cec5SDimitry Andric // predicated.
17310b57cec5SDimitry Andric IterIfcvt = false;
17320b57cec5SDimitry Andric }
17330b57cec5SDimitry Andric
17340b57cec5SDimitry Andric // Update block info. BB can be iteratively if-converted.
17350b57cec5SDimitry Andric if (!IterIfcvt)
17360b57cec5SDimitry Andric BBI.IsDone = true;
17370b57cec5SDimitry Andric InvalidatePreds(*BBI.BB);
17380b57cec5SDimitry Andric CvtBBI->IsDone = true;
17390b57cec5SDimitry Andric if (FalseBBDead)
17400b57cec5SDimitry Andric NextBBI->IsDone = true;
17410b57cec5SDimitry Andric
17420b57cec5SDimitry Andric // FIXME: Must maintain LiveIns.
17430b57cec5SDimitry Andric return true;
17440b57cec5SDimitry Andric }
17450b57cec5SDimitry Andric
17460b57cec5SDimitry Andric /// Common code shared between diamond conversions.
17470b57cec5SDimitry Andric /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
17480b57cec5SDimitry Andric /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
17490b57cec5SDimitry Andric /// and FalseBBI
17500b57cec5SDimitry Andric /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
17510b57cec5SDimitry Andric /// and \p FalseBBI
17520b57cec5SDimitry Andric /// \p RemoveBranch - Remove the common branch of the two blocks before
17530b57cec5SDimitry Andric /// predicating. Only false for unanalyzable fallthrough
17540b57cec5SDimitry Andric /// cases. The caller will replace the branch if necessary.
17550b57cec5SDimitry Andric /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
17560b57cec5SDimitry Andric /// unanalyzable fallthrough
IfConvertDiamondCommon(BBInfo & BBI,BBInfo & TrueBBI,BBInfo & FalseBBI,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred,bool RemoveBranch,bool MergeAddEdges)17570b57cec5SDimitry Andric bool IfConverter::IfConvertDiamondCommon(
17580b57cec5SDimitry Andric BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
17590b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
17600b57cec5SDimitry Andric bool TClobbersPred, bool FClobbersPred,
17610b57cec5SDimitry Andric bool RemoveBranch, bool MergeAddEdges) {
17620b57cec5SDimitry Andric
17630b57cec5SDimitry Andric if (TrueBBI.IsDone || FalseBBI.IsDone ||
17640b57cec5SDimitry Andric TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
17650b57cec5SDimitry Andric // Something has changed. It's no longer safe to predicate these blocks.
17660b57cec5SDimitry Andric BBI.IsAnalyzed = false;
17670b57cec5SDimitry Andric TrueBBI.IsAnalyzed = false;
17680b57cec5SDimitry Andric FalseBBI.IsAnalyzed = false;
17690b57cec5SDimitry Andric return false;
17700b57cec5SDimitry Andric }
17710b57cec5SDimitry Andric
17720b57cec5SDimitry Andric if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
17730b57cec5SDimitry Andric // Conservatively abort if-conversion if either BB has its address taken.
17740b57cec5SDimitry Andric return false;
17750b57cec5SDimitry Andric
17760b57cec5SDimitry Andric // Put the predicated instructions from the 'true' block before the
17770b57cec5SDimitry Andric // instructions from the 'false' block, unless the true block would clobber
17780b57cec5SDimitry Andric // the predicate, in which case, do the opposite.
17790b57cec5SDimitry Andric BBInfo *BBI1 = &TrueBBI;
17800b57cec5SDimitry Andric BBInfo *BBI2 = &FalseBBI;
17810b57cec5SDimitry Andric SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
17820b57cec5SDimitry Andric if (TII->reverseBranchCondition(RevCond))
17830b57cec5SDimitry Andric llvm_unreachable("Unable to reverse branch condition!");
17840b57cec5SDimitry Andric SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
17850b57cec5SDimitry Andric SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
17860b57cec5SDimitry Andric
17870b57cec5SDimitry Andric // Figure out the more profitable ordering.
17880b57cec5SDimitry Andric bool DoSwap = false;
17890b57cec5SDimitry Andric if (TClobbersPred && !FClobbersPred)
17900b57cec5SDimitry Andric DoSwap = true;
17910b57cec5SDimitry Andric else if (!TClobbersPred && !FClobbersPred) {
17920b57cec5SDimitry Andric if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
17930b57cec5SDimitry Andric DoSwap = true;
17940b57cec5SDimitry Andric } else if (TClobbersPred && FClobbersPred)
17950b57cec5SDimitry Andric llvm_unreachable("Predicate info cannot be clobbered by both sides.");
17960b57cec5SDimitry Andric if (DoSwap) {
17970b57cec5SDimitry Andric std::swap(BBI1, BBI2);
17980b57cec5SDimitry Andric std::swap(Cond1, Cond2);
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric
18010b57cec5SDimitry Andric // Remove the conditional branch from entry to the blocks.
18020b57cec5SDimitry Andric BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
18030b57cec5SDimitry Andric
18040b57cec5SDimitry Andric MachineBasicBlock &MBB1 = *BBI1->BB;
18050b57cec5SDimitry Andric MachineBasicBlock &MBB2 = *BBI2->BB;
18060b57cec5SDimitry Andric
18070b57cec5SDimitry Andric // Initialize the Redefs:
18080b57cec5SDimitry Andric // - BB2 live-in regs need implicit uses before being redefined by BB1
18090b57cec5SDimitry Andric // instructions.
18100b57cec5SDimitry Andric // - BB1 live-out regs need implicit uses before being redefined by BB2
18110b57cec5SDimitry Andric // instructions. We start with BB1 live-ins so we have the live-out regs
18120b57cec5SDimitry Andric // after tracking the BB1 instructions.
18130b57cec5SDimitry Andric Redefs.init(*TRI);
18140b57cec5SDimitry Andric if (MRI->tracksLiveness()) {
1815fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(MBB1);
1816fe6060f1SDimitry Andric Redefs.addLiveInsNoPristines(MBB2);
18170b57cec5SDimitry Andric }
18180b57cec5SDimitry Andric
18190b57cec5SDimitry Andric // Remove the duplicated instructions at the beginnings of both paths.
18200b57cec5SDimitry Andric // Skip dbg_value instructions.
1821fe6060f1SDimitry Andric MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr(false);
1822fe6060f1SDimitry Andric MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr(false);
18230b57cec5SDimitry Andric BBI1->NonPredSize -= NumDups1;
18240b57cec5SDimitry Andric BBI2->NonPredSize -= NumDups1;
18250b57cec5SDimitry Andric
18260b57cec5SDimitry Andric // Skip past the dups on each side separately since there may be
18270b57cec5SDimitry Andric // differing dbg_value entries. NumDups1 can include a "return"
18280b57cec5SDimitry Andric // instruction, if it's not marked as "branch".
18290b57cec5SDimitry Andric for (unsigned i = 0; i < NumDups1; ++DI1) {
18300b57cec5SDimitry Andric if (DI1 == MBB1.end())
18310b57cec5SDimitry Andric break;
18320b57cec5SDimitry Andric if (!DI1->isDebugInstr())
18330b57cec5SDimitry Andric ++i;
18340b57cec5SDimitry Andric }
18350b57cec5SDimitry Andric while (NumDups1 != 0) {
18368bcb0991SDimitry Andric // Since this instruction is going to be deleted, update call
18378bcb0991SDimitry Andric // site info state if the instruction is call instruction.
18385ffd83dbSDimitry Andric if (DI2->shouldUpdateCallSiteInfo())
18398bcb0991SDimitry Andric MBB2.getParent()->eraseCallSiteInfo(&*DI2);
18408bcb0991SDimitry Andric
18410b57cec5SDimitry Andric ++DI2;
18420b57cec5SDimitry Andric if (DI2 == MBB2.end())
18430b57cec5SDimitry Andric break;
18440b57cec5SDimitry Andric if (!DI2->isDebugInstr())
18450b57cec5SDimitry Andric --NumDups1;
18460b57cec5SDimitry Andric }
18470b57cec5SDimitry Andric
18480b57cec5SDimitry Andric if (MRI->tracksLiveness()) {
18490b57cec5SDimitry Andric for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
18500b57cec5SDimitry Andric SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
18510b57cec5SDimitry Andric Redefs.stepForward(MI, Dummy);
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric }
18540b57cec5SDimitry Andric
18550b57cec5SDimitry Andric BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
18560b57cec5SDimitry Andric MBB2.erase(MBB2.begin(), DI2);
18570b57cec5SDimitry Andric
18580b57cec5SDimitry Andric // The branches have been checked to match, so it is safe to remove the
18590b57cec5SDimitry Andric // branch in BB1 and rely on the copy in BB2. The complication is that
18600b57cec5SDimitry Andric // the blocks may end with a return instruction, which may or may not
18610b57cec5SDimitry Andric // be marked as "branch". If it's not, then it could be included in
18620b57cec5SDimitry Andric // "dups1", leaving the blocks potentially empty after moving the common
18630b57cec5SDimitry Andric // duplicates.
18640b57cec5SDimitry Andric #ifndef NDEBUG
18650b57cec5SDimitry Andric // Unanalyzable branches must match exactly. Check that now.
18660b57cec5SDimitry Andric if (!BBI1->IsBrAnalyzable)
18670b57cec5SDimitry Andric verifySameBranchInstructions(&MBB1, &MBB2);
18680b57cec5SDimitry Andric #endif
18690b57cec5SDimitry Andric // Remove duplicated instructions from the tail of MBB1: any branch
18700b57cec5SDimitry Andric // instructions, and the common instructions counted by NumDups2.
18710b57cec5SDimitry Andric DI1 = MBB1.end();
18720b57cec5SDimitry Andric while (DI1 != MBB1.begin()) {
18730b57cec5SDimitry Andric MachineBasicBlock::iterator Prev = std::prev(DI1);
18740b57cec5SDimitry Andric if (!Prev->isBranch() && !Prev->isDebugInstr())
18750b57cec5SDimitry Andric break;
18760b57cec5SDimitry Andric DI1 = Prev;
18770b57cec5SDimitry Andric }
18780b57cec5SDimitry Andric for (unsigned i = 0; i != NumDups2; ) {
18790b57cec5SDimitry Andric // NumDups2 only counted non-dbg_value instructions, so this won't
18800b57cec5SDimitry Andric // run off the head of the list.
18810b57cec5SDimitry Andric assert(DI1 != MBB1.begin());
18828bcb0991SDimitry Andric
18830b57cec5SDimitry Andric --DI1;
18848bcb0991SDimitry Andric
18858bcb0991SDimitry Andric // Since this instruction is going to be deleted, update call
18868bcb0991SDimitry Andric // site info state if the instruction is call instruction.
18875ffd83dbSDimitry Andric if (DI1->shouldUpdateCallSiteInfo())
18888bcb0991SDimitry Andric MBB1.getParent()->eraseCallSiteInfo(&*DI1);
18898bcb0991SDimitry Andric
18900b57cec5SDimitry Andric // skip dbg_value instructions
18910b57cec5SDimitry Andric if (!DI1->isDebugInstr())
18920b57cec5SDimitry Andric ++i;
18930b57cec5SDimitry Andric }
18940b57cec5SDimitry Andric MBB1.erase(DI1, MBB1.end());
18950b57cec5SDimitry Andric
18960b57cec5SDimitry Andric DI2 = BBI2->BB->end();
18970b57cec5SDimitry Andric // The branches have been checked to match. Skip over the branch in the false
18980b57cec5SDimitry Andric // block so that we don't try to predicate it.
18990b57cec5SDimitry Andric if (RemoveBranch)
19000b57cec5SDimitry Andric BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
19010b57cec5SDimitry Andric else {
19020b57cec5SDimitry Andric // Make DI2 point to the end of the range where the common "tail"
19030b57cec5SDimitry Andric // instructions could be found.
19040b57cec5SDimitry Andric while (DI2 != MBB2.begin()) {
19050b57cec5SDimitry Andric MachineBasicBlock::iterator Prev = std::prev(DI2);
19060b57cec5SDimitry Andric if (!Prev->isBranch() && !Prev->isDebugInstr())
19070b57cec5SDimitry Andric break;
19080b57cec5SDimitry Andric DI2 = Prev;
19090b57cec5SDimitry Andric }
19100b57cec5SDimitry Andric }
19110b57cec5SDimitry Andric while (NumDups2 != 0) {
19120b57cec5SDimitry Andric // NumDups2 only counted non-dbg_value instructions, so this won't
19130b57cec5SDimitry Andric // run off the head of the list.
19140b57cec5SDimitry Andric assert(DI2 != MBB2.begin());
19150b57cec5SDimitry Andric --DI2;
19160b57cec5SDimitry Andric // skip dbg_value instructions
19170b57cec5SDimitry Andric if (!DI2->isDebugInstr())
19180b57cec5SDimitry Andric --NumDups2;
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric
19210b57cec5SDimitry Andric // Remember which registers would later be defined by the false block.
19220b57cec5SDimitry Andric // This allows us not to predicate instructions in the true block that would
19230b57cec5SDimitry Andric // later be re-defined. That is, rather than
19240b57cec5SDimitry Andric // subeq r0, r1, #1
19250b57cec5SDimitry Andric // addne r0, r1, #1
19260b57cec5SDimitry Andric // generate:
19270b57cec5SDimitry Andric // sub r0, r1, #1
19280b57cec5SDimitry Andric // addne r0, r1, #1
19290b57cec5SDimitry Andric SmallSet<MCPhysReg, 4> RedefsByFalse;
19300b57cec5SDimitry Andric SmallSet<MCPhysReg, 4> ExtUses;
19310b57cec5SDimitry Andric if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
19320b57cec5SDimitry Andric for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
19330b57cec5SDimitry Andric if (FI.isDebugInstr())
19340b57cec5SDimitry Andric continue;
19350b57cec5SDimitry Andric SmallVector<MCPhysReg, 4> Defs;
19360b57cec5SDimitry Andric for (const MachineOperand &MO : FI.operands()) {
19370b57cec5SDimitry Andric if (!MO.isReg())
19380b57cec5SDimitry Andric continue;
19398bcb0991SDimitry Andric Register Reg = MO.getReg();
19400b57cec5SDimitry Andric if (!Reg)
19410b57cec5SDimitry Andric continue;
19420b57cec5SDimitry Andric if (MO.isDef()) {
19430b57cec5SDimitry Andric Defs.push_back(Reg);
19440b57cec5SDimitry Andric } else if (!RedefsByFalse.count(Reg)) {
19450b57cec5SDimitry Andric // These are defined before ctrl flow reach the 'false' instructions.
19460b57cec5SDimitry Andric // They cannot be modified by the 'true' instructions.
1947fe013be4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
1948fe013be4SDimitry Andric ExtUses.insert(SubReg);
19490b57cec5SDimitry Andric }
19500b57cec5SDimitry Andric }
19510b57cec5SDimitry Andric
19520b57cec5SDimitry Andric for (MCPhysReg Reg : Defs) {
19530b57cec5SDimitry Andric if (!ExtUses.count(Reg)) {
1954fe013be4SDimitry Andric for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
1955fe013be4SDimitry Andric RedefsByFalse.insert(SubReg);
19560b57cec5SDimitry Andric }
19570b57cec5SDimitry Andric }
19580b57cec5SDimitry Andric }
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric
19610b57cec5SDimitry Andric // Predicate the 'true' block.
19620b57cec5SDimitry Andric PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
19630b57cec5SDimitry Andric
19640b57cec5SDimitry Andric // After predicating BBI1, if there is a predicated terminator in BBI1 and
19650b57cec5SDimitry Andric // a non-predicated in BBI2, then we don't want to predicate the one from
19660b57cec5SDimitry Andric // BBI2. The reason is that if we merged these blocks, we would end up with
19670b57cec5SDimitry Andric // two predicated terminators in the same block.
19680b57cec5SDimitry Andric // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
19690b57cec5SDimitry Andric // predicate them either. They were checked to be identical, and so the
19700b57cec5SDimitry Andric // same branch would happen regardless of which path was taken.
19710b57cec5SDimitry Andric if (!MBB2.empty() && (DI2 == MBB2.end())) {
19720b57cec5SDimitry Andric MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
19730b57cec5SDimitry Andric MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
19740b57cec5SDimitry Andric bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
19750b57cec5SDimitry Andric bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
19760b57cec5SDimitry Andric if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
19770b57cec5SDimitry Andric --DI2;
19780b57cec5SDimitry Andric }
19790b57cec5SDimitry Andric
19800b57cec5SDimitry Andric // Predicate the 'false' block.
19810b57cec5SDimitry Andric PredicateBlock(*BBI2, DI2, *Cond2);
19820b57cec5SDimitry Andric
19830b57cec5SDimitry Andric // Merge the true block into the entry of the diamond.
19840b57cec5SDimitry Andric MergeBlocks(BBI, *BBI1, MergeAddEdges);
19850b57cec5SDimitry Andric MergeBlocks(BBI, *BBI2, MergeAddEdges);
19860b57cec5SDimitry Andric return true;
19870b57cec5SDimitry Andric }
19880b57cec5SDimitry Andric
19890b57cec5SDimitry Andric /// If convert an almost-diamond sub-CFG where the true
19900b57cec5SDimitry Andric /// and false blocks share a common tail.
IfConvertForkedDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)19910b57cec5SDimitry Andric bool IfConverter::IfConvertForkedDiamond(
19920b57cec5SDimitry Andric BBInfo &BBI, IfcvtKind Kind,
19930b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
19940b57cec5SDimitry Andric bool TClobbersPred, bool FClobbersPred) {
19950b57cec5SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
19960b57cec5SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
19970b57cec5SDimitry Andric
19980b57cec5SDimitry Andric // Save the debug location for later.
19990b57cec5SDimitry Andric DebugLoc dl;
20000b57cec5SDimitry Andric MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
20010b57cec5SDimitry Andric if (TIE != TrueBBI.BB->end())
20020b57cec5SDimitry Andric dl = TIE->getDebugLoc();
20030b57cec5SDimitry Andric // Removing branches from both blocks is safe, because we have already
20040b57cec5SDimitry Andric // determined that both blocks have the same branch instructions. The branch
20050b57cec5SDimitry Andric // will be added back at the end, unpredicated.
20060b57cec5SDimitry Andric if (!IfConvertDiamondCommon(
20070b57cec5SDimitry Andric BBI, TrueBBI, FalseBBI,
20080b57cec5SDimitry Andric NumDups1, NumDups2,
20090b57cec5SDimitry Andric TClobbersPred, FClobbersPred,
20100b57cec5SDimitry Andric /* RemoveBranch */ true, /* MergeAddEdges */ true))
20110b57cec5SDimitry Andric return false;
20120b57cec5SDimitry Andric
20130b57cec5SDimitry Andric // Add back the branch.
20140b57cec5SDimitry Andric // Debug location saved above when removing the branch from BBI2
20150b57cec5SDimitry Andric TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
20160b57cec5SDimitry Andric TrueBBI.BrCond, dl);
20170b57cec5SDimitry Andric
20180b57cec5SDimitry Andric // Update block info.
20190b57cec5SDimitry Andric BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
20200b57cec5SDimitry Andric InvalidatePreds(*BBI.BB);
20210b57cec5SDimitry Andric
20220b57cec5SDimitry Andric // FIXME: Must maintain LiveIns.
20230b57cec5SDimitry Andric return true;
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric
20260b57cec5SDimitry Andric /// If convert a diamond sub-CFG.
IfConvertDiamond(BBInfo & BBI,IfcvtKind Kind,unsigned NumDups1,unsigned NumDups2,bool TClobbersPred,bool FClobbersPred)20270b57cec5SDimitry Andric bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
20280b57cec5SDimitry Andric unsigned NumDups1, unsigned NumDups2,
20290b57cec5SDimitry Andric bool TClobbersPred, bool FClobbersPred) {
20300b57cec5SDimitry Andric BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
20310b57cec5SDimitry Andric BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
20320b57cec5SDimitry Andric MachineBasicBlock *TailBB = TrueBBI.TrueBB;
20330b57cec5SDimitry Andric
20340b57cec5SDimitry Andric // True block must fall through or end with an unanalyzable terminator.
20350b57cec5SDimitry Andric if (!TailBB) {
20360b57cec5SDimitry Andric if (blockAlwaysFallThrough(TrueBBI))
20370b57cec5SDimitry Andric TailBB = FalseBBI.TrueBB;
20380b57cec5SDimitry Andric assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
20390b57cec5SDimitry Andric }
20400b57cec5SDimitry Andric
20410b57cec5SDimitry Andric if (!IfConvertDiamondCommon(
20420b57cec5SDimitry Andric BBI, TrueBBI, FalseBBI,
20430b57cec5SDimitry Andric NumDups1, NumDups2,
20440b57cec5SDimitry Andric TClobbersPred, FClobbersPred,
20450b57cec5SDimitry Andric /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
20460b57cec5SDimitry Andric /* MergeAddEdges */ TailBB == nullptr))
20470b57cec5SDimitry Andric return false;
20480b57cec5SDimitry Andric
20490b57cec5SDimitry Andric // If the if-converted block falls through or unconditionally branches into
20500b57cec5SDimitry Andric // the tail block, and the tail block does not have other predecessors, then
20510b57cec5SDimitry Andric // fold the tail block in as well. Otherwise, unless it falls through to the
20520b57cec5SDimitry Andric // tail, add a unconditional branch to it.
20530b57cec5SDimitry Andric if (TailBB) {
20540b57cec5SDimitry Andric // We need to remove the edges to the true and false blocks manually since
20550b57cec5SDimitry Andric // we didn't let IfConvertDiamondCommon update the CFG.
20560b57cec5SDimitry Andric BBI.BB->removeSuccessor(TrueBBI.BB);
20570b57cec5SDimitry Andric BBI.BB->removeSuccessor(FalseBBI.BB, true);
20580b57cec5SDimitry Andric
20590b57cec5SDimitry Andric BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
20600b57cec5SDimitry Andric bool CanMergeTail = !TailBBI.HasFallThrough &&
20610b57cec5SDimitry Andric !TailBBI.BB->hasAddressTaken();
20620b57cec5SDimitry Andric // The if-converted block can still have a predicated terminator
20630b57cec5SDimitry Andric // (e.g. a predicated return). If that is the case, we cannot merge
20640b57cec5SDimitry Andric // it with the tail block.
20650b57cec5SDimitry Andric MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
20660b57cec5SDimitry Andric if (TI != BBI.BB->end() && TII->isPredicated(*TI))
20670b57cec5SDimitry Andric CanMergeTail = false;
20680b57cec5SDimitry Andric // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
20690b57cec5SDimitry Andric // check if there are any other predecessors besides those.
20700b57cec5SDimitry Andric unsigned NumPreds = TailBB->pred_size();
20710b57cec5SDimitry Andric if (NumPreds > 1)
20720b57cec5SDimitry Andric CanMergeTail = false;
20730b57cec5SDimitry Andric else if (NumPreds == 1 && CanMergeTail) {
20740b57cec5SDimitry Andric MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
20750b57cec5SDimitry Andric if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
20760b57cec5SDimitry Andric CanMergeTail = false;
20770b57cec5SDimitry Andric }
20780b57cec5SDimitry Andric if (CanMergeTail) {
20790b57cec5SDimitry Andric MergeBlocks(BBI, TailBBI);
20800b57cec5SDimitry Andric TailBBI.IsDone = true;
20810b57cec5SDimitry Andric } else {
20820b57cec5SDimitry Andric BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
20830b57cec5SDimitry Andric InsertUncondBranch(*BBI.BB, *TailBB, TII);
20840b57cec5SDimitry Andric BBI.HasFallThrough = false;
20850b57cec5SDimitry Andric }
20860b57cec5SDimitry Andric }
20870b57cec5SDimitry Andric
20880b57cec5SDimitry Andric // Update block info.
20890b57cec5SDimitry Andric BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
20900b57cec5SDimitry Andric InvalidatePreds(*BBI.BB);
20910b57cec5SDimitry Andric
20920b57cec5SDimitry Andric // FIXME: Must maintain LiveIns.
20930b57cec5SDimitry Andric return true;
20940b57cec5SDimitry Andric }
20950b57cec5SDimitry Andric
MaySpeculate(const MachineInstr & MI,SmallSet<MCPhysReg,4> & LaterRedefs)20960b57cec5SDimitry Andric static bool MaySpeculate(const MachineInstr &MI,
20970b57cec5SDimitry Andric SmallSet<MCPhysReg, 4> &LaterRedefs) {
20980b57cec5SDimitry Andric bool SawStore = true;
20990b57cec5SDimitry Andric if (!MI.isSafeToMove(nullptr, SawStore))
21000b57cec5SDimitry Andric return false;
21010b57cec5SDimitry Andric
21020b57cec5SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
21030b57cec5SDimitry Andric if (!MO.isReg())
21040b57cec5SDimitry Andric continue;
21058bcb0991SDimitry Andric Register Reg = MO.getReg();
21060b57cec5SDimitry Andric if (!Reg)
21070b57cec5SDimitry Andric continue;
21080b57cec5SDimitry Andric if (MO.isDef() && !LaterRedefs.count(Reg))
21090b57cec5SDimitry Andric return false;
21100b57cec5SDimitry Andric }
21110b57cec5SDimitry Andric
21120b57cec5SDimitry Andric return true;
21130b57cec5SDimitry Andric }
21140b57cec5SDimitry Andric
21150b57cec5SDimitry Andric /// Predicate instructions from the start of the block to the specified end with
21160b57cec5SDimitry Andric /// the specified condition.
PredicateBlock(BBInfo & BBI,MachineBasicBlock::iterator E,SmallVectorImpl<MachineOperand> & Cond,SmallSet<MCPhysReg,4> * LaterRedefs)21170b57cec5SDimitry Andric void IfConverter::PredicateBlock(BBInfo &BBI,
21180b57cec5SDimitry Andric MachineBasicBlock::iterator E,
21190b57cec5SDimitry Andric SmallVectorImpl<MachineOperand> &Cond,
21200b57cec5SDimitry Andric SmallSet<MCPhysReg, 4> *LaterRedefs) {
21210b57cec5SDimitry Andric bool AnyUnpred = false;
21220b57cec5SDimitry Andric bool MaySpec = LaterRedefs != nullptr;
21230b57cec5SDimitry Andric for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
21240b57cec5SDimitry Andric if (I.isDebugInstr() || TII->isPredicated(I))
21250b57cec5SDimitry Andric continue;
21260b57cec5SDimitry Andric // It may be possible not to predicate an instruction if it's the 'true'
21270b57cec5SDimitry Andric // side of a diamond and the 'false' side may re-define the instruction's
21280b57cec5SDimitry Andric // defs.
21290b57cec5SDimitry Andric if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
21300b57cec5SDimitry Andric AnyUnpred = true;
21310b57cec5SDimitry Andric continue;
21320b57cec5SDimitry Andric }
21330b57cec5SDimitry Andric // If any instruction is predicated, then every instruction after it must
21340b57cec5SDimitry Andric // be predicated.
21350b57cec5SDimitry Andric MaySpec = false;
21360b57cec5SDimitry Andric if (!TII->PredicateInstruction(I, Cond)) {
21370b57cec5SDimitry Andric #ifndef NDEBUG
21380b57cec5SDimitry Andric dbgs() << "Unable to predicate " << I << "!\n";
21390b57cec5SDimitry Andric #endif
21400b57cec5SDimitry Andric llvm_unreachable(nullptr);
21410b57cec5SDimitry Andric }
21420b57cec5SDimitry Andric
21430b57cec5SDimitry Andric // If the predicated instruction now redefines a register as the result of
21440b57cec5SDimitry Andric // if-conversion, add an implicit kill.
21450b57cec5SDimitry Andric UpdatePredRedefs(I, Redefs);
21460b57cec5SDimitry Andric }
21470b57cec5SDimitry Andric
21480b57cec5SDimitry Andric BBI.Predicate.append(Cond.begin(), Cond.end());
21490b57cec5SDimitry Andric
21500b57cec5SDimitry Andric BBI.IsAnalyzed = false;
21510b57cec5SDimitry Andric BBI.NonPredSize = 0;
21520b57cec5SDimitry Andric
21530b57cec5SDimitry Andric ++NumIfConvBBs;
21540b57cec5SDimitry Andric if (AnyUnpred)
21550b57cec5SDimitry Andric ++NumUnpred;
21560b57cec5SDimitry Andric }
21570b57cec5SDimitry Andric
21580b57cec5SDimitry Andric /// Copy and predicate instructions from source BB to the destination block.
21590b57cec5SDimitry Andric /// Skip end of block branches if IgnoreBr is true.
CopyAndPredicateBlock(BBInfo & ToBBI,BBInfo & FromBBI,SmallVectorImpl<MachineOperand> & Cond,bool IgnoreBr)21600b57cec5SDimitry Andric void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
21610b57cec5SDimitry Andric SmallVectorImpl<MachineOperand> &Cond,
21620b57cec5SDimitry Andric bool IgnoreBr) {
21630b57cec5SDimitry Andric MachineFunction &MF = *ToBBI.BB->getParent();
21640b57cec5SDimitry Andric
21650b57cec5SDimitry Andric MachineBasicBlock &FromMBB = *FromBBI.BB;
21660b57cec5SDimitry Andric for (MachineInstr &I : FromMBB) {
21670b57cec5SDimitry Andric // Do not copy the end of the block branches.
21680b57cec5SDimitry Andric if (IgnoreBr && I.isBranch())
21690b57cec5SDimitry Andric break;
21700b57cec5SDimitry Andric
21710b57cec5SDimitry Andric MachineInstr *MI = MF.CloneMachineInstr(&I);
21728bcb0991SDimitry Andric // Make a copy of the call site info.
21735ffd83dbSDimitry Andric if (I.isCandidateForCallSiteEntry())
21748bcb0991SDimitry Andric MF.copyCallSiteInfo(&I, MI);
21758bcb0991SDimitry Andric
21760b57cec5SDimitry Andric ToBBI.BB->insert(ToBBI.BB->end(), MI);
21770b57cec5SDimitry Andric ToBBI.NonPredSize++;
21780b57cec5SDimitry Andric unsigned ExtraPredCost = TII->getPredicationCost(I);
21790b57cec5SDimitry Andric unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
21800b57cec5SDimitry Andric if (NumCycles > 1)
21810b57cec5SDimitry Andric ToBBI.ExtraCost += NumCycles-1;
21820b57cec5SDimitry Andric ToBBI.ExtraCost2 += ExtraPredCost;
21830b57cec5SDimitry Andric
21840b57cec5SDimitry Andric if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
21850b57cec5SDimitry Andric if (!TII->PredicateInstruction(*MI, Cond)) {
21860b57cec5SDimitry Andric #ifndef NDEBUG
21870b57cec5SDimitry Andric dbgs() << "Unable to predicate " << I << "!\n";
21880b57cec5SDimitry Andric #endif
21890b57cec5SDimitry Andric llvm_unreachable(nullptr);
21900b57cec5SDimitry Andric }
21910b57cec5SDimitry Andric }
21920b57cec5SDimitry Andric
21930b57cec5SDimitry Andric // If the predicated instruction now redefines a register as the result of
21940b57cec5SDimitry Andric // if-conversion, add an implicit kill.
21950b57cec5SDimitry Andric UpdatePredRedefs(*MI, Redefs);
21960b57cec5SDimitry Andric }
21970b57cec5SDimitry Andric
21980b57cec5SDimitry Andric if (!IgnoreBr) {
21990b57cec5SDimitry Andric std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
22000b57cec5SDimitry Andric FromMBB.succ_end());
22010b57cec5SDimitry Andric MachineBasicBlock *NBB = getNextBlock(FromMBB);
22020b57cec5SDimitry Andric MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
22030b57cec5SDimitry Andric
22040b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Succs) {
22050b57cec5SDimitry Andric // Fallthrough edge can't be transferred.
22060b57cec5SDimitry Andric if (Succ == FallThrough)
22070b57cec5SDimitry Andric continue;
22080b57cec5SDimitry Andric ToBBI.BB->addSuccessor(Succ);
22090b57cec5SDimitry Andric }
22100b57cec5SDimitry Andric }
22110b57cec5SDimitry Andric
22120b57cec5SDimitry Andric ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
22130b57cec5SDimitry Andric ToBBI.Predicate.append(Cond.begin(), Cond.end());
22140b57cec5SDimitry Andric
22150b57cec5SDimitry Andric ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
22160b57cec5SDimitry Andric ToBBI.IsAnalyzed = false;
22170b57cec5SDimitry Andric
22180b57cec5SDimitry Andric ++NumDupBBs;
22190b57cec5SDimitry Andric }
22200b57cec5SDimitry Andric
22210b57cec5SDimitry Andric /// Move all instructions from FromBB to the end of ToBB. This will leave
22225ffd83dbSDimitry Andric /// FromBB as an empty block, so remove all of its successor edges and move it
22235ffd83dbSDimitry Andric /// to the end of the function. If AddEdges is true, i.e., when FromBBI's
22245ffd83dbSDimitry Andric /// branch is being moved, add those successor edges to ToBBI and remove the old
22255ffd83dbSDimitry Andric /// edge from ToBBI to FromBBI.
MergeBlocks(BBInfo & ToBBI,BBInfo & FromBBI,bool AddEdges)22260b57cec5SDimitry Andric void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
22270b57cec5SDimitry Andric MachineBasicBlock &FromMBB = *FromBBI.BB;
22280b57cec5SDimitry Andric assert(!FromMBB.hasAddressTaken() &&
22290b57cec5SDimitry Andric "Removing a BB whose address is taken!");
22300b57cec5SDimitry Andric
22311ac55f4cSDimitry Andric // If we're about to splice an INLINEASM_BR from FromBBI, we need to update
22321ac55f4cSDimitry Andric // ToBBI's successor list accordingly.
22331ac55f4cSDimitry Andric if (FromMBB.mayHaveInlineAsmBr())
22341ac55f4cSDimitry Andric for (MachineInstr &MI : FromMBB)
22351ac55f4cSDimitry Andric if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
22361ac55f4cSDimitry Andric for (MachineOperand &MO : MI.operands())
22371ac55f4cSDimitry Andric if (MO.isMBB() && !ToBBI.BB->isSuccessor(MO.getMBB()))
22381ac55f4cSDimitry Andric ToBBI.BB->addSuccessor(MO.getMBB(), BranchProbability::getZero());
22391ac55f4cSDimitry Andric
22400b57cec5SDimitry Andric // In case FromMBB contains terminators (e.g. return instruction),
22410b57cec5SDimitry Andric // first move the non-terminator instructions, then the terminators.
22420b57cec5SDimitry Andric MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
22430b57cec5SDimitry Andric MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
22440b57cec5SDimitry Andric ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
22450b57cec5SDimitry Andric
22460b57cec5SDimitry Andric // If FromBB has non-predicated terminator we should copy it at the end.
22470b57cec5SDimitry Andric if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
22480b57cec5SDimitry Andric ToTI = ToBBI.BB->end();
22490b57cec5SDimitry Andric ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
22500b57cec5SDimitry Andric
22510b57cec5SDimitry Andric // Force normalizing the successors' probabilities of ToBBI.BB to convert all
22520b57cec5SDimitry Andric // unknown probabilities into known ones.
22530b57cec5SDimitry Andric // FIXME: This usage is too tricky and in the future we would like to
22540b57cec5SDimitry Andric // eliminate all unknown probabilities in MBB.
22550b57cec5SDimitry Andric if (ToBBI.IsBrAnalyzable)
22560b57cec5SDimitry Andric ToBBI.BB->normalizeSuccProbs();
22570b57cec5SDimitry Andric
2258e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
22590b57cec5SDimitry Andric MachineBasicBlock *NBB = getNextBlock(FromMBB);
22600b57cec5SDimitry Andric MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
22610b57cec5SDimitry Andric // The edge probability from ToBBI.BB to FromMBB, which is only needed when
22620b57cec5SDimitry Andric // AddEdges is true and FromMBB is a successor of ToBBI.BB.
22630b57cec5SDimitry Andric auto To2FromProb = BranchProbability::getZero();
22640b57cec5SDimitry Andric if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
22650b57cec5SDimitry Andric // Remove the old edge but remember the edge probability so we can calculate
22660b57cec5SDimitry Andric // the correct weights on the new edges being added further down.
22670b57cec5SDimitry Andric To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
22680b57cec5SDimitry Andric ToBBI.BB->removeSuccessor(&FromMBB);
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric
22710b57cec5SDimitry Andric for (MachineBasicBlock *Succ : FromSuccs) {
22720b57cec5SDimitry Andric // Fallthrough edge can't be transferred.
22735ffd83dbSDimitry Andric if (Succ == FallThrough) {
22745ffd83dbSDimitry Andric FromMBB.removeSuccessor(Succ);
22750b57cec5SDimitry Andric continue;
22765ffd83dbSDimitry Andric }
22770b57cec5SDimitry Andric
22780b57cec5SDimitry Andric auto NewProb = BranchProbability::getZero();
22790b57cec5SDimitry Andric if (AddEdges) {
22800b57cec5SDimitry Andric // Calculate the edge probability for the edge from ToBBI.BB to Succ,
22810b57cec5SDimitry Andric // which is a portion of the edge probability from FromMBB to Succ. The
22820b57cec5SDimitry Andric // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
22830b57cec5SDimitry Andric // FromBBI is a successor of ToBBI.BB. See comment below for exception).
22840b57cec5SDimitry Andric NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
22850b57cec5SDimitry Andric
22860b57cec5SDimitry Andric // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
22870b57cec5SDimitry Andric // only happens when if-converting a diamond CFG and FromMBB is the
22880b57cec5SDimitry Andric // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
22890b57cec5SDimitry Andric // could just use the probabilities on FromMBB's out-edges when adding
22900b57cec5SDimitry Andric // new successors.
22910b57cec5SDimitry Andric if (!To2FromProb.isZero())
22920b57cec5SDimitry Andric NewProb *= To2FromProb;
22930b57cec5SDimitry Andric }
22940b57cec5SDimitry Andric
22950b57cec5SDimitry Andric FromMBB.removeSuccessor(Succ);
22960b57cec5SDimitry Andric
22970b57cec5SDimitry Andric if (AddEdges) {
22980b57cec5SDimitry Andric // If the edge from ToBBI.BB to Succ already exists, update the
22990b57cec5SDimitry Andric // probability of this edge by adding NewProb to it. An example is shown
23000b57cec5SDimitry Andric // below, in which A is ToBBI.BB and B is FromMBB. In this case we
23010b57cec5SDimitry Andric // don't have to set C as A's successor as it already is. We only need to
23020b57cec5SDimitry Andric // update the edge probability on A->C. Note that B will not be
23030b57cec5SDimitry Andric // immediately removed from A's successors. It is possible that B->D is
23040b57cec5SDimitry Andric // not removed either if D is a fallthrough of B. Later the edge A->D
23050b57cec5SDimitry Andric // (generated here) and B->D will be combined into one edge. To maintain
23060b57cec5SDimitry Andric // correct edge probability of this combined edge, we need to set the edge
23070b57cec5SDimitry Andric // probability of A->B to zero, which is already done above. The edge
23080b57cec5SDimitry Andric // probability on A->D is calculated by scaling the original probability
23090b57cec5SDimitry Andric // on A->B by the probability of B->D.
23100b57cec5SDimitry Andric //
23110b57cec5SDimitry Andric // Before ifcvt: After ifcvt (assume B->D is kept):
23120b57cec5SDimitry Andric //
23130b57cec5SDimitry Andric // A A
23140b57cec5SDimitry Andric // /| /|\
23150b57cec5SDimitry Andric // / B / B|
23160b57cec5SDimitry Andric // | /| | ||
23170b57cec5SDimitry Andric // |/ | | |/
23180b57cec5SDimitry Andric // C D C D
23190b57cec5SDimitry Andric //
23200b57cec5SDimitry Andric if (ToBBI.BB->isSuccessor(Succ))
23210b57cec5SDimitry Andric ToBBI.BB->setSuccProbability(
23220b57cec5SDimitry Andric find(ToBBI.BB->successors(), Succ),
23230b57cec5SDimitry Andric MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
23240b57cec5SDimitry Andric else
23250b57cec5SDimitry Andric ToBBI.BB->addSuccessor(Succ, NewProb);
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric }
23280b57cec5SDimitry Andric
23290b57cec5SDimitry Andric // Move the now empty FromMBB out of the way to the end of the function so
23300b57cec5SDimitry Andric // it doesn't interfere with fallthrough checks done by canFallThroughTo().
23310b57cec5SDimitry Andric MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
23320b57cec5SDimitry Andric if (Last != &FromMBB)
23330b57cec5SDimitry Andric FromMBB.moveAfter(Last);
23340b57cec5SDimitry Andric
23350b57cec5SDimitry Andric // Normalize the probabilities of ToBBI.BB's successors with all adjustment
23360b57cec5SDimitry Andric // we've done above.
23370b57cec5SDimitry Andric if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
23380b57cec5SDimitry Andric ToBBI.BB->normalizeSuccProbs();
23390b57cec5SDimitry Andric
23400b57cec5SDimitry Andric ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
23410b57cec5SDimitry Andric FromBBI.Predicate.clear();
23420b57cec5SDimitry Andric
23430b57cec5SDimitry Andric ToBBI.NonPredSize += FromBBI.NonPredSize;
23440b57cec5SDimitry Andric ToBBI.ExtraCost += FromBBI.ExtraCost;
23450b57cec5SDimitry Andric ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
23460b57cec5SDimitry Andric FromBBI.NonPredSize = 0;
23470b57cec5SDimitry Andric FromBBI.ExtraCost = 0;
23480b57cec5SDimitry Andric FromBBI.ExtraCost2 = 0;
23490b57cec5SDimitry Andric
23500b57cec5SDimitry Andric ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
23510b57cec5SDimitry Andric ToBBI.HasFallThrough = FromBBI.HasFallThrough;
23520b57cec5SDimitry Andric ToBBI.IsAnalyzed = false;
23530b57cec5SDimitry Andric FromBBI.IsAnalyzed = false;
23540b57cec5SDimitry Andric }
23550b57cec5SDimitry Andric
23560b57cec5SDimitry Andric FunctionPass *
createIfConverter(std::function<bool (const MachineFunction &)> Ftor)23570b57cec5SDimitry Andric llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
23580b57cec5SDimitry Andric return new IfConverter(std::move(Ftor));
23590b57cec5SDimitry Andric }
2360