blob: 33597705cae2835e50a41af82fde7869b33837cc [file] [log] [blame]
Sanjoy Das083f3892016-05-18 22:55:34 +00001//===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sanjoy Das083f3892016-05-18 22:55:34 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the guard widening pass. The semantics of the
10// @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
11// more often that it did before the transform. This optimization is called
12// "widening" and can be used hoist and common runtime checks in situations like
13// these:
14//
15// %cmp0 = 7 u< Length
16// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
17// call @unknown_side_effects()
18// %cmp1 = 9 u< Length
19// call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
20// ...
21//
22// =>
23//
24// %cmp0 = 9 u< Length
25// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
26// call @unknown_side_effects()
27// ...
28//
29// If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
30// generic implementation of the same function, which will have the correct
31// semantics from that point onward. It is always _legal_ to deoptimize (so
32// replacing %cmp0 with false is "correct"), though it may not always be
33// profitable to do so.
34//
35// NB! This pass is a work in progress. It hasn't been tuned to be "production
36// ready" yet. It is known to have quadriatic running time and will not scale
37// to large numbers of guards
38//
39//===----------------------------------------------------------------------===//
40
41#include "llvm/Transforms/Scalar/GuardWidening.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000042#include <functional>
Sanjoy Das083f3892016-05-18 22:55:34 +000043#include "llvm/ADT/DenseMap.h"
44#include "llvm/ADT/DepthFirstIterator.h"
Max Kazantseveb8e9c02018-07-31 04:37:11 +000045#include "llvm/ADT/Statistic.h"
Max Kazantseveded4ab2018-08-06 05:49:19 +000046#include "llvm/Analysis/BranchProbabilityInfo.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000047#include "llvm/Analysis/GuardUtils.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000048#include "llvm/Analysis/LoopInfo.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000049#include "llvm/Analysis/LoopPass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000050#include "llvm/Analysis/PostDominators.h"
51#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000052#include "llvm/IR/ConstantRange.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/Pass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000057#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000058#include "llvm/Support/KnownBits.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000059#include "llvm/Transforms/Scalar.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000060#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000061
62using namespace llvm;
63
64#define DEBUG_TYPE "guard-widening"
65
Max Kazantseveb8e9c02018-07-31 04:37:11 +000066STATISTIC(GuardsEliminated, "Number of eliminated guards");
Max Kazantseveded4ab2018-08-06 05:49:19 +000067STATISTIC(CondBranchEliminated, "Number of eliminated conditional branches");
68
69static cl::opt<bool> WidenFrequentBranches(
70 "guard-widening-widen-frequent-branches", cl::Hidden,
71 cl::desc("Widen conditions of explicit branches into dominating guards in "
72 "case if their taken frequency exceeds threshold set by "
73 "guard-widening-frequent-branch-threshold option"),
74 cl::init(false));
75
76static cl::opt<unsigned> FrequentBranchThreshold(
77 "guard-widening-frequent-branch-threshold", cl::Hidden,
78 cl::desc("When WidenFrequentBranches is set to true, this option is used "
79 "to determine which branches are frequently taken. The criteria "
80 "that a branch is taken more often than "
81 "((FrequentBranchThreshold - 1) / FrequentBranchThreshold), then "
82 "it is considered frequently taken"),
83 cl::init(1000));
84
Max Kazantseveb8e9c02018-07-31 04:37:11 +000085
Sanjoy Das083f3892016-05-18 22:55:34 +000086namespace {
87
Max Kazantseveded4ab2018-08-06 05:49:19 +000088// Get the condition of \p I. It can either be a guard or a conditional branch.
89static Value *getCondition(Instruction *I) {
90 if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
91 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
92 "Bad guard intrinsic?");
93 return GI->getArgOperand(0);
94 }
95 return cast<BranchInst>(I)->getCondition();
Max Kazantsev65cd4832018-08-03 10:16:40 +000096}
97
Max Kazantseveded4ab2018-08-06 05:49:19 +000098// Set the condition for \p I to \p NewCond. \p I can either be a guard or a
99// conditional branch.
100static void setCondition(Instruction *I, Value *NewCond) {
101 if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
102 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
103 "Bad guard intrinsic?");
104 GI->setArgOperand(0, NewCond);
105 return;
106 }
107 cast<BranchInst>(I)->setCondition(NewCond);
Max Kazantsev65cd4832018-08-03 10:16:40 +0000108}
109
Max Kazantsev65cd4832018-08-03 10:16:40 +0000110// Eliminates the guard instruction properly.
111static void eliminateGuard(Instruction *GuardInst) {
112 GuardInst->eraseFromParent();
113 ++GuardsEliminated;
114}
115
Sanjoy Das083f3892016-05-18 22:55:34 +0000116class GuardWideningImpl {
117 DominatorTree &DT;
Philip Reames502d44812018-04-27 23:15:56 +0000118 PostDominatorTree *PDT;
Sanjoy Das083f3892016-05-18 22:55:34 +0000119 LoopInfo &LI;
Max Kazantseveded4ab2018-08-06 05:49:19 +0000120 BranchProbabilityInfo *BPI;
Sanjoy Das083f3892016-05-18 22:55:34 +0000121
Philip Reames9258e9d2018-04-27 17:29:10 +0000122 /// Together, these describe the region of interest. This might be all of
123 /// the blocks within a function, or only a given loop's blocks and preheader.
124 DomTreeNode *Root;
125 std::function<bool(BasicBlock*)> BlockFilter;
126
Max Kazantseveded4ab2018-08-06 05:49:19 +0000127 /// The set of guards and conditional branches whose conditions have been
128 /// widened into dominating guards.
129 SmallVector<Instruction *, 16> EliminatedGuardsAndBranches;
Sanjoy Das083f3892016-05-18 22:55:34 +0000130
131 /// The set of guards which have been widened to include conditions to other
132 /// guards.
Max Kazantsev3327bca2018-07-30 07:07:32 +0000133 DenseSet<Instruction *> WidenedGuards;
Sanjoy Das083f3892016-05-18 22:55:34 +0000134
Max Kazantsev09802f42019-02-04 10:31:18 +0000135 /// Try to eliminate instruction \p Instr by widening it into an earlier
136 /// dominating guard. \p DFSI is the DFS iterator on the dominator tree that
137 /// is currently visiting the block containing \p Guard, and \p GuardsPerBlock
Sanjoy Das083f3892016-05-18 22:55:34 +0000138 /// maps BasicBlocks to the set of guards seen in that block.
Max Kazantsev09802f42019-02-04 10:31:18 +0000139 bool eliminateInstrViaWidening(
140 Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
Max Kazantsev3327bca2018-07-30 07:07:32 +0000141 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Max Kazantsev5c490b42018-08-13 07:58:19 +0000142 GuardsPerBlock, bool InvertCondition = false);
Sanjoy Das083f3892016-05-18 22:55:34 +0000143
144 /// Used to keep track of which widening potential is more effective.
145 enum WideningScore {
146 /// Don't widen.
147 WS_IllegalOrNegative,
148
149 /// Widening is performance neutral as far as the cycles spent in check
150 /// conditions goes (but can still help, e.g., code layout, having less
151 /// deopt state).
152 WS_Neutral,
153
154 /// Widening is profitable.
155 WS_Positive,
156
157 /// Widening is very profitable. Not significantly different from \c
158 /// WS_Positive, except by the order.
159 WS_VeryPositive
160 };
161
162 static StringRef scoreTypeToString(WideningScore WS);
163
Max Kazantsev09802f42019-02-04 10:31:18 +0000164 /// Compute the score for widening the condition in \p DominatedInstr
Max Kazantsev13ab5cb2019-02-04 10:20:51 +0000165 /// into \p DominatingGuard. If \p InvertCond is set, then we widen the
Max Kazantsev5c490b42018-08-13 07:58:19 +0000166 /// inverted condition of the dominating guard.
Max Kazantsev09802f42019-02-04 10:31:18 +0000167 WideningScore computeWideningScore(Instruction *DominatedInstr,
Max Kazantsev3327bca2018-07-30 07:07:32 +0000168 Instruction *DominatingGuard,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000169 bool InvertCond);
Sanjoy Das083f3892016-05-18 22:55:34 +0000170
171 /// Helper to check if \p V can be hoisted to \p InsertPos.
172 bool isAvailableAt(Value *V, Instruction *InsertPos) {
173 SmallPtrSet<Instruction *, 8> Visited;
174 return isAvailableAt(V, InsertPos, Visited);
175 }
176
177 bool isAvailableAt(Value *V, Instruction *InsertPos,
178 SmallPtrSetImpl<Instruction *> &Visited);
179
180 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
181 /// isAvailableAt returned true.
182 void makeAvailableAt(Value *V, Instruction *InsertPos);
183
184 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
Max Kazantsev5c490b42018-08-13 07:58:19 +0000185 /// to generate an expression computing the logical AND of \p Cond0 and (\p
186 /// Cond1 XOR \p InvertCondition).
187 /// Return true if the expression computing the AND is only as
Sanjoy Das083f3892016-05-18 22:55:34 +0000188 /// expensive as computing one of the two. If \p InsertPt is true then
189 /// actually generate the resulting expression, make it available at \p
190 /// InsertPt and return it in \p Result (else no change to the IR is made).
191 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000192 Value *&Result, bool InvertCondition);
Sanjoy Das083f3892016-05-18 22:55:34 +0000193
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000194 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
195 /// with the constraint that \c Length is not negative. \c CheckInst is the
196 /// pre-existing instruction in the IR that computes the result of this range
197 /// check.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000198 class RangeCheck {
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000199 Value *Base;
200 ConstantInt *Offset;
201 Value *Length;
202 ICmpInst *CheckInst;
203
Sanjoy Dasbe991532016-05-24 20:54:45 +0000204 public:
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000205 explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
206 ICmpInst *CheckInst)
207 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
208
Sanjoy Dasbe991532016-05-24 20:54:45 +0000209 void setBase(Value *NewBase) { Base = NewBase; }
210 void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
211
212 Value *getBase() const { return Base; }
213 ConstantInt *getOffset() const { return Offset; }
214 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
215 Value *getLength() const { return Length; };
216 ICmpInst *getCheckInst() const { return CheckInst; }
217
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000218 void print(raw_ostream &OS, bool PrintTypes = false) {
219 OS << "Base: ";
220 Base->printAsOperand(OS, PrintTypes);
221 OS << " Offset: ";
222 Offset->printAsOperand(OS, PrintTypes);
223 OS << " Length: ";
224 Length->printAsOperand(OS, PrintTypes);
225 }
226
227 LLVM_DUMP_METHOD void dump() {
228 print(dbgs());
229 dbgs() << "\n";
230 }
231 };
232
233 /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
234 /// append them to \p Checks. Returns true on success, may clobber \c Checks
235 /// on failure.
236 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
237 SmallPtrSet<Value *, 8> Visited;
238 return parseRangeChecks(CheckCond, Checks, Visited);
239 }
240
241 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
242 SmallPtrSetImpl<Value *> &Visited);
243
244 /// Combine the checks in \p Checks into a smaller set of checks and append
245 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
246 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
247 /// and \p CombinedChecks on success and on failure.
248 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
249 SmallVectorImpl<RangeCheck> &CombinedChecks);
250
Sanjoy Das083f3892016-05-18 22:55:34 +0000251 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
252 /// computing only one of the two expressions?
Max Kazantsev5c490b42018-08-13 07:58:19 +0000253 bool isWideningCondProfitable(Value *Cond0, Value *Cond1, bool InvertCond) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000254 Value *ResultUnused;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000255 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused,
256 InvertCond);
Sanjoy Das083f3892016-05-18 22:55:34 +0000257 }
258
Max Kazantsev5c490b42018-08-13 07:58:19 +0000259 /// If \p InvertCondition is false, Widen \p ToWiden to fail if
260 /// \p NewCondition is false, otherwise make it fail if \p NewCondition is
261 /// true (in addition to whatever it is already checking).
262 void widenGuard(Instruction *ToWiden, Value *NewCondition,
263 bool InvertCondition) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000264 Value *Result;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000265 widenCondCommon(ToWiden->getOperand(0), NewCondition, ToWiden, Result,
266 InvertCondition);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000267 setCondition(ToWiden, Result);
Sanjoy Das083f3892016-05-18 22:55:34 +0000268 }
269
270public:
Philip Reames9258e9d2018-04-27 17:29:10 +0000271
Philip Reames502d44812018-04-27 23:15:56 +0000272 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
Max Kazantseveded4ab2018-08-06 05:49:19 +0000273 LoopInfo &LI, BranchProbabilityInfo *BPI,
274 DomTreeNode *Root,
Philip Reames9258e9d2018-04-27 17:29:10 +0000275 std::function<bool(BasicBlock*)> BlockFilter)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000276 : DT(DT), PDT(PDT), LI(LI), BPI(BPI), Root(Root), BlockFilter(BlockFilter)
277 {}
Sanjoy Das083f3892016-05-18 22:55:34 +0000278
279 /// The entry point for this pass.
280 bool run();
281};
Sanjoy Das083f3892016-05-18 22:55:34 +0000282}
283
284bool GuardWideningImpl::run() {
Max Kazantsev3327bca2018-07-30 07:07:32 +0000285 DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
Sanjoy Das083f3892016-05-18 22:55:34 +0000286 bool Changed = false;
Max Kazantseveded4ab2018-08-06 05:49:19 +0000287 Optional<BranchProbability> LikelyTaken = None;
288 if (WidenFrequentBranches && BPI) {
289 unsigned Threshold = FrequentBranchThreshold;
290 assert(Threshold > 0 && "Zero threshold makes no sense!");
Max Kazantsev778f62b2018-08-06 06:35:21 +0000291 LikelyTaken = BranchProbability(Threshold - 1, Threshold);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000292 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000293
Philip Reames9258e9d2018-04-27 17:29:10 +0000294 for (auto DFI = df_begin(Root), DFE = df_end(Root);
Sanjoy Das083f3892016-05-18 22:55:34 +0000295 DFI != DFE; ++DFI) {
296 auto *BB = (*DFI)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000297 if (!BlockFilter(BB))
298 continue;
299
Sanjoy Das083f3892016-05-18 22:55:34 +0000300 auto &CurrentList = GuardsInBlock[BB];
301
302 for (auto &I : *BB)
Max Kazantsev3327bca2018-07-30 07:07:32 +0000303 if (isGuard(&I))
304 CurrentList.push_back(cast<Instruction>(&I));
Sanjoy Das083f3892016-05-18 22:55:34 +0000305
306 for (auto *II : CurrentList)
Max Kazantsev09802f42019-02-04 10:31:18 +0000307 Changed |= eliminateInstrViaWidening(II, DFI, GuardsInBlock);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000308 if (WidenFrequentBranches && BPI)
309 if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator()))
Max Kazantsev5c490b42018-08-13 07:58:19 +0000310 if (BI->isConditional()) {
311 // If one of branches of a conditional is likely taken, try to
312 // eliminate it.
313 if (BPI->getEdgeProbability(BB, 0U) >= *LikelyTaken)
Max Kazantsev09802f42019-02-04 10:31:18 +0000314 Changed |= eliminateInstrViaWidening(BI, DFI, GuardsInBlock);
Max Kazantsev5c490b42018-08-13 07:58:19 +0000315 else if (BPI->getEdgeProbability(BB, 1U) >= *LikelyTaken)
Max Kazantsev09802f42019-02-04 10:31:18 +0000316 Changed |= eliminateInstrViaWidening(BI, DFI, GuardsInBlock,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000317 /*InvertCondition*/true);
318 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000319 }
320
Max Kazantseveded4ab2018-08-06 05:49:19 +0000321 assert(EliminatedGuardsAndBranches.empty() || Changed);
322 for (auto *I : EliminatedGuardsAndBranches)
323 if (!WidenedGuards.count(I)) {
324 assert(isa<ConstantInt>(getCondition(I)) && "Should be!");
325 if (isGuard(I))
326 eliminateGuard(I);
327 else {
328 assert(isa<BranchInst>(I) &&
329 "Eliminated something other than guard or branch?");
330 ++CondBranchEliminated;
331 }
332 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000333
334 return Changed;
335}
336
Max Kazantsev09802f42019-02-04 10:31:18 +0000337bool GuardWideningImpl::eliminateInstrViaWidening(
338 Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
Max Kazantsev3327bca2018-07-30 07:07:32 +0000339 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Max Kazantsev5c490b42018-08-13 07:58:19 +0000340 GuardsInBlock, bool InvertCondition) {
Max Kazantsev611d6452018-08-22 02:40:49 +0000341 // Ignore trivial true or false conditions. These instructions will be
342 // trivially eliminated by any cleanup pass. Do not erase them because other
343 // guards can possibly be widened into them.
Max Kazantsev09802f42019-02-04 10:31:18 +0000344 if (isa<ConstantInt>(getCondition(Instr)))
Max Kazantsev611d6452018-08-22 02:40:49 +0000345 return false;
346
Max Kazantsev3327bca2018-07-30 07:07:32 +0000347 Instruction *BestSoFar = nullptr;
Sanjoy Das083f3892016-05-18 22:55:34 +0000348 auto BestScoreSoFar = WS_IllegalOrNegative;
Sanjoy Das083f3892016-05-18 22:55:34 +0000349
350 // In the set of dominating guards, find the one we can merge GuardInst with
351 // for the most profit.
352 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
353 auto *CurBB = DFSI.getPath(i)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000354 if (!BlockFilter(CurBB))
355 break;
Sanjoy Das083f3892016-05-18 22:55:34 +0000356 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
357 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
358
359 auto I = GuardsInCurBB.begin();
360 auto E = GuardsInCurBB.end();
361
362#ifndef NDEBUG
363 {
364 unsigned Index = 0;
365 for (auto &I : *CurBB) {
366 if (Index == GuardsInCurBB.size())
367 break;
368 if (GuardsInCurBB[Index] == &I)
369 Index++;
370 }
371 assert(Index == GuardsInCurBB.size() &&
372 "Guards expected to be in order!");
373 }
374#endif
375
Max Kazantsev09802f42019-02-04 10:31:18 +0000376 assert((i == (e - 1)) == (Instr->getParent() == CurBB) && "Bad DFS?");
Sanjoy Das083f3892016-05-18 22:55:34 +0000377
Max Kazantsev09802f42019-02-04 10:31:18 +0000378 if (Instr->getParent() == CurBB && CurBB->getTerminator() != Instr) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000379 // Corner case: make sure we're only looking at guards strictly dominating
380 // GuardInst when visiting GuardInst->getParent().
Max Kazantsev09802f42019-02-04 10:31:18 +0000381 auto NewEnd = std::find(I, E, Instr);
Sanjoy Das083f3892016-05-18 22:55:34 +0000382 assert(NewEnd != E && "GuardInst not in its own block?");
383 E = NewEnd;
384 }
385
386 for (auto *Candidate : make_range(I, E)) {
Max Kazantsev09802f42019-02-04 10:31:18 +0000387 auto Score = computeWideningScore(Instr, Candidate, InvertCondition);
388 LLVM_DEBUG(dbgs() << "Score between " << *getCondition(Instr)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000389 << " and " << *getCondition(Candidate) << " is "
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000390 << scoreTypeToString(Score) << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000391 if (Score > BestScoreSoFar) {
392 BestScoreSoFar = Score;
393 BestSoFar = Candidate;
394 }
395 }
396 }
397
398 if (BestScoreSoFar == WS_IllegalOrNegative) {
Max Kazantsev09802f42019-02-04 10:31:18 +0000399 LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *Instr << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000400 return false;
401 }
402
Max Kazantsev09802f42019-02-04 10:31:18 +0000403 assert(BestSoFar != Instr && "Should have never visited same guard!");
404 assert(DT.dominates(BestSoFar, Instr) && "Should be!");
Sanjoy Das083f3892016-05-18 22:55:34 +0000405
Max Kazantsev09802f42019-02-04 10:31:18 +0000406 LLVM_DEBUG(dbgs() << "Widening " << *Instr << " into " << *BestSoFar
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 << " with score " << scoreTypeToString(BestScoreSoFar)
408 << "\n");
Max Kazantsev09802f42019-02-04 10:31:18 +0000409 widenGuard(BestSoFar, getCondition(Instr), InvertCondition);
Max Kazantsev5c490b42018-08-13 07:58:19 +0000410 auto NewGuardCondition = InvertCondition
Max Kazantsev09802f42019-02-04 10:31:18 +0000411 ? ConstantInt::getFalse(Instr->getContext())
412 : ConstantInt::getTrue(Instr->getContext());
413 setCondition(Instr, NewGuardCondition);
414 EliminatedGuardsAndBranches.push_back(Instr);
Sanjoy Das083f3892016-05-18 22:55:34 +0000415 WidenedGuards.insert(BestSoFar);
416 return true;
417}
418
Max Kazantsev13ab5cb2019-02-04 10:20:51 +0000419GuardWideningImpl::WideningScore
Max Kazantsev09802f42019-02-04 10:31:18 +0000420GuardWideningImpl::computeWideningScore(Instruction *DominatedInstr,
Max Kazantsev13ab5cb2019-02-04 10:20:51 +0000421 Instruction *DominatingGuard,
422 bool InvertCond) {
Max Kazantsev09802f42019-02-04 10:31:18 +0000423 Loop *DominatedInstrLoop = LI.getLoopFor(DominatedInstr->getParent());
Max Kazantsev13ab5cb2019-02-04 10:20:51 +0000424 Loop *DominatingGuardLoop = LI.getLoopFor(DominatingGuard->getParent());
Sanjoy Das083f3892016-05-18 22:55:34 +0000425 bool HoistingOutOfLoop = false;
426
Max Kazantsev09802f42019-02-04 10:31:18 +0000427 if (DominatingGuardLoop != DominatedInstrLoop) {
Philip Reamesde5a1da2018-04-27 17:41:37 +0000428 // Be conservative and don't widen into a sibling loop. TODO: If the
429 // sibling is colder, we should consider allowing this.
Sanjoy Das083f3892016-05-18 22:55:34 +0000430 if (DominatingGuardLoop &&
Max Kazantsev09802f42019-02-04 10:31:18 +0000431 !DominatingGuardLoop->contains(DominatedInstrLoop))
Sanjoy Das083f3892016-05-18 22:55:34 +0000432 return WS_IllegalOrNegative;
433
434 HoistingOutOfLoop = true;
435 }
436
Max Kazantsev09802f42019-02-04 10:31:18 +0000437 if (!isAvailableAt(getCondition(DominatedInstr), DominatingGuard))
Sanjoy Das083f3892016-05-18 22:55:34 +0000438 return WS_IllegalOrNegative;
439
Philip Reamesde5a1da2018-04-27 17:41:37 +0000440 // If the guard was conditional executed, it may never be reached
441 // dynamically. There are two potential downsides to hoisting it out of the
442 // conditionally executed region: 1) we may spuriously deopt without need and
443 // 2) we have the extra cost of computing the guard condition in the common
444 // case. At the moment, we really only consider the second in our heuristic
445 // here. TODO: evaluate cost model for spurious deopt
Philip Reames502d44812018-04-27 23:15:56 +0000446 // NOTE: As written, this also lets us hoist right over another guard which
Fangrui Songf78650a2018-07-30 19:41:25 +0000447 // is essentially just another spelling for control flow.
Max Kazantsev09802f42019-02-04 10:31:18 +0000448 if (isWideningCondProfitable(getCondition(DominatedInstr),
Max Kazantsev5c490b42018-08-13 07:58:19 +0000449 getCondition(DominatingGuard), InvertCond))
Sanjoy Das083f3892016-05-18 22:55:34 +0000450 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
451
452 if (HoistingOutOfLoop)
453 return WS_Positive;
454
Philip Reames502d44812018-04-27 23:15:56 +0000455 // Returns true if we might be hoisting above explicit control flow. Note
456 // that this completely ignores implicit control flow (guards, calls which
457 // throw, etc...). That choice appears arbitrary.
458 auto MaybeHoistingOutOfIf = [&]() {
459 auto *DominatingBlock = DominatingGuard->getParent();
Max Kazantsev09802f42019-02-04 10:31:18 +0000460 auto *DominatedBlock = DominatedInstr->getParent();
Fangrui Songf78650a2018-07-30 19:41:25 +0000461
Philip Reames502d44812018-04-27 23:15:56 +0000462 // Same Block?
463 if (DominatedBlock == DominatingBlock)
464 return false;
465 // Obvious successor (common loop header/preheader case)
466 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
467 return false;
468 // TODO: diamond, triangle cases
469 if (!PDT) return true;
Max Kazantsev9b25bf32018-12-25 07:20:06 +0000470 return !PDT->dominates(DominatedBlock, DominatingBlock);
Philip Reames502d44812018-04-27 23:15:56 +0000471 };
472
473 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
Sanjoy Das083f3892016-05-18 22:55:34 +0000474}
475
476bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
477 SmallPtrSetImpl<Instruction *> &Visited) {
478 auto *Inst = dyn_cast<Instruction>(V);
479 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
480 return true;
481
482 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
483 Inst->mayReadFromMemory())
484 return false;
485
486 Visited.insert(Inst);
487
488 // We only want to go _up_ the dominance chain when recursing.
489 assert(!isa<PHINode>(Loc) &&
490 "PHIs should return false for isSafeToSpeculativelyExecute");
491 assert(DT.isReachableFromEntry(Inst->getParent()) &&
492 "We did a DFS from the block entry!");
493 return all_of(Inst->operands(),
494 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
495}
496
497void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
498 auto *Inst = dyn_cast<Instruction>(V);
499 if (!Inst || DT.dominates(Inst, Loc))
500 return;
501
502 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
503 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
504
505 for (Value *Op : Inst->operands())
506 makeAvailableAt(Op, Loc);
507
508 Inst->moveBefore(Loc);
509}
510
511bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000512 Instruction *InsertPt, Value *&Result,
513 bool InvertCondition) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000514 using namespace llvm::PatternMatch;
515
516 {
517 // L >u C0 && L >u C1 -> L >u max(C0, C1)
518 ConstantInt *RHS0, *RHS1;
519 Value *LHS;
520 ICmpInst::Predicate Pred0, Pred1;
521 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
522 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
Max Kazantsev5c490b42018-08-13 07:58:19 +0000523 if (InvertCondition)
524 Pred1 = ICmpInst::getInversePredicate(Pred1);
Sanjoy Das083f3892016-05-18 22:55:34 +0000525
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000526 ConstantRange CR0 =
527 ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
528 ConstantRange CR1 =
529 ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
Sanjoy Das083f3892016-05-18 22:55:34 +0000530
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000531 // SubsetIntersect is a subset of the actual mathematical intersection of
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000532 // CR0 and CR1, while SupersetIntersect is a superset of the actual
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000533 // mathematical intersection. If these two ConstantRanges are equal, then
534 // we know we were able to represent the actual mathematical intersection
535 // of CR0 and CR1, and can use the same to generate an icmp instruction.
536 //
537 // Given what we're doing here and the semantics of guards, it would
538 // actually be correct to just use SubsetIntersect, but that may be too
539 // aggressive in cases we care about.
540 auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
541 auto SupersetIntersect = CR0.intersectWith(CR1);
542
543 APInt NewRHSAP;
544 CmpInst::Predicate Pred;
545 if (SubsetIntersect == SupersetIntersect &&
546 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000547 if (InsertPt) {
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000548 ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
549 Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
Sanjoy Das083f3892016-05-18 22:55:34 +0000550 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000551 return true;
552 }
553 }
554 }
555
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000556 {
557 SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000558 // TODO: Support InvertCondition case?
559 if (!InvertCondition &&
560 parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000561 combineRangeChecks(Checks, CombinedChecks)) {
562 if (InsertPt) {
563 Result = nullptr;
564 for (auto &RC : CombinedChecks) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000565 makeAvailableAt(RC.getCheckInst(), InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000566 if (Result)
Sanjoy Dasbe991532016-05-24 20:54:45 +0000567 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
568 InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000569 else
Sanjoy Dasbe991532016-05-24 20:54:45 +0000570 Result = RC.getCheckInst();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000571 }
572
573 Result->setName("wide.chk");
574 }
575 return true;
576 }
577 }
578
Sanjoy Das083f3892016-05-18 22:55:34 +0000579 // Base case -- just logical-and the two conditions together.
580
581 if (InsertPt) {
582 makeAvailableAt(Cond0, InsertPt);
583 makeAvailableAt(Cond1, InsertPt);
Max Kazantsev5c490b42018-08-13 07:58:19 +0000584 if (InvertCondition)
585 Cond1 = BinaryOperator::CreateNot(Cond1, "inverted", InsertPt);
Sanjoy Das083f3892016-05-18 22:55:34 +0000586 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
587 }
588
589 // We were not able to compute Cond0 AND Cond1 for the price of one.
590 return false;
591}
592
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000593bool GuardWideningImpl::parseRangeChecks(
594 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
595 SmallPtrSetImpl<Value *> &Visited) {
596 if (!Visited.insert(CheckCond).second)
597 return true;
598
599 using namespace llvm::PatternMatch;
600
601 {
602 Value *AndLHS, *AndRHS;
603 if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
604 return parseRangeChecks(AndLHS, Checks) &&
605 parseRangeChecks(AndRHS, Checks);
606 }
607
608 auto *IC = dyn_cast<ICmpInst>(CheckCond);
609 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
610 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
611 IC->getPredicate() != ICmpInst::ICMP_UGT))
612 return false;
613
614 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
615 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
616 std::swap(CmpLHS, CmpRHS);
617
618 auto &DL = IC->getModule()->getDataLayout();
619
Sanjoy Dasbe991532016-05-24 20:54:45 +0000620 GuardWideningImpl::RangeCheck Check(
621 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
622 CmpRHS, IC);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000623
Sanjoy Dasbe991532016-05-24 20:54:45 +0000624 if (!isKnownNonNegative(Check.getLength(), DL))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000625 return false;
626
627 // What we have in \c Check now is a correct interpretation of \p CheckCond.
628 // Try to see if we can move some constant offsets into the \c Offset field.
629
630 bool Changed;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000631 auto &Ctx = CheckCond->getContext();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000632
633 do {
634 Value *OpLHS;
635 ConstantInt *OpRHS;
636 Changed = false;
637
638#ifndef NDEBUG
Sanjoy Dasbe991532016-05-24 20:54:45 +0000639 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000640 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
641 "Unreachable instruction?");
642#endif
643
Sanjoy Dasbe991532016-05-24 20:54:45 +0000644 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
645 Check.setBase(OpLHS);
646 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
647 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000648 Changed = true;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000649 } else if (match(Check.getBase(),
650 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000651 KnownBits Known = computeKnownBits(OpLHS, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000652 if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000653 Check.setBase(OpLHS);
654 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
655 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000656 Changed = true;
657 }
658 }
659 } while (Changed);
660
661 Checks.push_back(Check);
662 return true;
663}
664
665bool GuardWideningImpl::combineRangeChecks(
666 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
667 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
668 unsigned OldCount = Checks.size();
669 while (!Checks.empty()) {
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000670 // Pick all of the range checks with a specific base and length, and try to
671 // merge them.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000672 Value *CurrentBase = Checks.front().getBase();
673 Value *CurrentLength = Checks.front().getLength();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000674
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000675 SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000676
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000677 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000678 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000679 };
680
Sanjoy Das90208722017-02-21 00:38:44 +0000681 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000682 Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
683
684 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
685
686 if (CurrentChecks.size() < 3) {
687 RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
688 CurrentChecks.end());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000689 continue;
690 }
691
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000692 // CurrentChecks.size() will typically be 3 here, but so far there has been
693 // no need to hard-code that fact.
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000694
Fangrui Song0cac7262018-09-27 02:13:45 +0000695 llvm::sort(CurrentChecks, [&](const GuardWideningImpl::RangeCheck &LHS,
696 const GuardWideningImpl::RangeCheck &RHS) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000697 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000698 });
699
700 // Note: std::sort should not invalidate the ChecksStart iterator.
701
Sanjoy Dasbe991532016-05-24 20:54:45 +0000702 ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
703 *MaxOffset = CurrentChecks.back().getOffset();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000704
705 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
706 if ((MaxOffset->getValue() - MinOffset->getValue())
707 .ugt(APInt::getSignedMinValue(BitWidth)))
708 return false;
709
710 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000711 const APInt &HighOffset = MaxOffset->getValue();
Sanjoy Das23519752016-05-19 23:15:59 +0000712 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000713 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000714 };
715
716 if (MaxDiff.isMinValue() ||
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000717 !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
718 OffsetOK))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000719 return false;
720
721 // We have a series of f+1 checks as:
722 //
723 // I+k_0 u< L ... Chk_0
Sanjoy Das23f314d2017-05-03 18:29:34 +0000724 // I+k_1 u< L ... Chk_1
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000725 // ...
Sanjoy Das23f314d2017-05-03 18:29:34 +0000726 // I+k_f u< L ... Chk_f
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000727 //
Sanjoy Das23f314d2017-05-03 18:29:34 +0000728 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000729 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
730 // k_f != k_0 ... Precond_2
731 //
732 // Claim:
Sanjoy Das23f314d2017-05-03 18:29:34 +0000733 // Chk_0 AND Chk_f implies all the other checks
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000734 //
735 // Informal proof sketch:
736 //
737 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
738 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
739 // thus I+k_f is the greatest unsigned value in that range.
740 //
741 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
742 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
743 // lie in [I+k_0,I+k_f], this proving our claim.
744 //
745 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
746 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
747 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
748 // range by definition, and the latter case is impossible:
749 //
750 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
751 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
752 //
753 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
754 // with 'x' above) to be at least >u INT_MIN.
755
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000756 RangeChecksOut.emplace_back(CurrentChecks.front());
757 RangeChecksOut.emplace_back(CurrentChecks.back());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000758 }
759
760 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
761 return RangeChecksOut.size() != OldCount;
762}
763
Florian Hahn6b3216a2017-07-31 10:07:49 +0000764#ifndef NDEBUG
Sanjoy Das083f3892016-05-18 22:55:34 +0000765StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
766 switch (WS) {
767 case WS_IllegalOrNegative:
768 return "IllegalOrNegative";
769 case WS_Neutral:
770 return "Neutral";
771 case WS_Positive:
772 return "Positive";
773 case WS_VeryPositive:
774 return "VeryPositive";
775 }
776
777 llvm_unreachable("Fully covered switch above!");
778}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000779#endif
Sanjoy Das083f3892016-05-18 22:55:34 +0000780
Philip Reames6a1f3442018-03-23 23:41:47 +0000781PreservedAnalyses GuardWideningPass::run(Function &F,
782 FunctionAnalysisManager &AM) {
783 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
784 auto &LI = AM.getResult<LoopAnalysis>(F);
785 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000786 BranchProbabilityInfo *BPI = nullptr;
787 if (WidenFrequentBranches)
788 BPI = AM.getCachedResult<BranchProbabilityAnalysis>(F);
789 if (!GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000790 [](BasicBlock*) { return true; } ).run())
Philip Reames6a1f3442018-03-23 23:41:47 +0000791 return PreservedAnalyses::all();
792
793 PreservedAnalyses PA;
794 PA.preserveSet<CFGAnalyses>();
795 return PA;
796}
797
798namespace {
799struct GuardWideningLegacyPass : public FunctionPass {
800 static char ID;
Philip Reames6a1f3442018-03-23 23:41:47 +0000801
802 GuardWideningLegacyPass() : FunctionPass(ID) {
803 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
804 }
805
806 bool runOnFunction(Function &F) override {
807 if (skipFunction(F))
808 return false;
Philip Reames9258e9d2018-04-27 17:29:10 +0000809 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
810 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
811 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Max Kazantseveded4ab2018-08-06 05:49:19 +0000812 BranchProbabilityInfo *BPI = nullptr;
813 if (WidenFrequentBranches)
814 BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
815 return GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000816 [](BasicBlock*) { return true; } ).run();
Philip Reames6a1f3442018-03-23 23:41:47 +0000817 }
818
819 void getAnalysisUsage(AnalysisUsage &AU) const override {
820 AU.setPreservesCFG();
821 AU.addRequired<DominatorTreeWrapperPass>();
822 AU.addRequired<PostDominatorTreeWrapperPass>();
823 AU.addRequired<LoopInfoWrapperPass>();
Max Kazantseveded4ab2018-08-06 05:49:19 +0000824 if (WidenFrequentBranches)
825 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Philip Reames6a1f3442018-03-23 23:41:47 +0000826 }
827};
Philip Reames9258e9d2018-04-27 17:29:10 +0000828
829/// Same as above, but restricted to a single loop at a time. Can be
830/// scheduled with other loop passes w/o breaking out of LPM
831struct LoopGuardWideningLegacyPass : public LoopPass {
832 static char ID;
833
834 LoopGuardWideningLegacyPass() : LoopPass(ID) {
835 initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
836 }
837
838 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
839 if (skipLoop(L))
840 return false;
841 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
842 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Philip Reames502d44812018-04-27 23:15:56 +0000843 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
844 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
Philip Reames9258e9d2018-04-27 17:29:10 +0000845 BasicBlock *RootBB = L->getLoopPredecessor();
846 if (!RootBB)
847 RootBB = L->getHeader();
848 auto BlockFilter = [&](BasicBlock *BB) {
849 return BB == RootBB || L->contains(BB);
850 };
Max Kazantseveded4ab2018-08-06 05:49:19 +0000851 BranchProbabilityInfo *BPI = nullptr;
852 if (WidenFrequentBranches)
853 BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
854 return GuardWideningImpl(DT, PDT, LI, BPI,
Philip Reames9258e9d2018-04-27 17:29:10 +0000855 DT.getNode(RootBB), BlockFilter).run();
856 }
857
858 void getAnalysisUsage(AnalysisUsage &AU) const override {
Max Kazantseveded4ab2018-08-06 05:49:19 +0000859 if (WidenFrequentBranches)
860 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Philip Reames9258e9d2018-04-27 17:29:10 +0000861 AU.setPreservesCFG();
862 getLoopAnalysisUsage(AU);
Philip Reames9258e9d2018-04-27 17:29:10 +0000863 AU.addPreserved<PostDominatorTreeWrapperPass>();
864 }
865};
Philip Reames6a1f3442018-03-23 23:41:47 +0000866}
867
Sanjoy Das083f3892016-05-18 22:55:34 +0000868char GuardWideningLegacyPass::ID = 0;
Philip Reames9258e9d2018-04-27 17:29:10 +0000869char LoopGuardWideningLegacyPass::ID = 0;
Sanjoy Das083f3892016-05-18 22:55:34 +0000870
871INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
872 false, false)
873INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
874INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
875INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000876if (WidenFrequentBranches)
877 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Sanjoy Das083f3892016-05-18 22:55:34 +0000878INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
879 false, false)
880
Philip Reames9258e9d2018-04-27 17:29:10 +0000881INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
882 "Widen guards (within a single loop, as a loop pass)",
883 false, false)
884INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
885INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
886INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000887if (WidenFrequentBranches)
888 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Philip Reames9258e9d2018-04-27 17:29:10 +0000889INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
890 "Widen guards (within a single loop, as a loop pass)",
891 false, false)
892
Sanjoy Das083f3892016-05-18 22:55:34 +0000893FunctionPass *llvm::createGuardWideningPass() {
894 return new GuardWideningLegacyPass();
895}
Philip Reames9258e9d2018-04-27 17:29:10 +0000896
897Pass *llvm::createLoopGuardWideningPass() {
898 return new LoopGuardWideningLegacyPass();
899}