blob: 567461c19452fb7a7f3125925fb0647b610535ab [file] [log] [blame]
Eugene Zelenkof1933322017-09-22 23:46:57 +00001//===- IfConversion.cpp - Machine code if conversion pass -----------------===//
Evan Chengf5e53a52007-05-16 02:00:57 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengf5e53a52007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
Justin Lebaracc47102016-04-01 01:09:03 +000010// This file implements the machine instruction level if-conversion pass, which
11// tries to convert conditional branches into predicated instructions.
Evan Chengf5e53a52007-05-16 02:00:57 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "BranchFolding.h"
16#include "llvm/ADT/STLExtras.h"
Kyle Buttd76755e2016-08-18 22:09:23 +000017#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/SparseSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Statistic.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000022#include "llvm/ADT/iterator_range.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000023#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000024#include "llvm/CodeGen/MachineBasicBlock.h"
Akira Hatanakabbd33f62014-08-07 19:30:13 +000025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakub Staszak3ef20e32011-08-03 22:53:41 +000026#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000027#include "llvm/CodeGen/MachineFunction.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000028#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000029#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenf623e982012-12-20 18:08:06 +000030#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000032#include "llvm/CodeGen/MachineOperand.h"
Evan Chengc5adcca2012-06-08 21:53:50 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000034#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetLowering.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000037#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000039#include "llvm/IR/DebugLoc.h"
40#include "llvm/MC/MCRegisterInfo.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/BranchProbability.h"
Evan Chenge93ccc02007-06-08 19:10:51 +000043#include "llvm/Support/CommandLine.h"
Evan Chengf5e53a52007-05-16 02:00:57 +000044#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000045#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/raw_ostream.h"
Cong Houd97c1002015-12-01 05:29:22 +000047#include <algorithm>
Eugene Zelenkof1933322017-09-22 23:46:57 +000048#include <cassert>
49#include <functional>
50#include <iterator>
51#include <memory>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000052#include <utility>
Eugene Zelenkof1933322017-09-22 23:46:57 +000053#include <vector>
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +000054
Evan Chengf5e53a52007-05-16 02:00:57 +000055using namespace llvm;
56
Matthias Braun1527baa2017-05-25 21:26:32 +000057#define DEBUG_TYPE "if-converter"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058
Chris Lattner769c86b2008-01-07 05:40:58 +000059// Hidden options for help debugging.
60static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
61static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
62static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000063static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattner769c86b2008-01-07 05:40:58 +000064 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000065static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000066 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000067static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattner769c86b2008-01-07 05:40:58 +000068 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000069static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000070 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000071static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattner769c86b2008-01-07 05:40:58 +000072 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000073static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattner769c86b2008-01-07 05:40:58 +000074 cl::init(false), cl::Hidden);
Bob Wilson81051442010-06-15 22:18:54 +000075static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattner769c86b2008-01-07 05:40:58 +000076 cl::init(false), cl::Hidden);
Kyle Butta8c73712016-08-24 21:34:27 +000077static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
78 cl::init(false), cl::Hidden);
Evan Chengf128bdc2010-06-16 07:35:02 +000079static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
80 cl::init(true), cl::Hidden);
Evan Chenge93ccc02007-06-08 19:10:51 +000081
Evan Cheng2117d1f2007-06-09 01:03:43 +000082STATISTIC(NumSimple, "Number of simple if-conversions performed");
83STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
84STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Cheng9acfa7b2007-06-12 23:54:05 +000085STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000086STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
87STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
88STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
Kyle Butta8c73712016-08-24 21:34:27 +000089STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
Evan Cheng2117d1f2007-06-09 01:03:43 +000090STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng92fb5452007-06-15 07:36:12 +000091STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4266a792011-12-19 22:01:30 +000092STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
Evan Chengf5e53a52007-05-16 02:00:57 +000093
94namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000095
Nick Lewycky02d5f772009-10-25 06:33:48 +000096 class IfConverter : public MachineFunctionPass {
Evan Cheng3a51c852007-06-16 09:34:52 +000097 enum IfcvtKind {
Evan Chengf5e53a52007-05-16 02:00:57 +000098 ICNotClassfied, // BB data valid, but not classified.
Evan Cheng312b7232007-06-04 06:47:22 +000099 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +0000100 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
101 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000102 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng2117d1f2007-06-09 01:03:43 +0000103 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Cheng3a51c852007-06-16 09:34:52 +0000104 ICTriangle, // BB is entry of a triangle sub-CFG.
Kyle Butta8c73712016-08-24 21:34:27 +0000105 ICDiamond, // BB is entry of a diamond sub-CFG.
106 ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
107 // common tail that can be shared.
Evan Chengf5e53a52007-05-16 02:00:57 +0000108 };
109
Matthias Braun2c931792016-08-17 02:51:57 +0000110 /// One per MachineBasicBlock, this is used to cache the result
Evan Chengf5e53a52007-05-16 02:00:57 +0000111 /// if-conversion feasibility analysis. This includes results from
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000112 /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng0f745da2007-05-18 00:20:58 +0000113 /// classification, and common tail block of its successors (if it's a
Evan Cheng2e82cef2007-05-18 18:14:37 +0000114 /// diamond shape), its size, whether it's predicable, and whether any
115 /// instruction can clobber the 'would-be' predicate.
Evan Chengd0e66912007-05-23 07:23:16 +0000116 ///
Evan Cheng4dd31a72007-06-11 22:26:22 +0000117 /// IsDone - True if BB is not to be considered for ifcvt.
118 /// IsBeingAnalyzed - True if BB is currently being analyzed.
119 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
120 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000121 /// IsBrAnalyzable - True if analyzeBranch() returns false.
Evan Cheng4dd31a72007-06-11 22:26:22 +0000122 /// HasFallThrough - True if BB may fallthrough to the following BB.
123 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Chengfbc73092007-07-10 17:50:43 +0000124 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng9030b982007-06-06 10:16:17 +0000125 /// cmp, call, etc.)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000126 /// NonPredSize - Number of non-predicated instructions.
Evan Chengdebf9c52010-11-03 00:45:17 +0000127 /// ExtraCost - Extra cost for multi-cycle instructions.
128 /// ExtraCost2 - Some instructions are slower when predicated
Evan Chengd0e66912007-05-23 07:23:16 +0000129 /// BB - Corresponding MachineBasicBlock.
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000130 /// TrueBB / FalseBB- See analyzeBranch().
Evan Chengd0e66912007-05-23 07:23:16 +0000131 /// BrCond - Conditions for end of block conditional branches.
132 /// Predicate - Predicate used in the BB.
Evan Chengf5e53a52007-05-16 02:00:57 +0000133 struct BBInfo {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000134 bool IsDone : 1;
135 bool IsBeingAnalyzed : 1;
136 bool IsAnalyzed : 1;
137 bool IsEnqueued : 1;
138 bool IsBrAnalyzable : 1;
Kyle Butta8c73712016-08-24 21:34:27 +0000139 bool IsBrReversible : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000140 bool HasFallThrough : 1;
141 bool IsUnpredicable : 1;
Evan Cheng23402fc2007-06-15 21:18:05 +0000142 bool CannotBeCopied : 1;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000143 bool ClobbersPred : 1;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000144 unsigned NonPredSize = 0;
145 unsigned ExtraCost = 0;
146 unsigned ExtraCost2 = 0;
147 MachineBasicBlock *BB = nullptr;
148 MachineBasicBlock *TrueBB = nullptr;
149 MachineBasicBlock *FalseBB = nullptr;
Owen Anderson4f6bf042008-08-14 22:49:33 +0000150 SmallVector<MachineOperand, 4> BrCond;
151 SmallVector<MachineOperand, 4> Predicate;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000152
Evan Cheng3a51c852007-06-16 09:34:52 +0000153 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng4dd31a72007-06-11 22:26:22 +0000154 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
Kyle Butta8c73712016-08-24 21:34:27 +0000155 IsBrReversible(false), HasFallThrough(false),
156 IsUnpredicable(false), CannotBeCopied(false),
Eugene Zelenkof1933322017-09-22 23:46:57 +0000157 ClobbersPred(false) {}
Evan Cheng3a51c852007-06-16 09:34:52 +0000158 };
159
Matthias Braun2c931792016-08-17 02:51:57 +0000160 /// Record information about pending if-conversions to attempt:
Evan Cheng3a51c852007-06-16 09:34:52 +0000161 /// BBI - Corresponding BBInfo.
162 /// Kind - Type of block. See IfcvtKind.
Bob Wilson2371f4f2009-05-13 23:25:24 +0000163 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Cheng3a51c852007-06-16 09:34:52 +0000164 /// predicated.
Evan Cheng51eb2c32007-06-18 08:37:25 +0000165 /// NumDups - Number of instructions that would be duplicated due
166 /// to this if-conversion. (For diamonds, the number of
167 /// identical instructions at the beginnings of both
168 /// paths).
169 /// NumDups2 - For diamonds, the number of identical instructions
170 /// at the ends of both paths.
Evan Cheng3a51c852007-06-16 09:34:52 +0000171 struct IfcvtToken {
172 BBInfo &BBI;
173 IfcvtKind Kind;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000174 unsigned NumDups;
175 unsigned NumDups2;
Kyle Butt6262ca32016-08-24 21:34:24 +0000176 bool NeedSubsumption : 1;
177 bool TClobbersPred : 1;
178 bool FClobbersPred : 1;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000179
Kyle Butt6262ca32016-08-24 21:34:24 +0000180 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
181 bool tc = false, bool fc = false)
182 : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
183 TClobbersPred(tc), FClobbersPred(fc) {}
Evan Chengf5e53a52007-05-16 02:00:57 +0000184 };
185
Matthias Braun2c931792016-08-17 02:51:57 +0000186 /// Results of if-conversion feasibility analysis indexed by basic block
187 /// number.
Evan Chengf5e53a52007-05-16 02:00:57 +0000188 std::vector<BBInfo> BBAnalysis;
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000189 TargetSchedModel SchedModel;
Evan Chengf5e53a52007-05-16 02:00:57 +0000190
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000191 const TargetLoweringBase *TLI;
Evan Chengf5e53a52007-05-16 02:00:57 +0000192 const TargetInstrInfo *TII;
Evan Chengf128bdc2010-06-16 07:35:02 +0000193 const TargetRegisterInfo *TRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000194 const MachineBranchProbabilityInfo *MBPI;
Evan Chengc5adcca2012-06-08 21:53:50 +0000195 MachineRegisterInfo *MRI;
Jakub Staszak15e5b742011-08-03 22:34:43 +0000196
Juergen Ributzka310034e2013-12-14 06:52:56 +0000197 LivePhysRegs Redefs;
Andrew Trick276dd452013-10-14 20:45:17 +0000198
Evan Chengc5adcca2012-06-08 21:53:50 +0000199 bool PreRegAlloc;
Evan Chengf5e53a52007-05-16 02:00:57 +0000200 bool MadeChange;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000201 int FnNum = -1;
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000202 std::function<bool(const MachineFunction &)> PredicateFtor;
Akira Hatanaka4a616192015-06-08 18:50:43 +0000203
Evan Chengf5e53a52007-05-16 02:00:57 +0000204 public:
205 static char ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000206
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000207 IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
Eugene Zelenkof1933322017-09-22 23:46:57 +0000208 : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000209 initializeIfConverterPass(*PassRegistry::getPassRegistry());
210 }
Jakub Staszak15e5b742011-08-03 22:34:43 +0000211
Craig Topper4584cd52014-03-07 09:26:03 +0000212 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanakabbd33f62014-08-07 19:30:13 +0000213 AU.addRequired<MachineBlockFrequencyInfo>();
Jakub Staszak15e5b742011-08-03 22:34:43 +0000214 AU.addRequired<MachineBranchProbabilityInfo>();
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000215 MachineFunctionPass::getAnalysisUsage(AU);
216 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000217
Craig Topper4584cd52014-03-07 09:26:03 +0000218 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Chengf5e53a52007-05-16 02:00:57 +0000219
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000220 MachineFunctionProperties getRequiredProperties() const override {
221 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000222 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000223 }
224
Evan Chengf5e53a52007-05-16 02:00:57 +0000225 private:
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000226 bool reverseBranchCondition(BBInfo &BBI) const;
Owen Andersonf31f33e2010-10-01 22:45:50 +0000227 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000228 BranchProbability Prediction) const;
Evan Cheng7783f822007-06-08 09:36:04 +0000229 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000230 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000231 BranchProbability Prediction) const;
Kyle Butt6262ca32016-08-24 21:34:24 +0000232 bool CountDuplicatedInstructions(
233 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
234 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
235 unsigned &Dups1, unsigned &Dups2,
236 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
237 bool SkipUnconditionalBranches) const;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000238 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
Kyle Butt6262ca32016-08-24 21:34:24 +0000239 unsigned &Dups1, unsigned &Dups2,
240 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butta8c73712016-08-24 21:34:27 +0000241 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
242 unsigned &Dups1, unsigned &Dups2,
243 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000244 void AnalyzeBranches(BBInfo &BBI);
245 void ScanInstructions(BBInfo &BBI,
246 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000247 MachineBasicBlock::iterator &End,
248 bool BranchUnpredicable = false) const;
249 bool RescanInstructions(
250 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
251 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
252 BBInfo &TrueBBI, BBInfo &FalseBBI) const;
Matthias Braun08f47042016-08-17 02:52:01 +0000253 void AnalyzeBlock(MachineBasicBlock &MBB,
Justin Lebar3a7bc572016-02-22 17:51:28 +0000254 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Owen Anderson4f6bf042008-08-14 22:49:33 +0000255 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Kyle Butt6262ca32016-08-24 21:34:24 +0000256 bool isTriangle = false, bool RevBranch = false,
257 bool hasCommonTail = false);
Justin Lebar3a7bc572016-02-22 17:51:28 +0000258 void AnalyzeBlocks(MachineFunction &MF,
259 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
Matthias Braun08f47042016-08-17 02:52:01 +0000260 void InvalidatePreds(MachineBasicBlock &MBB);
Evan Cheng3a51c852007-06-16 09:34:52 +0000261 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
262 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Kyle Butta8c73712016-08-24 21:34:27 +0000263 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
264 unsigned NumDups1, unsigned NumDups2,
265 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +0000266 bool RemoveBranch, bool MergeAddEdges);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000267 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
Kyle Butt6262ca32016-08-24 21:34:24 +0000268 unsigned NumDups1, unsigned NumDups2,
269 bool TClobbers, bool FClobbers);
Kyle Butta8c73712016-08-24 21:34:27 +0000270 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
271 unsigned NumDups1, unsigned NumDups2,
272 bool TClobbers, bool FClobbers);
Evan Chengd0e66912007-05-23 07:23:16 +0000273 void PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +0000274 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +0000275 SmallVectorImpl<MachineOperand> &Cond,
Craig Topperc0196b12014-04-14 00:51:57 +0000276 SmallSet<unsigned, 4> *LaterRedefs = nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +0000277 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +0000278 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +0000279 bool IgnoreBr = false);
Bob Wilson1e5da552010-06-29 00:55:23 +0000280 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng20e05992007-06-01 00:12:12 +0000281
Evan Chengdebf9c52010-11-03 00:45:17 +0000282 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
283 unsigned Cycle, unsigned Extra,
Cong Houc536bd92015-09-10 23:10:42 +0000284 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000285 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000286 Prediction);
Evan Cheng02b184d2010-06-25 22:42:03 +0000287 }
288
Evan Chengdebf9c52010-11-03 00:45:17 +0000289 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
290 unsigned TCycle, unsigned TExtra,
291 MachineBasicBlock &FBB,
292 unsigned FCycle, unsigned FExtra,
Cong Houc536bd92015-09-10 23:10:42 +0000293 BranchProbability Prediction) const {
Evan Chengdebf9c52010-11-03 00:45:17 +0000294 return TCycle > 0 && FCycle > 0 &&
295 TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000296 Prediction);
Evan Cheng51eb2c32007-06-18 08:37:25 +0000297 }
298
Matthias Braun2c931792016-08-17 02:51:57 +0000299 /// Returns true if Block ends without a terminator.
Evan Chengbe9859e2007-06-07 02:12:15 +0000300 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000301 return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
Evan Cheng9030b982007-06-06 10:16:17 +0000302 }
303
Matthias Braun2c931792016-08-17 02:51:57 +0000304 /// Used to sort if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +0000305 static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
306 const std::unique_ptr<IfcvtToken> &C2) {
Evan Cheng51eb2c32007-06-18 08:37:25 +0000307 int Incr1 = (C1->Kind == ICDiamond)
308 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
309 int Incr2 = (C2->Kind == ICDiamond)
310 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
311 if (Incr1 > Incr2)
Evan Cheng3a51c852007-06-16 09:34:52 +0000312 return true;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000313 else if (Incr1 == Incr2) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000314 // Favors subsumption.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000315 if (!C1->NeedSubsumption && C2->NeedSubsumption)
Evan Cheng3a51c852007-06-16 09:34:52 +0000316 return true;
Bob Wilson2371f4f2009-05-13 23:25:24 +0000317 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Cheng3a51c852007-06-16 09:34:52 +0000318 // Favors diamond over triangle, etc.
319 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
320 return true;
321 else if (C1->Kind == C2->Kind)
322 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
323 }
324 }
325 return false;
Evan Cheng20e05992007-06-01 00:12:12 +0000326 }
Evan Chengf5e53a52007-05-16 02:00:57 +0000327 };
Evan Cheng3a51c852007-06-16 09:34:52 +0000328
Eugene Zelenkof1933322017-09-22 23:46:57 +0000329} // end anonymous namespace
330
331char IfConverter::ID = 0;
Evan Chengf5e53a52007-05-16 02:00:57 +0000332
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000333char &llvm::IfConverterID = IfConverter::ID;
334
Matthias Braun1527baa2017-05-25 21:26:32 +0000335INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Jakub Staszak15e5b742011-08-03 22:34:43 +0000336INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000337INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
Bob Wilson97b93122009-10-28 20:46:46 +0000338
Evan Chengf5e53a52007-05-16 02:00:57 +0000339bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Matthias Braun8b38ffa2016-10-24 23:23:02 +0000340 if (skipFunction(*MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
Akira Hatanaka4a616192015-06-08 18:50:43 +0000341 return false;
342
Eric Christopher3d4276f2015-01-27 07:31:29 +0000343 const TargetSubtargetInfo &ST = MF.getSubtarget();
344 TLI = ST.getTargetLowering();
345 TII = ST.getInstrInfo();
346 TRI = ST.getRegisterInfo();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000347 BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
Jakub Staszak15e5b742011-08-03 22:34:43 +0000348 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Evan Chengc5adcca2012-06-08 21:53:50 +0000349 MRI = &MF.getRegInfo();
Pete Cooper11759452014-09-02 17:43:54 +0000350 SchedModel.init(ST.getSchedModel(), &ST, TII);
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000351
Evan Chengf5e53a52007-05-16 02:00:57 +0000352 if (!TII) return false;
353
Evan Chengc5adcca2012-06-08 21:53:50 +0000354 PreRegAlloc = MRI->isSSA();
355
356 bool BFChange = false;
357 if (!PreRegAlloc) {
358 // Tail merge tend to expose more if-conversion opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000359 BranchFolder BF(true, false, MBFI, *MBPI);
Eric Christopher3d4276f2015-01-27 07:31:29 +0000360 BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
Eric Christopherfc6de422014-08-05 02:39:49 +0000361 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Chengc5adcca2012-06-08 21:53:50 +0000362 }
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000363
David Greene72e47cd2010-01-04 22:02:01 +0000364 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Craig Toppera538d832012-08-22 06:07:19 +0000365 << MF.getName() << "\'");
Evan Chenge93ccc02007-06-08 19:10:51 +0000366
367 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene72e47cd2010-01-04 22:02:01 +0000368 DEBUG(dbgs() << " skipped\n");
Evan Chenge93ccc02007-06-08 19:10:51 +0000369 return false;
370 }
David Greene72e47cd2010-01-04 22:02:01 +0000371 DEBUG(dbgs() << "\n");
Evan Cheng20e05992007-06-01 00:12:12 +0000372
Evan Chengf5e53a52007-05-16 02:00:57 +0000373 MF.RenumberBlocks();
Evan Cheng20e05992007-06-01 00:12:12 +0000374 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Chengf5e53a52007-05-16 02:00:57 +0000375
Justin Lebar3a7bc572016-02-22 17:51:28 +0000376 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
Evan Cheng478b8052007-05-18 01:55:58 +0000377 MadeChange = false;
Evan Cheng92fb5452007-06-15 07:36:12 +0000378 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
379 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
380 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson2371f4f2009-05-13 23:25:24 +0000381 // Do an initial analysis for each basic block and find all the potential
382 // candidates to perform if-conversion.
Bob Wilsonfc7d7392010-06-15 18:57:15 +0000383 bool Change = false;
384 AnalyzeBlocks(MF, Tokens);
Evan Cheng3a51c852007-06-16 09:34:52 +0000385 while (!Tokens.empty()) {
Justin Lebar3a7bc572016-02-22 17:51:28 +0000386 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Evan Cheng3a51c852007-06-16 09:34:52 +0000387 Tokens.pop_back();
388 BBInfo &BBI = Token->BBI;
389 IfcvtKind Kind = Token->Kind;
Nuno Lopes57c65942008-11-04 13:02:59 +0000390 unsigned NumDups = Token->NumDups;
Duncan Sandsdd571d32008-11-04 18:05:30 +0000391 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes57c65942008-11-04 13:02:59 +0000392
Evan Cheng4dd31a72007-06-11 22:26:22 +0000393 // If the block has been evicted out of the queue or it has already been
394 // marked dead (due to it being predicated), then skip it.
Evan Cheng3a51c852007-06-16 09:34:52 +0000395 if (BBI.IsDone)
396 BBI.IsEnqueued = false;
397 if (!BBI.IsEnqueued)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000398 continue;
Evan Cheng3a51c852007-06-16 09:34:52 +0000399
Evan Cheng1e6f08b2007-06-14 20:28:52 +0000400 BBI.IsEnqueued = false;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000401
Evan Cheng312b7232007-06-04 06:47:22 +0000402 bool RetVal = false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000403 switch (Kind) {
Craig Topperee4dab52012-02-05 08:31:47 +0000404 default: llvm_unreachable("Unexpected!");
Evan Cheng312b7232007-06-04 06:47:22 +0000405 case ICSimple:
Evan Chengb30a8942007-06-06 01:12:44 +0000406 case ICSimpleFalse: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000407 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000408 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson81051442010-06-15 22:18:54 +0000409 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
410 " false" : "")
Bill Wendlingfb363162009-08-22 20:11:17 +0000411 << "): BB#" << BBI.BB->getNumber() << " ("
412 << ((Kind == ICSimpleFalse)
413 ? BBI.FalseBB->getNumber()
414 : BBI.TrueBB->getNumber()) << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000415 RetVal = IfConvertSimple(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000416 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000417 if (RetVal) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000418 if (isFalse) ++NumSimpleFalse;
419 else ++NumSimple;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +0000420 }
Evan Cheng312b7232007-06-04 06:47:22 +0000421 break;
Evan Chengb30a8942007-06-06 01:12:44 +0000422 }
Evan Chengd0e66912007-05-23 07:23:16 +0000423 case ICTriangle:
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000424 case ICTriangleRev:
Evan Cheng2117d1f2007-06-09 01:03:43 +0000425 case ICTriangleFalse:
Reid Spencer14b62a52007-06-10 00:19:17 +0000426 case ICTriangleFRev: {
Evan Cheng3a51c852007-06-16 09:34:52 +0000427 bool isFalse = Kind == ICTriangleFalse;
428 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000429 if (DisableTriangle && !isFalse && !isRev) break;
430 if (DisableTriangleR && !isFalse && isRev) break;
431 if (DisableTriangleF && isFalse && !isRev) break;
432 if (DisableTriangleFR && isFalse && isRev) break;
David Greene72e47cd2010-01-04 22:02:01 +0000433 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000434 if (isFalse)
David Greene72e47cd2010-01-04 22:02:01 +0000435 DEBUG(dbgs() << " false");
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000436 if (isRev)
David Greene72e47cd2010-01-04 22:02:01 +0000437 DEBUG(dbgs() << " rev");
438 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000439 << BBI.TrueBB->getNumber() << ",F:"
440 << BBI.FalseBB->getNumber() << ") ");
Evan Cheng3a51c852007-06-16 09:34:52 +0000441 RetVal = IfConvertTriangle(BBI, Kind);
David Greene72e47cd2010-01-04 22:02:01 +0000442 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng2117d1f2007-06-09 01:03:43 +0000443 if (RetVal) {
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000444 if (isFalse) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000445 if (isRev) ++NumTriangleFRev;
446 else ++NumTriangleFalse;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000447 } else {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000448 if (isRev) ++NumTriangleRev;
449 else ++NumTriangle;
Evan Cheng9acfa7b2007-06-12 23:54:05 +0000450 }
Evan Cheng2117d1f2007-06-09 01:03:43 +0000451 }
Evan Chengd0e66912007-05-23 07:23:16 +0000452 break;
Reid Spencer14b62a52007-06-10 00:19:17 +0000453 }
Eugene Zelenkof1933322017-09-22 23:46:57 +0000454 case ICDiamond:
Evan Chenge93ccc02007-06-08 19:10:51 +0000455 if (DisableDiamond) break;
David Greene72e47cd2010-01-04 22:02:01 +0000456 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendlingfb363162009-08-22 20:11:17 +0000457 << BBI.TrueBB->getNumber() << ",F:"
458 << BBI.FalseBB->getNumber() << ") ");
Kyle Butt6262ca32016-08-24 21:34:24 +0000459 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
460 Token->TClobbersPred,
461 Token->FClobbersPred);
David Greene72e47cd2010-01-04 22:02:01 +0000462 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000463 if (RetVal) ++NumDiamonds;
Evan Chengd0e66912007-05-23 07:23:16 +0000464 break;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000465 case ICForkedDiamond:
Kyle Butta8c73712016-08-24 21:34:27 +0000466 if (DisableForkedDiamond) break;
467 DEBUG(dbgs() << "Ifcvt (Forked Diamond): BB#"
468 << BBI.BB->getNumber() << " (T:"
469 << BBI.TrueBB->getNumber() << ",F:"
470 << BBI.FalseBB->getNumber() << ") ");
471 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
472 Token->TClobbersPred,
473 Token->FClobbersPred);
474 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
475 if (RetVal) ++NumForkedDiamonds;
476 break;
477 }
Evan Cheng3a51c852007-06-16 09:34:52 +0000478
Krzysztof Parzyszek6ca02b22017-09-14 15:53:11 +0000479 if (RetVal && MRI->tracksLiveness())
480 recomputeLivenessFlags(*BBI.BB);
481
Evan Cheng312b7232007-06-04 06:47:22 +0000482 Change |= RetVal;
Evan Chenge93ccc02007-06-08 19:10:51 +0000483
Evan Cheng92fb5452007-06-15 07:36:12 +0000484 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
485 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
486 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chenge93ccc02007-06-08 19:10:51 +0000487 break;
Evan Chengf5e53a52007-05-16 02:00:57 +0000488 }
Evan Chengd0e66912007-05-23 07:23:16 +0000489
Evan Chengd0e66912007-05-23 07:23:16 +0000490 if (!Change)
491 break;
Evan Cheng312b7232007-06-04 06:47:22 +0000492 MadeChange |= Change;
Evan Chengf5e53a52007-05-16 02:00:57 +0000493 }
Evan Cheng478b8052007-05-18 01:55:58 +0000494
Evan Cheng3a51c852007-06-16 09:34:52 +0000495 Tokens.clear();
Evan Cheng478b8052007-05-18 01:55:58 +0000496 BBAnalysis.clear();
497
Evan Chengcf9e8a92010-06-18 22:17:13 +0000498 if (MadeChange && IfCvtBranchFold) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000499 BranchFolder BF(false, false, MBFI, *MBPI);
Eric Christopherfc6de422014-08-05 02:39:49 +0000500 BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Evan Cheng3d2fce02009-09-04 07:47:40 +0000501 getAnalysisIfAvailable<MachineModuleInfo>());
502 }
503
Evan Cheng2d51c7c2010-06-18 23:09:54 +0000504 MadeChange |= BFChange;
Evan Chengf5e53a52007-05-16 02:00:57 +0000505 return MadeChange;
506}
507
Matthias Braun2c931792016-08-17 02:51:57 +0000508/// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
Evan Chengf5e53a52007-05-16 02:00:57 +0000509static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng0f745da2007-05-18 00:20:58 +0000510 MachineBasicBlock *TrueBB) {
Matthias Braunb1e05582016-08-17 02:51:59 +0000511 for (MachineBasicBlock *SuccBB : BB->successors()) {
Evan Cheng0f745da2007-05-18 00:20:58 +0000512 if (SuccBB != TrueBB)
Evan Chengf5e53a52007-05-16 02:00:57 +0000513 return SuccBB;
514 }
Craig Topperc0196b12014-04-14 00:51:57 +0000515 return nullptr;
Evan Chengf5e53a52007-05-16 02:00:57 +0000516}
517
Matthias Braun2c931792016-08-17 02:51:57 +0000518/// Reverse the condition of the end of the block branch. Swap block's 'true'
519/// and 'false' successors.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000520bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
Stuart Hastings0125b642010-06-17 22:43:56 +0000521 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000522 if (!TII->reverseBranchCondition(BBI.BrCond)) {
523 TII->removeBranch(*BBI.BB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000524 TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Cheng312b7232007-06-04 06:47:22 +0000525 std::swap(BBI.TrueBB, BBI.FalseBB);
526 return true;
527 }
528 return false;
529}
530
Matthias Braun2c931792016-08-17 02:51:57 +0000531/// Returns the next block in the function blocks ordering. If it is the end,
532/// returns NULL.
Matthias Braun08f47042016-08-17 02:52:01 +0000533static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
534 MachineFunction::iterator I = MBB.getIterator();
535 MachineFunction::iterator E = MBB.getParent()->end();
Evan Cheng2117d1f2007-06-09 01:03:43 +0000536 if (++I == E)
Craig Topperc0196b12014-04-14 00:51:57 +0000537 return nullptr;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000538 return &*I;
Evan Cheng2117d1f2007-06-09 01:03:43 +0000539}
540
Matthias Braun2c931792016-08-17 02:51:57 +0000541/// Returns true if the 'true' block (along with its predecessor) forms a valid
542/// simple shape for ifcvt. It also returns the number of instructions that the
543/// ifcvt would need to duplicate if performed in Dups.
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000544bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000545 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000546 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000547 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000548 return false;
549
Evan Chenga955c022007-06-19 21:45:13 +0000550 if (TrueBBI.IsBrAnalyzable)
551 return false;
552
Evan Cheng23402fc2007-06-15 21:18:05 +0000553 if (TrueBBI.BB->pred_size() > 1) {
554 if (TrueBBI.CannotBeCopied ||
Owen Anderson1b35f4c2010-09-28 20:42:15 +0000555 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000556 Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000557 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000558 Dups = TrueBBI.NonPredSize;
Evan Cheng92fb5452007-06-15 07:36:12 +0000559 }
560
Evan Chenga955c022007-06-19 21:45:13 +0000561 return true;
Evan Cheng9030b982007-06-06 10:16:17 +0000562}
563
Matthias Braun2c931792016-08-17 02:51:57 +0000564/// Returns true if the 'true' and 'false' blocks (along with their common
565/// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
566/// true, it checks if 'true' block's false branch branches to the 'false' block
567/// rather than the other way around. It also returns the number of instructions
568/// that the ifcvt would need to duplicate if performed in 'Dups'.
Evan Cheng7783f822007-06-08 09:36:04 +0000569bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersonf31f33e2010-10-01 22:45:50 +0000570 bool FalseBranch, unsigned &Dups,
Cong Houc536bd92015-09-10 23:10:42 +0000571 BranchProbability Prediction) const {
Evan Cheng3a51c852007-06-16 09:34:52 +0000572 Dups = 0;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000573 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng4dd31a72007-06-11 22:26:22 +0000574 return false;
575
Evan Cheng23402fc2007-06-15 21:18:05 +0000576 if (TrueBBI.BB->pred_size() > 1) {
577 if (TrueBBI.CannotBeCopied)
578 return false;
579
Evan Cheng92fb5452007-06-15 07:36:12 +0000580 unsigned Size = TrueBBI.NonPredSize;
Evan Cheng3a51c852007-06-16 09:34:52 +0000581 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman70de4cb2008-01-29 13:02:09 +0000582 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson2371f4f2009-05-13 23:25:24 +0000583 // Ends with an unconditional branch. It will be removed.
Evan Cheng3a51c852007-06-16 09:34:52 +0000584 --Size;
585 else {
586 MachineBasicBlock *FExit = FalseBranch
587 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
588 if (FExit)
589 // Require a conditional branch
590 ++Size;
591 }
592 }
Jakub Staszak9b07c0a2011-07-10 02:58:07 +0000593 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
Evan Cheng92fb5452007-06-15 07:36:12 +0000594 return false;
Evan Cheng3a51c852007-06-16 09:34:52 +0000595 Dups = Size;
Evan Cheng92fb5452007-06-15 07:36:12 +0000596 }
Evan Chengbe9859e2007-06-07 02:12:15 +0000597
Evan Cheng7783f822007-06-08 09:36:04 +0000598 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
599 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000600 MachineFunction::iterator I = TrueBBI.BB->getIterator();
Evan Chengbe9859e2007-06-07 02:12:15 +0000601 if (++I == TrueBBI.BB->getParent()->end())
602 return false;
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +0000603 TExit = &*I;
Evan Chengbe9859e2007-06-07 02:12:15 +0000604 }
Evan Cheng7783f822007-06-08 09:36:04 +0000605 return TExit && TExit == FalseBBI.BB;
Evan Chengbe9859e2007-06-07 02:12:15 +0000606}
607
Kyle Butt4f0e2872016-08-06 01:52:33 +0000608/// Count duplicated instructions and move the iterators to show where they
609/// are.
610/// @param TIB True Iterator Begin
611/// @param FIB False Iterator Begin
612/// These two iterators initially point to the first instruction of the two
613/// blocks, and finally point to the first non-shared instruction.
614/// @param TIE True Iterator End
615/// @param FIE False Iterator End
616/// These two iterators initially point to End() for the two blocks() and
617/// finally point to the first shared instruction in the tail.
618/// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
619/// two blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000620/// @param Dups1 count of duplicated instructions at the beginning of the 2
621/// blocks.
622/// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
623/// @param SkipUnconditionalBranches if true, Don't make sure that
624/// unconditional branches at the end of the blocks are the same. True is
625/// passed when the blocks are analyzable to allow for fallthrough to be
626/// handled.
627/// @return false if the shared portion prevents if conversion.
628bool IfConverter::CountDuplicatedInstructions(
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000629 MachineBasicBlock::iterator &TIB,
630 MachineBasicBlock::iterator &FIB,
631 MachineBasicBlock::iterator &TIE,
632 MachineBasicBlock::iterator &FIE,
633 unsigned &Dups1, unsigned &Dups2,
634 MachineBasicBlock &TBB, MachineBasicBlock &FBB,
Kyle Butt6262ca32016-08-24 21:34:24 +0000635 bool SkipUnconditionalBranches) const {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000636 while (TIB != TIE && FIB != FIE) {
Evan Chengc0e0d852010-06-18 21:52:57 +0000637 // Skip dbg_value instructions. These do not count.
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000638 TIB = skipDebugInstructionsForward(TIB, TIE);
Florian Hahn3c8b8c92016-12-16 11:10:26 +0000639 FIB = skipDebugInstructionsForward(FIB, FIE);
Kyle Buttc4614b32017-01-26 20:02:47 +0000640 if (TIB == TIE || FIB == FIE)
Kyle Buttfe916822016-08-06 01:52:31 +0000641 break;
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000642 if (!TIB->isIdenticalTo(*FIB))
Bob Wilsone1961fe2010-10-26 00:02:24 +0000643 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000644 // A pred-clobbering instruction in the shared portion prevents
645 // if-conversion.
646 std::vector<MachineOperand> PredDefs;
647 if (TII->DefinesPredicate(*TIB, PredDefs))
648 return false;
Kyle Butt93e94e82016-09-02 01:20:06 +0000649 // If we get all the way to the branch instructions, don't count them.
650 if (!TIB->isBranch())
651 ++Dups1;
Bob Wilsone1961fe2010-10-26 00:02:24 +0000652 ++TIB;
653 ++FIB;
654 }
655
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +0000656 // Check for already containing all of the block.
657 if (TIB == TIE || FIB == FIE)
Kyle Butt6262ca32016-08-24 21:34:24 +0000658 return true;
Kyle Buttd76755e2016-08-18 22:09:23 +0000659 // Now, in preparation for counting duplicate instructions at the ends of the
Kyle Buttc4614b32017-01-26 20:02:47 +0000660 // blocks, switch to reverse_iterators. Note that getReverse() returns an
661 // iterator that points to the same instruction, unlike std::reverse_iterator.
662 // We have to do our own shifting so that we get the same range.
663 MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
664 MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
665 const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
666 const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
Kyle Buttd76755e2016-08-18 22:09:23 +0000667
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000668 if (!TBB.succ_empty() || !FBB.succ_empty()) {
Kyle Butt6262ca32016-08-24 21:34:24 +0000669 if (SkipUnconditionalBranches) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000670 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
671 ++RTIE;
672 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
673 ++RFIE;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000674 }
Bob Wilsone1961fe2010-10-26 00:02:24 +0000675 }
676
Bob Wilsone1961fe2010-10-26 00:02:24 +0000677 // Count duplicate instructions at the ends of the blocks.
Kyle Buttc4614b32017-01-26 20:02:47 +0000678 while (RTIE != RTIB && RFIE != RFIB) {
Bob Wilsone1961fe2010-10-26 00:02:24 +0000679 // Skip dbg_value instructions. These do not count.
Kyle Buttc4614b32017-01-26 20:02:47 +0000680 // Note that these are reverse iterators going forward.
681 RTIE = skipDebugInstructionsForward(RTIE, RTIB);
682 RFIE = skipDebugInstructionsForward(RFIE, RFIB);
683 if (RTIE == RTIB || RFIE == RFIB)
Kyle Buttfe916822016-08-06 01:52:31 +0000684 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000685 if (!RTIE->isIdenticalTo(*RFIE))
Evan Cheng51eb2c32007-06-18 08:37:25 +0000686 break;
Kyle Butt6262ca32016-08-24 21:34:24 +0000687 // We have to verify that any branch instructions are the same, and then we
688 // don't count them toward the # of duplicate instructions.
Kyle Buttc4614b32017-01-26 20:02:47 +0000689 if (!RTIE->isBranch())
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000690 ++Dups2;
Kyle Buttc4614b32017-01-26 20:02:47 +0000691 ++RTIE;
692 ++RFIE;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000693 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000694 TIE = std::next(RTIE.getReverse());
695 FIE = std::next(RFIE.getReverse());
Kyle Butt6262ca32016-08-24 21:34:24 +0000696 return true;
697}
698
699/// RescanInstructions - Run ScanInstructions on a pair of blocks.
700/// @param TIB - True Iterator Begin, points to first non-shared instruction
701/// @param FIB - False Iterator Begin, points to first non-shared instruction
702/// @param TIE - True Iterator End, points past last non-shared instruction
703/// @param FIE - False Iterator End, points past last non-shared instruction
704/// @param TrueBBI - BBInfo to update for the true block.
705/// @param FalseBBI - BBInfo to update for the false block.
706/// @returns - false if either block cannot be predicated or if both blocks end
707/// with a predicate-clobbering instruction.
708bool IfConverter::RescanInstructions(
709 MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
710 MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
711 BBInfo &TrueBBI, BBInfo &FalseBBI) const {
712 bool BranchUnpredicable = true;
713 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
714 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
715 if (TrueBBI.IsUnpredicable)
716 return false;
717 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
718 if (FalseBBI.IsUnpredicable)
719 return false;
720 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
721 return false;
722 return true;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000723}
Evan Cheng51eb2c32007-06-18 08:37:25 +0000724
Kyle Butt092c4dd2016-08-29 18:27:12 +0000725#ifndef NDEBUG
726static void verifySameBranchInstructions(
727 MachineBasicBlock *MBB1,
728 MachineBasicBlock *MBB2) {
Kyle Buttc4614b32017-01-26 20:02:47 +0000729 const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
730 const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
731 MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
732 MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
733 while (E1 != B1 && E2 != B2) {
734 skipDebugInstructionsForward(E1, B1);
735 skipDebugInstructionsForward(E2, B2);
736 if (E1 == B1 && E2 == B2)
Kyle Butt092c4dd2016-08-29 18:27:12 +0000737 break;
738
Kyle Buttc4614b32017-01-26 20:02:47 +0000739 if (E1 == B1) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000740 assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
741 break;
742 }
Kyle Buttc4614b32017-01-26 20:02:47 +0000743 if (E2 == B2) {
Kyle Butt092c4dd2016-08-29 18:27:12 +0000744 assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
745 break;
746 }
747
748 if (E1->isBranch() || E2->isBranch())
749 assert(E1->isIdenticalTo(*E2) &&
750 "Branch mis-match, branch instructions don't match.");
751 else
752 break;
Kyle Buttc4614b32017-01-26 20:02:47 +0000753 ++E1;
754 ++E2;
Kyle Butt092c4dd2016-08-29 18:27:12 +0000755 }
756}
757#endif
758
Kyle Butta8c73712016-08-24 21:34:27 +0000759/// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
760/// with their common predecessor) form a diamond if a common tail block is
761/// extracted.
762/// While not strictly a diamond, this pattern would form a diamond if
763/// tail-merging had merged the shared tails.
764/// EBB
765/// _/ \_
766/// | |
767/// TBB FBB
768/// / \ / \
769/// FalseBB TrueBB FalseBB
770/// Currently only handles analyzable branches.
771/// Specifically excludes actual diamonds to avoid overlap.
772bool IfConverter::ValidForkedDiamond(
773 BBInfo &TrueBBI, BBInfo &FalseBBI,
774 unsigned &Dups1, unsigned &Dups2,
775 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
776 Dups1 = Dups2 = 0;
777 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
778 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
779 return false;
780
781 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
782 return false;
783 // Don't IfConvert blocks that can't be folded into their predecessor.
784 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
785 return false;
786
787 // This function is specifically looking for conditional tails, as
788 // unconditional tails are already handled by the standard diamond case.
789 if (TrueBBI.BrCond.size() == 0 ||
790 FalseBBI.BrCond.size() == 0)
791 return false;
792
793 MachineBasicBlock *TT = TrueBBI.TrueBB;
794 MachineBasicBlock *TF = TrueBBI.FalseBB;
795 MachineBasicBlock *FT = FalseBBI.TrueBB;
796 MachineBasicBlock *FF = FalseBBI.FalseBB;
797
798 if (!TT)
799 TT = getNextBlock(*TrueBBI.BB);
800 if (!TF)
801 TF = getNextBlock(*TrueBBI.BB);
802 if (!FT)
803 FT = getNextBlock(*FalseBBI.BB);
804 if (!FF)
805 FF = getNextBlock(*FalseBBI.BB);
806
807 if (!TT || !TF)
808 return false;
809
810 // Check successors. If they don't match, bail.
811 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
812 return false;
813
814 bool FalseReversed = false;
815 if (TF == FT && TT == FF) {
816 // If the branches are opposing, but we can't reverse, don't do it.
817 if (!FalseBBI.IsBrReversible)
818 return false;
819 FalseReversed = true;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000820 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000821 }
822 auto UnReverseOnExit = make_scope_exit([&]() {
823 if (FalseReversed)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000824 reverseBranchCondition(FalseBBI);
Kyle Butta8c73712016-08-24 21:34:27 +0000825 });
826
827 // Count duplicate instructions at the beginning of the true and false blocks.
828 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
829 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
830 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
831 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
832 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
833 *TrueBBI.BB, *FalseBBI.BB,
834 /* SkipUnconditionalBranches */ true))
835 return false;
836
837 TrueBBICalc.BB = TrueBBI.BB;
838 FalseBBICalc.BB = FalseBBI.BB;
839 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
840 return false;
841
842 // The size is used to decide whether to if-convert, and the shared portions
843 // are subtracted off. Because of the subtraction, we just use the size that
844 // was calculated by the original ScanInstructions, as it is correct.
845 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
846 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
847 return true;
848}
849
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000850/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
851/// with their common predecessor) forms a valid diamond shape for ifcvt.
Kyle Butt6262ca32016-08-24 21:34:24 +0000852bool IfConverter::ValidDiamond(
853 BBInfo &TrueBBI, BBInfo &FalseBBI,
854 unsigned &Dups1, unsigned &Dups2,
855 BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000856 Dups1 = Dups2 = 0;
857 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
858 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
859 return false;
860
861 MachineBasicBlock *TT = TrueBBI.TrueBB;
862 MachineBasicBlock *FT = FalseBBI.TrueBB;
863
864 if (!TT && blockAlwaysFallThrough(TrueBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000865 TT = getNextBlock(*TrueBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000866 if (!FT && blockAlwaysFallThrough(FalseBBI))
Matthias Braun08f47042016-08-17 02:52:01 +0000867 FT = getNextBlock(*FalseBBI.BB);
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000868 if (TT != FT)
869 return false;
870 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
871 return false;
872 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
873 return false;
874
875 // FIXME: Allow true block to have an early exit?
Kyle Butt6262ca32016-08-24 21:34:24 +0000876 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000877 return false;
878
879 // Count duplicate instructions at the beginning and end of the true and
880 // false blocks.
Kyle Butt6262ca32016-08-24 21:34:24 +0000881 // Skip unconditional branches only if we are considering an analyzable
882 // diamond. Otherwise the branches must be the same.
883 bool SkipUnconditionalBranches =
884 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
Kyle Butt9b6d99b2016-07-27 20:19:33 +0000885 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
886 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
887 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
888 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
Kyle Butt6262ca32016-08-24 21:34:24 +0000889 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
890 *TrueBBI.BB, *FalseBBI.BB,
891 SkipUnconditionalBranches))
892 return false;
893
894 TrueBBICalc.BB = TrueBBI.BB;
895 FalseBBICalc.BB = FalseBBI.BB;
896 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
897 return false;
898 // The size is used to decide whether to if-convert, and the shared portions
899 // are subtracted off. Because of the subtraction, we just use the size that
900 // was calculated by the original ScanInstructions, as it is correct.
901 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
902 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
Evan Cheng51eb2c32007-06-18 08:37:25 +0000903 return true;
Evan Chengbe9859e2007-06-07 02:12:15 +0000904}
905
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000906/// AnalyzeBranches - Look at the branches at the end of a block to determine if
907/// the block is predicable.
908void IfConverter::AnalyzeBranches(BBInfo &BBI) {
Evan Cheng4dd31a72007-06-11 22:26:22 +0000909 if (BBI.IsDone)
910 return;
911
Craig Topperc0196b12014-04-14 00:51:57 +0000912 BBI.TrueBB = BBI.FalseBB = nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000913 BBI.BrCond.clear();
914 BBI.IsBrAnalyzable =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000915 !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
Kyle Butta8c73712016-08-24 21:34:27 +0000916 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
917 BBI.IsBrReversible = (RevCond.size() == 0) ||
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000918 !TII->reverseBranchCondition(RevCond);
Craig Topperc0196b12014-04-14 00:51:57 +0000919 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000920
921 if (BBI.BrCond.size()) {
922 // No false branch. This BB must end with a conditional branch and a
923 // fallthrough.
924 if (!BBI.FalseBB)
Bob Wilson81051442010-06-15 22:18:54 +0000925 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Chengb9bff582009-06-15 21:24:34 +0000926 if (!BBI.FalseBB) {
927 // Malformed bcc? True and false blocks are the same?
928 BBI.IsUnpredicable = true;
Evan Chengb9bff582009-06-15 21:24:34 +0000929 }
Evan Cheng4dd31a72007-06-11 22:26:22 +0000930 }
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000931}
Evan Cheng4dd31a72007-06-11 22:26:22 +0000932
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000933/// ScanInstructions - Scan all the instructions in the block to determine if
934/// the block is predicable. In most cases, that means all the instructions
935/// in the block are isPredicable(). Also checks if the block contains any
936/// instruction which can clobber a predicate (e.g. condition code register).
937/// If so, the block is not predicable unless it's the last instruction.
938void IfConverter::ScanInstructions(BBInfo &BBI,
939 MachineBasicBlock::iterator &Begin,
Kyle Butt6262ca32016-08-24 21:34:24 +0000940 MachineBasicBlock::iterator &End,
941 bool BranchUnpredicable) const {
Kyle Butt54bf3ce2016-08-06 01:52:34 +0000942 if (BBI.IsDone || BBI.IsUnpredicable)
943 return;
944
945 bool AlreadyPredicated = !BBI.Predicate.empty();
946
Evan Cheng4dd31a72007-06-11 22:26:22 +0000947 BBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +0000948 BBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +0000949 BBI.ExtraCost2 = 0;
Evan Cheng4dd31a72007-06-11 22:26:22 +0000950 BBI.ClobbersPred = false;
Matthias Braunb1e05582016-08-17 02:51:59 +0000951 for (MachineInstr &MI : make_range(Begin, End)) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000952 if (MI.isDebugValue())
Jim Grosbacha1e08fb2010-06-04 23:01:26 +0000953 continue;
954
Justin Lebar7dba2e02016-04-15 01:38:41 +0000955 // It's unsafe to duplicate convergent instructions in this context, so set
956 // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
957 // following CFG, which is subject to our "simple" transformation.
958 //
959 // BB0 // if (c1) goto BB1; else goto BB2;
960 // / \
961 // BB1 |
962 // | BB2 // if (c2) goto TBB; else goto FBB;
963 // | / |
964 // | / |
965 // TBB |
966 // | |
967 // | FBB
968 // |
969 // exit
970 //
971 // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
972 // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
973 // TBB contains a convergent instruction. This is safe iff doing so does
974 // not add a control-flow dependency to the convergent instruction -- i.e.,
975 // it's safe iff the set of control flows that leads us to the convergent
976 // instruction does not get smaller after the transformation.
977 //
978 // Originally we executed TBB if c1 || c2. After the transformation, there
979 // are two copies of TBB's instructions. We get to the first if c1, and we
980 // get to the second if !c1 && c2.
981 //
982 // There are clearly fewer ways to satisfy the condition "c1" than
983 // "c1 || c2". Since we've shrunk the set of control flows which lead to
984 // our convergent instruction, the transformation is unsafe.
985 if (MI.isNotDuplicable() || MI.isConvergent())
Evan Cheng23402fc2007-06-15 21:18:05 +0000986 BBI.CannotBeCopied = true;
987
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000988 bool isPredicated = TII->isPredicated(MI);
989 bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
Evan Cheng4dd31a72007-06-11 22:26:22 +0000990
Kyle Butt6262ca32016-08-24 21:34:24 +0000991 if (BranchUnpredicable && MI.isBranch()) {
992 BBI.IsUnpredicable = true;
993 return;
994 }
995
Joey Goulya5153cb2013-09-09 14:21:49 +0000996 // A conditional branch is not predicable, but it may be eliminated.
997 if (isCondBr)
998 continue;
999
1000 if (!isPredicated) {
1001 BBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001002 unsigned ExtraPredCost = TII->getPredicationCost(MI);
1003 unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
Joey Goulya5153cb2013-09-09 14:21:49 +00001004 if (NumCycles > 1)
1005 BBI.ExtraCost += NumCycles-1;
1006 BBI.ExtraCost2 += ExtraPredCost;
1007 } else if (!AlreadyPredicated) {
1008 // FIXME: This instruction is already predicated before the
1009 // if-conversion pass. It's probably something like a conditional move.
1010 // Mark this block unpredicable for now.
1011 BBI.IsUnpredicable = true;
1012 return;
Evan Cheng96c14572007-07-06 23:24:39 +00001013 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001014
1015 if (BBI.ClobbersPred && !isPredicated) {
1016 // Predicate modification instruction should end the block (except for
1017 // already predicated instructions and end of block branches).
Evan Cheng4dd31a72007-06-11 22:26:22 +00001018 // Predicate may have been modified, the subsequent (currently)
Evan Cheng96c14572007-07-06 23:24:39 +00001019 // unpredicated instructions cannot be correctly predicated.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001020 BBI.IsUnpredicable = true;
1021 return;
1022 }
1023
Evan Chengfbc73092007-07-10 17:50:43 +00001024 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
1025 // still potentially predicable.
1026 std::vector<MachineOperand> PredDefs;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001027 if (TII->DefinesPredicate(MI, PredDefs))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001028 BBI.ClobbersPred = true;
1029
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001030 if (!TII->isPredicable(MI)) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001031 BBI.IsUnpredicable = true;
1032 return;
1033 }
1034 }
1035}
1036
Matthias Braun2c931792016-08-17 02:51:57 +00001037/// Determine if the block is a suitable candidate to be predicated by the
1038/// specified predicate.
Kyle Butt6262ca32016-08-24 21:34:24 +00001039/// @param BBI BBInfo for the block to check
1040/// @param Pred Predicate array for the branch that leads to BBI
1041/// @param isTriangle true if the Analysis is for a triangle
1042/// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
1043/// case
1044/// @param hasCommonTail true if BBI shares a tail with a sibling block that
1045/// contains any instruction that would make the block unpredicable.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001046bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00001047 SmallVectorImpl<MachineOperand> &Pred,
Kyle Butt6262ca32016-08-24 21:34:24 +00001048 bool isTriangle, bool RevBranch,
1049 bool hasCommonTail) {
Evan Cheng3a51c852007-06-16 09:34:52 +00001050 // If the block is dead or unpredicable, then it cannot be predicated.
Kyle Butt6262ca32016-08-24 21:34:24 +00001051 // Two blocks may share a common unpredicable tail, but this doesn't prevent
1052 // them from being if-converted. The non-shared portion is assumed to have
1053 // been checked
1054 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001055 return false;
1056
Ahmed Bougacha7173b662015-03-21 01:23:15 +00001057 // If it is already predicated but we couldn't analyze its terminator, the
1058 // latter might fallthrough, but we can't determine where to.
1059 // Conservatively avoid if-converting again.
1060 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1061 return false;
1062
Quentin Colombetbdab2272013-07-24 20:20:37 +00001063 // If it is already predicated, check if the new predicate subsumes
1064 // its predicate.
1065 if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001066 return false;
1067
Kyle Butt6262ca32016-08-24 21:34:24 +00001068 if (!hasCommonTail && BBI.BrCond.size()) {
Evan Cheng4dd31a72007-06-11 22:26:22 +00001069 if (!isTriangle)
1070 return false;
1071
Bob Wilson2371f4f2009-05-13 23:25:24 +00001072 // Test predicate subsumption.
Owen Anderson4f6bf042008-08-14 22:49:33 +00001073 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
1074 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng4dd31a72007-06-11 22:26:22 +00001075 if (RevBranch) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001076 if (TII->reverseBranchCondition(Cond))
Evan Cheng4dd31a72007-06-11 22:26:22 +00001077 return false;
1078 }
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001079 if (TII->reverseBranchCondition(RevPred) ||
Evan Cheng4dd31a72007-06-11 22:26:22 +00001080 !TII->SubsumesPredicate(Cond, RevPred))
1081 return false;
1082 }
1083
1084 return true;
1085}
1086
Matthias Braun2c931792016-08-17 02:51:57 +00001087/// Analyze the structure of the sub-CFG starting from the specified block.
1088/// Record its successors and whether it looks like an if-conversion candidate.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001089void IfConverter::AnalyzeBlock(
Matthias Braun08f47042016-08-17 02:52:01 +00001090 MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001091 struct BBState {
Matthias Braun08f47042016-08-17 02:52:01 +00001092 BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001093 MachineBasicBlock *MBB;
Evan Chengf5e53a52007-05-16 02:00:57 +00001094
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001095 /// This flag is true if MBB's successors have been analyzed.
1096 bool SuccsAnalyzed;
1097 };
Evan Cheng0f745da2007-05-18 00:20:58 +00001098
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001099 // Push MBB to the stack.
1100 SmallVector<BBState, 16> BBStack(1, MBB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001101
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001102 while (!BBStack.empty()) {
1103 BBState &State = BBStack.back();
1104 MachineBasicBlock *BB = State.MBB;
1105 BBInfo &BBI = BBAnalysis[BB->getNumber()];
Evan Cheng4dd31a72007-06-11 22:26:22 +00001106
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001107 if (!State.SuccsAnalyzed) {
1108 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1109 BBStack.pop_back();
1110 continue;
1111 }
Evan Cheng9030b982007-06-06 10:16:17 +00001112
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001113 BBI.BB = BB;
1114 BBI.IsBeingAnalyzed = true;
Evan Cheng4dd31a72007-06-11 22:26:22 +00001115
Kyle Butt54bf3ce2016-08-06 01:52:34 +00001116 AnalyzeBranches(BBI);
1117 MachineBasicBlock::iterator Begin = BBI.BB->begin();
1118 MachineBasicBlock::iterator End = BBI.BB->end();
1119 ScanInstructions(BBI, Begin, End);
Evan Chengb9bff582009-06-15 21:24:34 +00001120
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001121 // Unanalyzable or ends with fallthrough or unconditional branch, or if is
1122 // not considered for ifcvt anymore.
1123 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1124 BBI.IsBeingAnalyzed = false;
1125 BBI.IsAnalyzed = true;
1126 BBStack.pop_back();
1127 continue;
1128 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001129
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001130 // Do not ifcvt if either path is a back edge to the entry block.
1131 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1132 BBI.IsBeingAnalyzed = false;
1133 BBI.IsAnalyzed = true;
1134 BBStack.pop_back();
1135 continue;
1136 }
Evan Cheng4dd31a72007-06-11 22:26:22 +00001137
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001138 // Do not ifcvt if true and false fallthrough blocks are the same.
1139 if (!BBI.FalseBB) {
1140 BBI.IsBeingAnalyzed = false;
1141 BBI.IsAnalyzed = true;
1142 BBStack.pop_back();
1143 continue;
1144 }
Evan Cheng7783f822007-06-08 09:36:04 +00001145
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001146 // Push the False and True blocks to the stack.
1147 State.SuccsAnalyzed = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001148 BBStack.push_back(*BBI.FalseBB);
1149 BBStack.push_back(*BBI.TrueBB);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001150 continue;
1151 }
Benjamin Kramer2016f0e2010-09-29 22:38:50 +00001152
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001153 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1154 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Jakub Staszak15e5b742011-08-03 22:34:43 +00001155
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001156 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1157 BBI.IsBeingAnalyzed = false;
1158 BBI.IsAnalyzed = true;
1159 BBStack.pop_back();
1160 continue;
1161 }
1162
1163 SmallVector<MachineOperand, 4>
1164 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001165 bool CanRevCond = !TII->reverseBranchCondition(RevCond);
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001166
1167 unsigned Dups = 0;
1168 unsigned Dups2 = 0;
1169 bool TNeedSub = !TrueBBI.Predicate.empty();
1170 bool FNeedSub = !FalseBBI.Predicate.empty();
1171 bool Enqueued = false;
1172
1173 BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
1174
Kyle Butt6262ca32016-08-24 21:34:24 +00001175 if (CanRevCond) {
1176 BBInfo TrueBBICalc, FalseBBICalc;
Kyle Butta8c73712016-08-24 21:34:27 +00001177 auto feasibleDiamond = [&]() {
1178 bool MeetsSize = MeetIfcvtSizeLimit(
1179 *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
1180 TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
1181 *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
1182 FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
1183 Prediction);
1184 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1185 /* IsTriangle */ false, /* RevCond */ false,
1186 /* hasCommonTail */ true);
1187 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1188 /* IsTriangle */ false, /* RevCond */ false,
1189 /* hasCommonTail */ true);
1190 return MeetsSize && TrueFeasible && FalseFeasible;
1191 };
1192
Kyle Butt6262ca32016-08-24 21:34:24 +00001193 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
Kyle Butta8c73712016-08-24 21:34:27 +00001194 TrueBBICalc, FalseBBICalc)) {
1195 if (feasibleDiamond()) {
1196 // Diamond:
1197 // EBB
1198 // / \_
1199 // | |
1200 // TBB FBB
1201 // \ /
1202 // TailBB
1203 // Note TailBB can be empty.
1204 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1205 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1206 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1207 Enqueued = true;
1208 }
1209 } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1210 TrueBBICalc, FalseBBICalc)) {
1211 if (feasibleDiamond()) {
1212 // ForkedDiamond:
1213 // if TBB and FBB have a common tail that includes their conditional
1214 // branch instructions, then we can If Convert this pattern.
1215 // EBB
1216 // _/ \_
1217 // | |
1218 // TBB FBB
1219 // / \ / \
1220 // FalseBB TrueBB FalseBB
1221 //
1222 Tokens.push_back(llvm::make_unique<IfcvtToken>(
1223 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1224 (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
1225 Enqueued = true;
1226 }
Kyle Butt6262ca32016-08-24 21:34:24 +00001227 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001228 }
1229
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001230 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
1231 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1232 TrueBBI.ExtraCost2, Prediction) &&
1233 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
1234 // Triangle:
1235 // EBB
1236 // | \_
1237 // | |
1238 // | TBB
1239 // | /
1240 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001241 Tokens.push_back(
1242 llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001243 Enqueued = true;
1244 }
1245
1246 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
1247 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1248 TrueBBI.ExtraCost2, Prediction) &&
1249 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001250 Tokens.push_back(
1251 llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001252 Enqueued = true;
1253 }
1254
1255 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1256 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1257 TrueBBI.ExtraCost2, Prediction) &&
1258 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1259 // Simple (split, no rejoin):
1260 // EBB
1261 // | \_
1262 // | |
1263 // | TBB---> exit
1264 // |
1265 // FBB
Justin Lebar3a7bc572016-02-22 17:51:28 +00001266 Tokens.push_back(
1267 llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001268 Enqueued = true;
1269 }
1270
1271 if (CanRevCond) {
1272 // Try the other path...
1273 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
1274 Prediction.getCompl()) &&
1275 MeetIfcvtSizeLimit(*FalseBBI.BB,
1276 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1277 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1278 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001279 Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1280 FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001281 Enqueued = true;
1282 }
1283
1284 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
1285 Prediction.getCompl()) &&
1286 MeetIfcvtSizeLimit(*FalseBBI.BB,
1287 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Jakub Staszak9b07c0a2011-07-10 02:58:07 +00001288 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
Evan Cheng3a51c852007-06-16 09:34:52 +00001289 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001290 Tokens.push_back(
1291 llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001292 Enqueued = true;
1293 }
1294
1295 if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
1296 MeetIfcvtSizeLimit(*FalseBBI.BB,
1297 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1298 FalseBBI.ExtraCost2, Prediction.getCompl()) &&
1299 FeasibilityAnalysis(FalseBBI, RevCond)) {
Justin Lebar3a7bc572016-02-22 17:51:28 +00001300 Tokens.push_back(
1301 llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001302 Enqueued = true;
1303 }
Evan Cheng3a51c852007-06-16 09:34:52 +00001304 }
1305
Akira Hatanaka14348aa2015-06-24 20:34:35 +00001306 BBI.IsEnqueued = Enqueued;
1307 BBI.IsBeingAnalyzed = false;
1308 BBI.IsAnalyzed = true;
1309 BBStack.pop_back();
Evan Chengf5e53a52007-05-16 02:00:57 +00001310 }
Evan Cheng2e82cef2007-05-18 18:14:37 +00001311}
1312
Matthias Braun2c931792016-08-17 02:51:57 +00001313/// Analyze all blocks and find entries for all if-conversion candidates.
Justin Lebar3a7bc572016-02-22 17:51:28 +00001314void IfConverter::AnalyzeBlocks(
1315 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001316 for (MachineBasicBlock &MBB : MF)
Matthias Braun08f47042016-08-17 02:52:01 +00001317 AnalyzeBlock(MBB, Tokens);
Evan Cheng905a8f42007-05-30 19:49:19 +00001318
Evan Cheng20e05992007-06-01 00:12:12 +00001319 // Sort to favor more complex ifcvt scheme.
Evan Cheng3a51c852007-06-16 09:34:52 +00001320 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Chengf5e53a52007-05-16 02:00:57 +00001321}
1322
Matthias Braun2c931792016-08-17 02:51:57 +00001323/// Returns true either if ToMBB is the next block after MBB or that all the
1324/// intervening blocks are empty (given MBB can fall through to its next block).
Matthias Braun08f47042016-08-17 02:52:01 +00001325static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
1326 MachineFunction::iterator PI = MBB.getIterator();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001327 MachineFunction::iterator I = std::next(PI);
Matthias Braun08f47042016-08-17 02:52:01 +00001328 MachineFunction::iterator TI = ToMBB.getIterator();
1329 MachineFunction::iterator E = MBB.getParent()->end();
Evan Chengf128bdc2010-06-16 07:35:02 +00001330 while (I != TI) {
1331 // Check isSuccessor to avoid case where the next block is empty, but
1332 // it's not a successor.
Duncan P. N. Exon Smith5ae59392015-10-09 19:13:58 +00001333 if (I == E || !I->empty() || !PI->isSuccessor(&*I))
Evan Cheng312b7232007-06-04 06:47:22 +00001334 return false;
Evan Chengf128bdc2010-06-16 07:35:02 +00001335 PI = I++;
1336 }
Mikael Holmen21c867c2017-05-10 13:06:13 +00001337 // Finally see if the last I is indeed a successor to PI.
1338 return PI->isSuccessor(&*I);
Evan Chenge26c0912007-05-21 22:22:58 +00001339}
1340
Matthias Braun2c931792016-08-17 02:51:57 +00001341/// Invalidate predecessor BB info so it would be re-analyzed to determine if it
1342/// can be if-converted. If predecessor is already enqueued, dequeue it!
Matthias Braun08f47042016-08-17 02:52:01 +00001343void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
1344 for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001345 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
Matthias Braun08f47042016-08-17 02:52:01 +00001346 if (PBBI.IsDone || PBBI.BB == &MBB)
Evan Cheng9fc56c02007-06-14 23:13:19 +00001347 continue;
Evan Chengadd97762007-06-14 23:34:09 +00001348 PBBI.IsAnalyzed = false;
1349 PBBI.IsEnqueued = false;
Evan Chengd0e66912007-05-23 07:23:16 +00001350 }
1351}
1352
Matthias Braun2c931792016-08-17 02:51:57 +00001353/// Inserts an unconditional branch from \p MBB to \p ToMBB.
Matthias Braun08f47042016-08-17 02:52:01 +00001354static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
Evan Chengc2237ce2007-05-29 22:31:16 +00001355 const TargetInstrInfo *TII) {
Stuart Hastings0125b642010-06-17 22:43:56 +00001356 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman14714cb2008-08-22 16:07:55 +00001357 SmallVector<MachineOperand, 0> NoCond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001358 TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
Evan Chengc2237ce2007-05-29 22:31:16 +00001359}
1360
Matthias Braund616ccc2013-10-11 19:04:37 +00001361/// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
Jonas Paulsson196986c2016-08-03 05:46:35 +00001362/// values defined in MI which are also live/used by MI.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001363static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001364 const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
Jonas Paulsson196986c2016-08-03 05:46:35 +00001365
1366 // Before stepping forward past MI, remember which regs were live
1367 // before MI. This is needed to set the Undef flag only when reg is
1368 // dead.
1369 SparseSet<unsigned> LiveBeforeMI;
1370 LiveBeforeMI.setUniverse(TRI->getNumRegs());
Matthias Braunb1e05582016-08-17 02:51:59 +00001371 for (unsigned Reg : Redefs)
Jonas Paulsson196986c2016-08-03 05:46:35 +00001372 LiveBeforeMI.insert(Reg);
1373
Pete Cooper7605e372015-05-05 20:14:22 +00001374 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001375 Redefs.stepForward(MI, Clobbers);
Matthias Braund616ccc2013-10-11 19:04:37 +00001376
Pete Cooper7605e372015-05-05 20:14:22 +00001377 // Now add the implicit uses for each of the clobbered values.
Matthias Braun08f47042016-08-17 02:52:01 +00001378 for (auto Clobber : Clobbers) {
Pete Cooper7605e372015-05-05 20:14:22 +00001379 // FIXME: Const cast here is nasty, but better than making StepForward
1380 // take a mutable instruction instead of const.
Matthias Braun08f47042016-08-17 02:52:01 +00001381 unsigned Reg = Clobber.first;
1382 MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
Pete Cooper27483912015-05-06 22:51:04 +00001383 MachineInstr *OpMI = Op.getParent();
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001384 MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
Pete Cooperce9ad752015-05-05 22:09:41 +00001385 if (Op.isRegMask()) {
1386 // First handle regmasks. They clobber any entries in the mask which
1387 // means that we need a def for those registers.
Matthias Braun08f47042016-08-17 02:52:01 +00001388 if (LiveBeforeMI.count(Reg))
1389 MIB.addReg(Reg, RegState::Implicit);
Pete Cooperce9ad752015-05-05 22:09:41 +00001390
1391 // We also need to add an implicit def of this register for the later
1392 // use to read from.
1393 // For the register allocator to have allocated a register clobbered
1394 // by the call which is used later, it must be the case that
1395 // the call doesn't return.
Matthias Braun08f47042016-08-17 02:52:01 +00001396 MIB.addReg(Reg, RegState::Implicit | RegState::Define);
Pete Cooperce9ad752015-05-05 22:09:41 +00001397 continue;
1398 }
Matthias Braun08f47042016-08-17 02:52:01 +00001399 if (LiveBeforeMI.count(Reg))
1400 MIB.addReg(Reg, RegState::Implicit);
Krzysztof Parzyszekdcb1bca2016-09-28 20:07:41 +00001401 else {
1402 bool HasLiveSubReg = false;
1403 for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
1404 if (!LiveBeforeMI.count(*S))
1405 continue;
1406 HasLiveSubReg = true;
1407 break;
1408 }
1409 if (HasLiveSubReg)
1410 MIB.addReg(Reg, RegState::Implicit);
1411 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001412 }
1413}
1414
Matthias Braun2c931792016-08-17 02:51:57 +00001415/// If convert a simple (split, no rejoin) sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001416bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenge26c0912007-05-21 22:22:58 +00001417 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1418 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1419 BBInfo *CvtBBI = &TrueBBI;
1420 BBInfo *NextBBI = &FalseBBI;
Evan Chengd0e66912007-05-23 07:23:16 +00001421
Owen Anderson4f6bf042008-08-14 22:49:33 +00001422 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001423 if (Kind == ICSimpleFalse)
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001424 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001425
Matthias Braun08f47042016-08-17 02:52:01 +00001426 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1427 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001428 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001429 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001430 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001431 BBI.IsAnalyzed = false;
1432 CvtBBI->IsAnalyzed = false;
1433 return false;
Evan Cheng4dcf1e82007-06-01 20:29:21 +00001434 }
Evan Chengd0e66912007-05-23 07:23:16 +00001435
Matthias Braun08f47042016-08-17 02:52:01 +00001436 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001437 // Conservatively abort if-conversion if BB's address is taken.
1438 return false;
1439
Evan Cheng3a51c852007-06-16 09:34:52 +00001440 if (Kind == ICSimpleFalse)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001441 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001442 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001443
Matthias Braun0c989a82016-12-08 00:15:51 +00001444 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001445
1446 if (MRI->tracksLiveness()) {
1447 // Initialize liveins to the first BB. These are potentiall redefined by
1448 // predicated instructions.
1449 Redefs.addLiveIns(CvtMBB);
1450 Redefs.addLiveIns(NextMBB);
Matthias Braun11723322017-01-05 20:01:19 +00001451 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001452
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001453 // Remove the branches from the entry so we can add the contents of the true
1454 // block to it.
1455 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1456
Matthias Braun08f47042016-08-17 02:52:01 +00001457 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001458 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001459 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001460 CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
Hal Finkel95081bf2013-04-10 22:05:25 +00001461
Mikael Holmen8b106802017-08-11 06:57:08 +00001462 // Keep the CFG updated.
Matthias Braun08f47042016-08-17 02:52:01 +00001463 BBI.BB->removeSuccessor(&CvtMBB, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001464 } else {
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001465 // Predicate the instructions in the true block.
Matthias Braun08f47042016-08-17 02:52:01 +00001466 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001467
Mikael Holmen8b106802017-08-11 06:57:08 +00001468 // Merge converted block into entry block. The BB to Cvt edge is removed
1469 // by MergeBlocks.
Evan Cheng92fb5452007-06-15 07:36:12 +00001470 MergeBlocks(BBI, *CvtBBI);
1471 }
Evan Chengbe9859e2007-06-07 02:12:15 +00001472
Evan Chenge4ec9182007-06-06 02:08:52 +00001473 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001474 if (!canFallThroughTo(*BBI.BB, NextMBB)) {
1475 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001476 BBI.HasFallThrough = false;
Evan Cheng7783f822007-06-08 09:36:04 +00001477 // Now ifcvt'd block will look like this:
1478 // BB:
1479 // ...
1480 // t, f = cmp
1481 // if t op
1482 // b BBf
1483 //
1484 // We cannot further ifcvt this block because the unconditional branch
1485 // will have to be predicated on the new condition, that will not be
1486 // available if cmp executes.
1487 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001488 }
Evan Chenge26c0912007-05-21 22:22:58 +00001489
Evan Chengd0e66912007-05-23 07:23:16 +00001490 // Update block info. BB can be iteratively if-converted.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001491 if (!IterIfcvt)
1492 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001493 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001494 CvtBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001495
1496 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001497 return true;
1498}
1499
Matthias Braun2c931792016-08-17 02:51:57 +00001500/// If convert a triangle sub-CFG.
Evan Cheng3a51c852007-06-16 09:34:52 +00001501bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chengd0e66912007-05-23 07:23:16 +00001502 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng2117d1f2007-06-09 01:03:43 +00001503 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1504 BBInfo *CvtBBI = &TrueBBI;
1505 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings0125b642010-06-17 22:43:56 +00001506 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng2117d1f2007-06-09 01:03:43 +00001507
Owen Anderson4f6bf042008-08-14 22:49:33 +00001508 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng3a51c852007-06-16 09:34:52 +00001509 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng2117d1f2007-06-09 01:03:43 +00001510 std::swap(CvtBBI, NextBBI);
Evan Cheng23402fc2007-06-15 21:18:05 +00001511
Matthias Braun08f47042016-08-17 02:52:01 +00001512 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1513 MachineBasicBlock &NextMBB = *NextBBI->BB;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001514 if (CvtBBI->IsDone ||
Matthias Braun08f47042016-08-17 02:52:01 +00001515 (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
Evan Cheng23402fc2007-06-15 21:18:05 +00001516 // Something has changed. It's no longer safe to predicate this block.
Evan Cheng23402fc2007-06-15 21:18:05 +00001517 BBI.IsAnalyzed = false;
1518 CvtBBI->IsAnalyzed = false;
1519 return false;
Evan Cheng2117d1f2007-06-09 01:03:43 +00001520 }
Evan Cheng23402fc2007-06-15 21:18:05 +00001521
Matthias Braun08f47042016-08-17 02:52:01 +00001522 if (CvtMBB.hasAddressTaken())
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001523 // Conservatively abort if-conversion if BB's address is taken.
1524 return false;
1525
Evan Cheng3a51c852007-06-16 09:34:52 +00001526 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001527 if (TII->reverseBranchCondition(Cond))
Craig Topperee4dab52012-02-05 08:31:47 +00001528 llvm_unreachable("Unable to reverse branch condition!");
Evan Cheng23402fc2007-06-15 21:18:05 +00001529
Evan Cheng3a51c852007-06-16 09:34:52 +00001530 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001531 if (reverseBranchCondition(*CvtBBI)) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001532 // BB has been changed, modify its predecessors (except for this
1533 // one) so they don't get ifcvt'ed based on bad intel.
Matthias Braun08f47042016-08-17 02:52:01 +00001534 for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
Dan Gohman97d95d62008-10-21 03:29:32 +00001535 if (PBB == BBI.BB)
1536 continue;
1537 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1538 if (PBBI.IsEnqueued) {
1539 PBBI.IsAnalyzed = false;
1540 PBBI.IsEnqueued = false;
1541 }
Evan Chengadd97762007-06-14 23:34:09 +00001542 }
Evan Cheng9acfa7b2007-06-12 23:54:05 +00001543 }
1544 }
Evan Cheng6a2cf072007-06-01 07:41:07 +00001545
Bob Wilson45814342010-06-19 05:33:57 +00001546 // Initialize liveins to the first BB. These are potentially redefined by
Evan Chengf128bdc2010-06-16 07:35:02 +00001547 // predicated instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001548 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001549 if (MRI->tracksLiveness()) {
1550 Redefs.addLiveIns(CvtMBB);
1551 Redefs.addLiveIns(NextMBB);
1552 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001553
Craig Topperc0196b12014-04-14 00:51:57 +00001554 bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
Cong Houd97c1002015-12-01 05:29:22 +00001555 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001556
Manman Renb6819182014-01-29 23:18:47 +00001557 if (HasEarlyExit) {
Matthias Braun08f47042016-08-17 02:52:01 +00001558 // Get probabilities before modifying CvtMBB and BBI.BB.
1559 CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
1560 CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
1561 BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
1562 BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
Manman Renb6819182014-01-29 23:18:47 +00001563 }
Saleem Abdulrasoolf158ca32014-08-09 17:21:29 +00001564
Mikael Holmen45bd32f2017-06-26 09:33:04 +00001565 // Remove the branches from the entry so we can add the contents of the true
1566 // block to it.
1567 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
1568
Matthias Braun08f47042016-08-17 02:52:01 +00001569 if (CvtMBB.pred_size() > 1) {
Bob Wilson2371f4f2009-05-13 23:25:24 +00001570 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng92fb5452007-06-15 07:36:12 +00001571 // the entry block.
Andrew Trick276dd452013-10-14 20:45:17 +00001572 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
Evan Cheng92fb5452007-06-15 07:36:12 +00001573 } else {
1574 // Predicate the 'true' block after removing its branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001575 CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
Matthias Braun08f47042016-08-17 02:52:01 +00001576 PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
Evan Chenge26c0912007-05-21 22:22:58 +00001577
Mikael Holmence3ec452017-05-12 06:28:58 +00001578 // Now merge the entry of the triangle with the true block.
Bob Wilson1e5da552010-06-29 00:55:23 +00001579 MergeBlocks(BBI, *CvtBBI, false);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001580 }
1581
Mikael Holmen8b106802017-08-11 06:57:08 +00001582 // Keep the CFG updated.
1583 BBI.BB->removeSuccessor(&CvtMBB, true);
1584
Evan Cheng312b7232007-06-04 06:47:22 +00001585 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng6e4babe2007-06-05 01:31:40 +00001586 if (HasEarlyExit) {
Owen Anderson4f6bf042008-08-14 22:49:33 +00001587 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1588 CvtBBI->BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001589 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001590 llvm_unreachable("Unable to reverse branch condition!");
Hans Wennborg1dbaf672015-12-01 03:49:42 +00001591
Cong Houd97c1002015-12-01 05:29:22 +00001592 // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
Matthias Braun08f47042016-08-17 02:52:01 +00001593 // NewNext = New_Prob(BBI.BB, NextMBB) =
1594 // Prob(BBI.BB, NextMBB) +
1595 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
Cong Houd97c1002015-12-01 05:29:22 +00001596 // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
Matthias Braun08f47042016-08-17 02:52:01 +00001597 // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
1598 auto NewTrueBB = getNextBlock(*BBI.BB);
Cong Houd97c1002015-12-01 05:29:22 +00001599 auto NewNext = BBNext + BBCvt * CvtNext;
David Majnemer42531262016-08-12 03:55:06 +00001600 auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
Cong Houcb07d702015-12-01 21:50:20 +00001601 if (NewTrueBBIter != BBI.BB->succ_end())
1602 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
Cong Houd97c1002015-12-01 05:29:22 +00001603
1604 auto NewFalse = BBCvt * CvtFalse;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001605 TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
Cong Houd97c1002015-12-01 05:29:22 +00001606 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
Evan Cheng92fb5452007-06-15 07:36:12 +00001607 }
Evan Cheng7783f822007-06-08 09:36:04 +00001608
1609 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson2371f4f2009-05-13 23:25:24 +00001610 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Cheng17aad8162007-06-05 00:07:37 +00001611 bool FalseBBDead = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001612 bool IterIfcvt = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001613 bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001614 if (!isFallThrough) {
1615 // Only merge them if the true block does not fallthrough to the false
1616 // block. By not merging them, we make it possible to iteratively
1617 // ifcvt the blocks.
Evan Cheng51eb2c32007-06-18 08:37:25 +00001618 if (!HasEarlyExit &&
Tobias Grosser8cf785f2017-05-29 06:12:18 +00001619 NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
Matthias Braun08f47042016-08-17 02:52:01 +00001620 !NextMBB.hasAddressTaken()) {
Evan Cheng2117d1f2007-06-09 01:03:43 +00001621 MergeBlocks(BBI, *NextBBI);
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001622 FalseBBDead = true;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001623 } else {
Matthias Braun08f47042016-08-17 02:52:01 +00001624 InsertUncondBranch(*BBI.BB, NextMBB, TII);
Evan Cheng2117d1f2007-06-09 01:03:43 +00001625 BBI.HasFallThrough = false;
Evan Chengd3f3f0a2007-06-07 08:13:00 +00001626 }
Evan Cheng7783f822007-06-08 09:36:04 +00001627 // Mixed predicated and unpredicated code. This cannot be iteratively
1628 // predicated.
1629 IterIfcvt = false;
Evan Chenge4ec9182007-06-06 02:08:52 +00001630 }
Evan Chenge26c0912007-05-21 22:22:58 +00001631
Evan Chengd0e66912007-05-23 07:23:16 +00001632 // Update block info. BB can be iteratively if-converted.
Bob Wilson81051442010-06-15 22:18:54 +00001633 if (!IterIfcvt)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001634 BBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001635 InvalidatePreds(*BBI.BB);
Evan Cheng4dd31a72007-06-11 22:26:22 +00001636 CvtBBI->IsDone = true;
Evan Cheng17aad8162007-06-05 00:07:37 +00001637 if (FalseBBDead)
Evan Cheng4dd31a72007-06-11 22:26:22 +00001638 NextBBI->IsDone = true;
Evan Chenge26c0912007-05-21 22:22:58 +00001639
1640 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001641 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001642}
1643
Kyle Butta8c73712016-08-24 21:34:27 +00001644/// Common code shared between diamond conversions.
1645/// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
1646/// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
1647/// and FalseBBI
1648/// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
1649/// and \p FalseBBI
Kyle Butt092c4dd2016-08-29 18:27:12 +00001650/// \p RemoveBranch - Remove the common branch of the two blocks before
1651/// predicating. Only false for unanalyzable fallthrough
1652/// cases. The caller will replace the branch if necessary.
Kyle Butta8c73712016-08-24 21:34:27 +00001653/// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
1654/// unanalyzable fallthrough
1655bool IfConverter::IfConvertDiamondCommon(
1656 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
1657 unsigned NumDups1, unsigned NumDups2,
1658 bool TClobbersPred, bool FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001659 bool RemoveBranch, bool MergeAddEdges) {
Evan Chenge26c0912007-05-21 22:22:58 +00001660
Evan Cheng51eb2c32007-06-18 08:37:25 +00001661 if (TrueBBI.IsDone || FalseBBI.IsDone ||
Kyle Butta8c73712016-08-24 21:34:27 +00001662 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001663 // Something has changed. It's no longer safe to predicate these blocks.
1664 BBI.IsAnalyzed = false;
1665 TrueBBI.IsAnalyzed = false;
1666 FalseBBI.IsAnalyzed = false;
1667 return false;
Evan Chenge26c0912007-05-21 22:22:58 +00001668 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001669
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001670 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1671 // Conservatively abort if-conversion if either BB has its address taken.
1672 return false;
1673
Bob Wilson1e5da552010-06-29 00:55:23 +00001674 // Put the predicated instructions from the 'true' block before the
1675 // instructions from the 'false' block, unless the true block would clobber
1676 // the predicate, in which case, do the opposite.
Evan Cheng79484222007-06-05 23:46:14 +00001677 BBInfo *BBI1 = &TrueBBI;
1678 BBInfo *BBI2 = &FalseBBI;
Owen Anderson4f6bf042008-08-14 22:49:33 +00001679 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001680 if (TII->reverseBranchCondition(RevCond))
Craig Topperee4dab52012-02-05 08:31:47 +00001681 llvm_unreachable("Unable to reverse branch condition!");
Owen Anderson4f6bf042008-08-14 22:49:33 +00001682 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1683 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Cheng30565992007-06-06 00:57:55 +00001684
Evan Cheng3a51c852007-06-16 09:34:52 +00001685 // Figure out the more profitable ordering.
1686 bool DoSwap = false;
Kyle Butt6262ca32016-08-24 21:34:24 +00001687 if (TClobbersPred && !FClobbersPred)
Evan Cheng3a51c852007-06-16 09:34:52 +00001688 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001689 else if (!TClobbersPred && !FClobbersPred) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001690 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Cheng3a51c852007-06-16 09:34:52 +00001691 DoSwap = true;
Kyle Butte31cc842016-09-02 18:29:28 +00001692 } else if (TClobbersPred && FClobbersPred)
1693 llvm_unreachable("Predicate info cannot be clobbered by both sides.");
Evan Cheng3a51c852007-06-16 09:34:52 +00001694 if (DoSwap) {
Evan Cheng30565992007-06-06 00:57:55 +00001695 std::swap(BBI1, BBI2);
1696 std::swap(Cond1, Cond2);
Evan Cheng30565992007-06-06 00:57:55 +00001697 }
Evan Cheng79484222007-06-05 23:46:14 +00001698
Evan Cheng51eb2c32007-06-18 08:37:25 +00001699 // Remove the conditional branch from entry to the blocks.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001700 BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001701
Matthias Braun08f47042016-08-17 02:52:01 +00001702 MachineBasicBlock &MBB1 = *BBI1->BB;
1703 MachineBasicBlock &MBB2 = *BBI2->BB;
1704
Krzysztof Parzyszeka003b762016-08-11 18:42:06 +00001705 // Initialize the Redefs:
1706 // - BB2 live-in regs need implicit uses before being redefined by BB1
1707 // instructions.
1708 // - BB1 live-out regs need implicit uses before being redefined by BB2
1709 // instructions. We start with BB1 live-ins so we have the live-out regs
1710 // after tracking the BB1 instructions.
Matthias Braun0c989a82016-12-08 00:15:51 +00001711 Redefs.init(*TRI);
Matthias Braun11723322017-01-05 20:01:19 +00001712 if (MRI->tracksLiveness()) {
1713 Redefs.addLiveIns(MBB1);
1714 Redefs.addLiveIns(MBB2);
1715 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001716
Evan Cheng51eb2c32007-06-18 08:37:25 +00001717 // Remove the duplicated instructions at the beginnings of both paths.
Jim Grosbach412800d2010-06-14 21:30:32 +00001718 // Skip dbg_value instructions
Matthias Braun08f47042016-08-17 02:52:01 +00001719 MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
1720 MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
Evan Cheng51eb2c32007-06-18 08:37:25 +00001721 BBI1->NonPredSize -= NumDups1;
1722 BBI2->NonPredSize -= NumDups1;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001723
1724 // Skip past the dups on each side separately since there may be
1725 // differing dbg_value entries.
1726 for (unsigned i = 0; i < NumDups1; ++DI1) {
1727 if (!DI1->isDebugValue())
1728 ++i;
1729 }
Jim Grosbachc34befc2010-06-25 23:05:46 +00001730 while (NumDups1 != 0) {
Evan Cheng51eb2c32007-06-18 08:37:25 +00001731 ++DI2;
Jim Grosbachee6e29a2010-06-28 20:26:00 +00001732 if (!DI2->isDebugValue())
1733 --NumDups1;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001734 }
Evan Chengf128bdc2010-06-16 07:35:02 +00001735
Matthias Braun11723322017-01-05 20:01:19 +00001736 if (MRI->tracksLiveness()) {
Matthias Braun11723322017-01-05 20:01:19 +00001737 for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
1738 SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Dummy;
1739 Redefs.stepForward(MI, Dummy);
1740 }
Matthias Braund616ccc2013-10-11 19:04:37 +00001741 }
Matthias Braun08f47042016-08-17 02:52:01 +00001742 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
1743 MBB2.erase(MBB2.begin(), DI2);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001744
Kyle Butt092c4dd2016-08-29 18:27:12 +00001745 // The branches have been checked to match, so it is safe to remove the branch
1746 // in BB1 and rely on the copy in BB2
1747#ifndef NDEBUG
1748 // Unanalyzable branches must match exactly. Check that now.
1749 if (!BBI1->IsBrAnalyzable)
1750 verifySameBranchInstructions(&MBB1, &MBB2);
1751#endif
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001752 BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001753 // Remove duplicated instructions.
Matthias Braun08f47042016-08-17 02:52:01 +00001754 DI1 = MBB1.end();
Jim Grosbach412800d2010-06-14 21:30:32 +00001755 for (unsigned i = 0; i != NumDups2; ) {
1756 // NumDups2 only counted non-dbg_value instructions, so this won't
1757 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001758 assert(DI1 != MBB1.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001759 --DI1;
Jim Grosbach412800d2010-06-14 21:30:32 +00001760 // skip dbg_value instructions
1761 if (!DI1->isDebugValue())
1762 ++i;
1763 }
Matthias Braun08f47042016-08-17 02:52:01 +00001764 MBB1.erase(DI1, MBB1.end());
Evan Cheng79484222007-06-05 23:46:14 +00001765
Kyle Butta8c73712016-08-24 21:34:27 +00001766 DI2 = BBI2->BB->end();
Kyle Butt092c4dd2016-08-29 18:27:12 +00001767 // The branches have been checked to match. Skip over the branch in the false
1768 // block so that we don't try to predicate it.
1769 if (RemoveBranch)
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001770 BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
Kyle Butt092c4dd2016-08-29 18:27:12 +00001771 else {
1772 do {
1773 assert(DI2 != MBB2.begin());
1774 DI2--;
1775 } while (DI2->isBranch() || DI2->isDebugValue());
1776 DI2++;
1777 }
Evan Cheng51eb2c32007-06-18 08:37:25 +00001778 while (NumDups2 != 0) {
Jim Grosbach412800d2010-06-14 21:30:32 +00001779 // NumDups2 only counted non-dbg_value instructions, so this won't
1780 // run off the head of the list.
Matthias Braun08f47042016-08-17 02:52:01 +00001781 assert(DI2 != MBB2.begin());
Evan Cheng51eb2c32007-06-18 08:37:25 +00001782 --DI2;
Jim Grosbach412800d2010-06-14 21:30:32 +00001783 // skip dbg_value instructions
1784 if (!DI2->isDebugValue())
1785 --NumDups2;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001786 }
Evan Cheng4266a792011-12-19 22:01:30 +00001787
1788 // Remember which registers would later be defined by the false block.
1789 // This allows us not to predicate instructions in the true block that would
1790 // later be re-defined. That is, rather than
1791 // subeq r0, r1, #1
1792 // addne r0, r1, #1
1793 // generate:
1794 // sub r0, r1, #1
1795 // addne r0, r1, #1
1796 SmallSet<unsigned, 4> RedefsByFalse;
1797 SmallSet<unsigned, 4> ExtUses;
Matthias Braun08f47042016-08-17 02:52:01 +00001798 if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1799 for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
Matthias Braunb1e05582016-08-17 02:51:59 +00001800 if (FI.isDebugValue())
Evan Cheng4266a792011-12-19 22:01:30 +00001801 continue;
1802 SmallVector<unsigned, 4> Defs;
Matthias Braunb1e05582016-08-17 02:51:59 +00001803 for (const MachineOperand &MO : FI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001804 if (!MO.isReg())
1805 continue;
1806 unsigned Reg = MO.getReg();
1807 if (!Reg)
1808 continue;
1809 if (MO.isDef()) {
1810 Defs.push_back(Reg);
1811 } else if (!RedefsByFalse.count(Reg)) {
1812 // These are defined before ctrl flow reach the 'false' instructions.
1813 // They cannot be modified by the 'true' instructions.
Chad Rosierabdb1d62013-05-22 23:17:36 +00001814 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1815 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001816 ExtUses.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001817 }
1818 }
1819
Matthias Braunb1e05582016-08-17 02:51:59 +00001820 for (unsigned Reg : Defs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001821 if (!ExtUses.count(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +00001822 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1823 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001824 RedefsByFalse.insert(*SubRegs);
Evan Cheng4266a792011-12-19 22:01:30 +00001825 }
1826 }
1827 }
1828 }
1829
1830 // Predicate the 'true' block.
Matthias Braun08f47042016-08-17 02:52:01 +00001831 PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
Evan Cheng4266a792011-12-19 22:01:30 +00001832
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001833 // After predicating BBI1, if there is a predicated terminator in BBI1 and
1834 // a non-predicated in BBI2, then we don't want to predicate the one from
1835 // BBI2. The reason is that if we merged these blocks, we would end up with
1836 // two predicated terminators in the same block.
Matthias Braun08f47042016-08-17 02:52:01 +00001837 if (!MBB2.empty() && (DI2 == MBB2.end())) {
1838 MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
1839 MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
1840 if (BBI1T != MBB1.end() && TII->isPredicated(*BBI1T) &&
1841 BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001842 --DI2;
1843 }
1844
Evan Cheng4266a792011-12-19 22:01:30 +00001845 // Predicate the 'false' block.
Andrew Trick276dd452013-10-14 20:45:17 +00001846 PredicateBlock(*BBI2, DI2, *Cond2);
Evan Cheng79484222007-06-05 23:46:14 +00001847
Evan Cheng0598b2d2007-06-18 22:44:57 +00001848 // Merge the true block into the entry of the diamond.
Kyle Butta8c73712016-08-24 21:34:27 +00001849 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1850 MergeBlocks(BBI, *BBI2, MergeAddEdges);
1851 return true;
1852}
1853
1854/// If convert an almost-diamond sub-CFG where the true
1855/// and false blocks share a common tail.
1856bool IfConverter::IfConvertForkedDiamond(
1857 BBInfo &BBI, IfcvtKind Kind,
1858 unsigned NumDups1, unsigned NumDups2,
1859 bool TClobbersPred, bool FClobbersPred) {
1860 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1861 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1862
1863 // Save the debug location for later.
1864 DebugLoc dl;
1865 MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
1866 if (TIE != TrueBBI.BB->end())
1867 dl = TIE->getDebugLoc();
1868 // Removing branches from both blocks is safe, because we have already
1869 // determined that both blocks have the same branch instructions. The branch
1870 // will be added back at the end, unpredicated.
1871 if (!IfConvertDiamondCommon(
1872 BBI, TrueBBI, FalseBBI,
1873 NumDups1, NumDups2,
1874 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001875 /* RemoveBranch */ true, /* MergeAddEdges */ true))
Kyle Butta8c73712016-08-24 21:34:27 +00001876 return false;
1877
1878 // Add back the branch.
1879 // Debug location saved above when removing the branch from BBI2
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001880 TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
Kyle Butta8c73712016-08-24 21:34:27 +00001881 TrueBBI.BrCond, dl);
1882
Kyle Butta8c73712016-08-24 21:34:27 +00001883 // Update block info.
1884 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
1885 InvalidatePreds(*BBI.BB);
1886
1887 // FIXME: Must maintain LiveIns.
1888 return true;
1889}
1890
1891/// If convert a diamond sub-CFG.
1892bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1893 unsigned NumDups1, unsigned NumDups2,
1894 bool TClobbersPred, bool FClobbersPred) {
1895 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1896 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1897 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
1898
1899 // True block must fall through or end with an unanalyzable terminator.
1900 if (!TailBB) {
1901 if (blockAlwaysFallThrough(TrueBBI))
1902 TailBB = FalseBBI.TrueBB;
1903 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
1904 }
1905
1906 if (!IfConvertDiamondCommon(
1907 BBI, TrueBBI, FalseBBI,
1908 NumDups1, NumDups2,
Kyle Butt86999212016-09-02 18:29:26 +00001909 TClobbersPred, FClobbersPred,
Kyle Butt092c4dd2016-08-29 18:27:12 +00001910 /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
Kyle Butta8c73712016-08-24 21:34:27 +00001911 /* MergeAddEdges */ TailBB == nullptr))
1912 return false;
Evan Cheng30565992007-06-06 00:57:55 +00001913
Bob Wilson2371f4f2009-05-13 23:25:24 +00001914 // If the if-converted block falls through or unconditionally branches into
1915 // the tail block, and the tail block does not have other predecessors, then
Evan Cheng51eb2c32007-06-18 08:37:25 +00001916 // fold the tail block in as well. Otherwise, unless it falls through to the
1917 // tail, add a unconditional branch to it.
1918 if (TailBB) {
Mikael Holmen8b106802017-08-11 06:57:08 +00001919 // We need to remove the edges to the true and false blocks manually since
1920 // we didn't let IfConvertDiamondCommon update the CFG.
1921 BBI.BB->removeSuccessor(TrueBBI.BB);
1922 BBI.BB->removeSuccessor(FalseBBI.BB, true);
1923
Pete Cooper77c703f2011-11-04 23:49:14 +00001924 BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
Evan Cheng8b8e8d82013-05-05 18:03:49 +00001925 bool CanMergeTail = !TailBBI.HasFallThrough &&
1926 !TailBBI.BB->hasAddressTaken();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001927 // The if-converted block can still have a predicated terminator
1928 // (e.g. a predicated return). If that is the case, we cannot merge
1929 // it with the tail block.
1930 MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001931 if (TI != BBI.BB->end() && TII->isPredicated(*TI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00001932 CanMergeTail = false;
Bob Wilson1e5da552010-06-29 00:55:23 +00001933 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1934 // check if there are any other predecessors besides those.
1935 unsigned NumPreds = TailBB->pred_size();
1936 if (NumPreds > 1)
1937 CanMergeTail = false;
1938 else if (NumPreds == 1 && CanMergeTail) {
1939 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
Kyle Butta8c73712016-08-24 21:34:27 +00001940 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
Bob Wilson1e5da552010-06-29 00:55:23 +00001941 CanMergeTail = false;
1942 }
1943 if (CanMergeTail) {
Evan Cheng0598b2d2007-06-18 22:44:57 +00001944 MergeBlocks(BBI, TailBBI);
Evan Cheng51eb2c32007-06-18 08:37:25 +00001945 TailBBI.IsDone = true;
1946 } else {
Cong Houd97c1002015-12-01 05:29:22 +00001947 BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
Matthias Braun08f47042016-08-17 02:52:01 +00001948 InsertUncondBranch(*BBI.BB, *TailBB, TII);
Evan Cheng0598b2d2007-06-18 22:44:57 +00001949 BBI.HasFallThrough = false;
Evan Cheng51eb2c32007-06-18 08:37:25 +00001950 }
Evan Chenge26c0912007-05-21 22:22:58 +00001951 }
1952
Evan Cheng79484222007-06-05 23:46:14 +00001953 // Update block info.
Evan Cheng4dd31a72007-06-11 22:26:22 +00001954 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Matthias Braun08f47042016-08-17 02:52:01 +00001955 InvalidatePreds(*BBI.BB);
Evan Chenge26c0912007-05-21 22:22:58 +00001956
1957 // FIXME: Must maintain LiveIns.
Evan Chenge26c0912007-05-21 22:22:58 +00001958 return true;
Evan Chengf5e53a52007-05-16 02:00:57 +00001959}
1960
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001961static bool MaySpeculate(const MachineInstr &MI,
Matthias Braun07066cc2015-05-19 21:22:20 +00001962 SmallSet<unsigned, 4> &LaterRedefs) {
Evan Cheng4266a792011-12-19 22:01:30 +00001963 bool SawStore = true;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001964 if (!MI.isSafeToMove(nullptr, SawStore))
Evan Cheng4266a792011-12-19 22:01:30 +00001965 return false;
1966
Matthias Braunb1e05582016-08-17 02:51:59 +00001967 for (const MachineOperand &MO : MI.operands()) {
Evan Cheng4266a792011-12-19 22:01:30 +00001968 if (!MO.isReg())
1969 continue;
1970 unsigned Reg = MO.getReg();
1971 if (!Reg)
1972 continue;
1973 if (MO.isDef() && !LaterRedefs.count(Reg))
1974 return false;
1975 }
1976
1977 return true;
1978}
1979
Matthias Braun2c931792016-08-17 02:51:57 +00001980/// Predicate instructions from the start of the block to the specified end with
1981/// the specified condition.
Evan Chengd0e66912007-05-23 07:23:16 +00001982void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Cheng51eb2c32007-06-18 08:37:25 +00001983 MachineBasicBlock::iterator E,
Evan Chengf128bdc2010-06-16 07:35:02 +00001984 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng4266a792011-12-19 22:01:30 +00001985 SmallSet<unsigned, 4> *LaterRedefs) {
1986 bool AnyUnpred = false;
Craig Topperc0196b12014-04-14 00:51:57 +00001987 bool MaySpec = LaterRedefs != nullptr;
Matthias Braunb1e05582016-08-17 02:51:59 +00001988 for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00001989 if (I.isDebugValue() || TII->isPredicated(I))
Evan Chengd0e66912007-05-23 07:23:16 +00001990 continue;
Evan Cheng4266a792011-12-19 22:01:30 +00001991 // It may be possible not to predicate an instruction if it's the 'true'
1992 // side of a diamond and the 'false' side may re-define the instruction's
1993 // defs.
Matthias Braun07066cc2015-05-19 21:22:20 +00001994 if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
Evan Cheng4266a792011-12-19 22:01:30 +00001995 AnyUnpred = true;
1996 continue;
1997 }
1998 // If any instruction is predicated, then every instruction after it must
1999 // be predicated.
2000 MaySpec = false;
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002001 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002002#ifndef NDEBUG
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002003 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002004#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002005 llvm_unreachable(nullptr);
Evan Chengaf716102007-05-16 21:54:37 +00002006 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002007
Bob Wilson45814342010-06-19 05:33:57 +00002008 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002009 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith0490cde2016-06-30 23:04:51 +00002010 UpdatePredRedefs(I, Redefs);
Evan Chengf5e53a52007-05-16 02:00:57 +00002011 }
Evan Chengd0e66912007-05-23 07:23:16 +00002012
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002013 BBI.Predicate.append(Cond.begin(), Cond.end());
Evan Chengdf1a4292007-06-08 19:17:12 +00002014
Evan Cheng92fb5452007-06-15 07:36:12 +00002015 BBI.IsAnalyzed = false;
2016 BBI.NonPredSize = 0;
2017
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002018 ++NumIfConvBBs;
Evan Cheng4266a792011-12-19 22:01:30 +00002019 if (AnyUnpred)
2020 ++NumUnpred;
Evan Cheng312b7232007-06-04 06:47:22 +00002021}
2022
Matthias Braun2c931792016-08-17 02:51:57 +00002023/// Copy and predicate instructions from source BB to the destination block.
2024/// Skip end of block branches if IgnoreBr is true.
Evan Cheng92fb5452007-06-15 07:36:12 +00002025void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson4f6bf042008-08-14 22:49:33 +00002026 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng92fb5452007-06-15 07:36:12 +00002027 bool IgnoreBr) {
Dan Gohman3b460302008-07-07 23:14:23 +00002028 MachineFunction &MF = *ToBBI.BB->getParent();
2029
Matthias Braun08f47042016-08-17 02:52:01 +00002030 MachineBasicBlock &FromMBB = *FromBBI.BB;
2031 for (MachineInstr &I : FromMBB) {
Evan Cheng92fb5452007-06-15 07:36:12 +00002032 // Do not copy the end of the block branches.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002033 if (IgnoreBr && I.isBranch())
Evan Cheng92fb5452007-06-15 07:36:12 +00002034 break;
2035
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002036 MachineInstr *MI = MF.CloneMachineInstr(&I);
Evan Cheng92fb5452007-06-15 07:36:12 +00002037 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilsonefd360c2010-10-26 00:02:21 +00002038 ToBBI.NonPredSize++;
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002039 unsigned ExtraPredCost = TII->getPredicationCost(I);
2040 unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
Evan Chengdebf9c52010-11-03 00:45:17 +00002041 if (NumCycles > 1)
2042 ToBBI.ExtraCost += NumCycles-1;
2043 ToBBI.ExtraCost2 += ExtraPredCost;
Evan Cheng92fb5452007-06-15 07:36:12 +00002044
Bob Wilsonf82c8fc2010-06-18 17:07:23 +00002045 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002046 if (!TII->PredicateInstruction(*MI, Cond)) {
Torok Edwin08954aa2009-07-12 20:07:01 +00002047#ifndef NDEBUG
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002048 dbgs() << "Unable to predicate " << I << "!\n";
Torok Edwin08954aa2009-07-12 20:07:01 +00002049#endif
Craig Topperc0196b12014-04-14 00:51:57 +00002050 llvm_unreachable(nullptr);
Evan Cheng92fb5452007-06-15 07:36:12 +00002051 }
Evan Chengf128bdc2010-06-16 07:35:02 +00002052 }
2053
Bob Wilson45814342010-06-19 05:33:57 +00002054 // If the predicated instruction now redefines a register as the result of
Evan Chengf128bdc2010-06-16 07:35:02 +00002055 // if-conversion, add an implicit kill.
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00002056 UpdatePredRedefs(*MI, Redefs);
Evan Cheng92fb5452007-06-15 07:36:12 +00002057 }
2058
Bob Wilson1e5da552010-06-29 00:55:23 +00002059 if (!IgnoreBr) {
Matthias Braun08f47042016-08-17 02:52:01 +00002060 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2061 FromMBB.succ_end());
2062 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002063 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Evan Cheng0598b2d2007-06-18 22:44:57 +00002064
Matthias Braunb1e05582016-08-17 02:51:59 +00002065 for (MachineBasicBlock *Succ : Succs) {
Bob Wilson1e5da552010-06-29 00:55:23 +00002066 // Fallthrough edge can't be transferred.
2067 if (Succ == FallThrough)
2068 continue;
2069 ToBBI.BB->addSuccessor(Succ);
2070 }
Evan Cheng0598b2d2007-06-18 22:44:57 +00002071 }
2072
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002073 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2074 ToBBI.Predicate.append(Cond.begin(), Cond.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002075
2076 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2077 ToBBI.IsAnalyzed = false;
2078
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002079 ++NumDupBBs;
Evan Cheng92fb5452007-06-15 07:36:12 +00002080}
2081
Matthias Braun2c931792016-08-17 02:51:57 +00002082/// Move all instructions from FromBB to the end of ToBB. This will leave
2083/// FromBB as an empty block, so remove all of its successor edges except for
2084/// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
Mikael Holmen8b106802017-08-11 06:57:08 +00002085/// being moved, add those successor edges to ToBBI and remove the old edge
2086/// from ToBBI to FromBBI.
Bob Wilson1e5da552010-06-29 00:55:23 +00002087void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Matthias Braun08f47042016-08-17 02:52:01 +00002088 MachineBasicBlock &FromMBB = *FromBBI.BB;
2089 assert(!FromMBB.hasAddressTaken() &&
Evan Cheng8b8e8d82013-05-05 18:03:49 +00002090 "Removing a BB whose address is taken!");
2091
Matthias Braun08f47042016-08-17 02:52:01 +00002092 // In case FromMBB contains terminators (e.g. return instruction),
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002093 // first move the non-terminator instructions, then the terminators.
Matthias Braun08f47042016-08-17 02:52:01 +00002094 MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002095 MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
Matthias Braun08f47042016-08-17 02:52:01 +00002096 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002097
2098 // If FromBB has non-predicated terminator we should copy it at the end.
Matthias Braun08f47042016-08-17 02:52:01 +00002099 if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
Krzysztof Parzyszek2451c482016-01-20 13:14:52 +00002100 ToTI = ToBBI.BB->end();
Matthias Braun08f47042016-08-17 02:52:01 +00002101 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
Evan Chengd0e66912007-05-23 07:23:16 +00002102
Cong Houb9e8d482015-12-17 01:29:08 +00002103 // Force normalizing the successors' probabilities of ToBBI.BB to convert all
2104 // unknown probabilities into known ones.
2105 // FIXME: This usage is too tricky and in the future we would like to
2106 // eliminate all unknown probabilities in MBB.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002107 if (ToBBI.IsBrAnalyzable)
2108 ToBBI.BB->normalizeSuccProbs();
Cong Houb9e8d482015-12-17 01:29:08 +00002109
Matthias Braun08f47042016-08-17 02:52:01 +00002110 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
2111 FromMBB.succ_end());
2112 MachineBasicBlock *NBB = getNextBlock(FromMBB);
Craig Topperc0196b12014-04-14 00:51:57 +00002113 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
Matthias Braun08f47042016-08-17 02:52:01 +00002114 // The edge probability from ToBBI.BB to FromMBB, which is only needed when
2115 // AddEdges is true and FromMBB is a successor of ToBBI.BB.
Cong Houd97c1002015-12-01 05:29:22 +00002116 auto To2FromProb = BranchProbability::getZero();
Matthias Braun08f47042016-08-17 02:52:01 +00002117 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
Mikael Holmen8b106802017-08-11 06:57:08 +00002118 // Remove the old edge but remember the edge probability so we can calculate
2119 // the correct weights on the new edges being added further down.
Matthias Braun08f47042016-08-17 02:52:01 +00002120 To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
Mikael Holmen8b106802017-08-11 06:57:08 +00002121 ToBBI.BB->removeSuccessor(&FromMBB);
Cong Houd97c1002015-12-01 05:29:22 +00002122 }
2123
Matthias Braunb1e05582016-08-17 02:51:59 +00002124 for (MachineBasicBlock *Succ : FromSuccs) {
Evan Cheng288f1542007-06-08 22:01:07 +00002125 // Fallthrough edge can't be transferred.
Evan Chengbe9859e2007-06-07 02:12:15 +00002126 if (Succ == FallThrough)
2127 continue;
Cong Houd40105d2015-09-18 20:22:41 +00002128
Cong Houd97c1002015-12-01 05:29:22 +00002129 auto NewProb = BranchProbability::getZero();
Cong Houd40105d2015-09-18 20:22:41 +00002130 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002131 // Calculate the edge probability for the edge from ToBBI.BB to Succ,
Matthias Braun08f47042016-08-17 02:52:01 +00002132 // which is a portion of the edge probability from FromMBB to Succ. The
2133 // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
Cong Houd97c1002015-12-01 05:29:22 +00002134 // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
Matthias Braun08f47042016-08-17 02:52:01 +00002135 NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002136
Matthias Braun08f47042016-08-17 02:52:01 +00002137 // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
2138 // only happens when if-converting a diamond CFG and FromMBB is the
2139 // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
2140 // could just use the probabilities on FromMBB's out-edges when adding
Cong Houd97c1002015-12-01 05:29:22 +00002141 // new successors.
2142 if (!To2FromProb.isZero())
2143 NewProb *= To2FromProb;
Cong Houd40105d2015-09-18 20:22:41 +00002144 }
2145
Matthias Braun08f47042016-08-17 02:52:01 +00002146 FromMBB.removeSuccessor(Succ);
Cong Houd40105d2015-09-18 20:22:41 +00002147
2148 if (AddEdges) {
Cong Houd97c1002015-12-01 05:29:22 +00002149 // If the edge from ToBBI.BB to Succ already exists, update the
Cong Houc1069892015-12-13 09:26:17 +00002150 // probability of this edge by adding NewProb to it. An example is shown
Matthias Braun08f47042016-08-17 02:52:01 +00002151 // below, in which A is ToBBI.BB and B is FromMBB. In this case we
Cong Houd97c1002015-12-01 05:29:22 +00002152 // don't have to set C as A's successor as it already is. We only need to
2153 // update the edge probability on A->C. Note that B will not be
2154 // immediately removed from A's successors. It is possible that B->D is
2155 // not removed either if D is a fallthrough of B. Later the edge A->D
2156 // (generated here) and B->D will be combined into one edge. To maintain
2157 // correct edge probability of this combined edge, we need to set the edge
2158 // probability of A->B to zero, which is already done above. The edge
2159 // probability on A->D is calculated by scaling the original probability
2160 // on A->B by the probability of B->D.
Cong Houd40105d2015-09-18 20:22:41 +00002161 //
2162 // Before ifcvt: After ifcvt (assume B->D is kept):
2163 //
2164 // A A
2165 // /| /|\
2166 // / B / B|
2167 // | /| | ||
2168 // |/ | | |/
2169 // C D C D
2170 //
2171 if (ToBBI.BB->isSuccessor(Succ))
Cong Houd97c1002015-12-01 05:29:22 +00002172 ToBBI.BB->setSuccProbability(
David Majnemer42531262016-08-12 03:55:06 +00002173 find(ToBBI.BB->successors(), Succ),
Cong Houd97c1002015-12-01 05:29:22 +00002174 MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002175 else
Cong Houd97c1002015-12-01 05:29:22 +00002176 ToBBI.BB->addSuccessor(Succ, NewProb);
Cong Houd40105d2015-09-18 20:22:41 +00002177 }
Evan Chengbe9859e2007-06-07 02:12:15 +00002178 }
2179
Mikael Holmen8b106802017-08-11 06:57:08 +00002180 // Move the now empty FromMBB out of the way to the end of the function so
2181 // it doesn't interfere with fallthrough checks done by canFallThroughTo().
2182 MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
2183 if (Last != &FromMBB)
2184 FromMBB.moveAfter(Last);
Evan Cheng288f1542007-06-08 22:01:07 +00002185
Cong Houc1069892015-12-13 09:26:17 +00002186 // Normalize the probabilities of ToBBI.BB's successors with all adjustment
2187 // we've done above.
Krzysztof Parzyszek5b8fae52017-03-06 19:12:42 +00002188 if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2189 ToBBI.BB->normalizeSuccProbs();
Cong Houc1069892015-12-13 09:26:17 +00002190
Benjamin Kramer4f6ac162015-02-28 10:11:12 +00002191 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
Evan Cheng92fb5452007-06-15 07:36:12 +00002192 FromBBI.Predicate.clear();
2193
Evan Chengd0e66912007-05-23 07:23:16 +00002194 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002195 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chengdebf9c52010-11-03 00:45:17 +00002196 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
Evan Chengd0e66912007-05-23 07:23:16 +00002197 FromBBI.NonPredSize = 0;
Bob Wilsonefd360c2010-10-26 00:02:21 +00002198 FromBBI.ExtraCost = 0;
Evan Chengdebf9c52010-11-03 00:45:17 +00002199 FromBBI.ExtraCost2 = 0;
Evan Cheng9030b982007-06-06 10:16:17 +00002200
Evan Cheng4dd31a72007-06-11 22:26:22 +00002201 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng2117d1f2007-06-09 01:03:43 +00002202 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng1e6f08b2007-06-14 20:28:52 +00002203 ToBBI.IsAnalyzed = false;
2204 FromBBI.IsAnalyzed = false;
Evan Chengf5e53a52007-05-16 02:00:57 +00002205}
Akira Hatanaka4a616192015-06-08 18:50:43 +00002206
2207FunctionPass *
Matthias Braun8b38ffa2016-10-24 23:23:02 +00002208llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
Benjamin Kramerd3f4c052016-06-12 16:13:55 +00002209 return new IfConverter(std::move(Ftor));
Akira Hatanaka4a616192015-06-08 18:50:43 +00002210}