blob: 506b38ba251cafb250f7e23e961e37d9f342ac5f [file] [log] [blame]
Sanjoy Das083f3892016-05-18 22:55:34 +00001//===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the guard widening pass. The semantics of the
11// @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
12// more often that it did before the transform. This optimization is called
13// "widening" and can be used hoist and common runtime checks in situations like
14// these:
15//
16// %cmp0 = 7 u< Length
17// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
18// call @unknown_side_effects()
19// %cmp1 = 9 u< Length
20// call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
21// ...
22//
23// =>
24//
25// %cmp0 = 9 u< Length
26// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
27// call @unknown_side_effects()
28// ...
29//
30// If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
31// generic implementation of the same function, which will have the correct
32// semantics from that point onward. It is always _legal_ to deoptimize (so
33// replacing %cmp0 with false is "correct"), though it may not always be
34// profitable to do so.
35//
36// NB! This pass is a work in progress. It hasn't been tuned to be "production
37// ready" yet. It is known to have quadriatic running time and will not scale
38// to large numbers of guards
39//
40//===----------------------------------------------------------------------===//
41
42#include "llvm/Transforms/Scalar/GuardWidening.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000043#include <functional>
Sanjoy Das083f3892016-05-18 22:55:34 +000044#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/Analysis/LoopInfo.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000047#include "llvm/Analysis/LoopPass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000048#include "llvm/Analysis/PostDominators.h"
49#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000050#include "llvm/IR/ConstantRange.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000051#include "llvm/IR/Dominators.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000054#include "llvm/Pass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000055#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000056#include "llvm/Support/KnownBits.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000057#include "llvm/Transforms/Scalar.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000058#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000059
60using namespace llvm;
61
62#define DEBUG_TYPE "guard-widening"
63
64namespace {
65
66class GuardWideningImpl {
67 DominatorTree &DT;
Philip Reames502d44812018-04-27 23:15:56 +000068 PostDominatorTree *PDT;
Sanjoy Das083f3892016-05-18 22:55:34 +000069 LoopInfo &LI;
70
Philip Reames9258e9d2018-04-27 17:29:10 +000071 /// Together, these describe the region of interest. This might be all of
72 /// the blocks within a function, or only a given loop's blocks and preheader.
73 DomTreeNode *Root;
74 std::function<bool(BasicBlock*)> BlockFilter;
75
Sanjoy Das083f3892016-05-18 22:55:34 +000076 /// The set of guards whose conditions have been widened into dominating
77 /// guards.
Max Kazantsev3327bca2018-07-30 07:07:32 +000078 SmallVector<Instruction *, 16> EliminatedGuards;
Sanjoy Das083f3892016-05-18 22:55:34 +000079
80 /// The set of guards which have been widened to include conditions to other
81 /// guards.
Max Kazantsev3327bca2018-07-30 07:07:32 +000082 DenseSet<Instruction *> WidenedGuards;
Sanjoy Das083f3892016-05-18 22:55:34 +000083
84 /// Try to eliminate guard \p Guard by widening it into an earlier dominating
85 /// guard. \p DFSI is the DFS iterator on the dominator tree that is
86 /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
87 /// maps BasicBlocks to the set of guards seen in that block.
88 bool eliminateGuardViaWidening(
Max Kazantsev3327bca2018-07-30 07:07:32 +000089 Instruction *Guard, const df_iterator<DomTreeNode *> &DFSI,
90 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Sanjoy Das083f3892016-05-18 22:55:34 +000091 GuardsPerBlock);
92
Max Kazantsev3327bca2018-07-30 07:07:32 +000093 // Get the condition from \p GuardInst.
94 Value *getGuardCondition(Instruction *GuardInst);
95
96 // Set the condition for \p GuardInst.
97 void setGuardCondition(Instruction *GuardInst, Value *NewCond);
98
99 // Whether or not the particular instruction is a guard.
100 bool isGuard(const Instruction *I);
101
102 // Eliminates the guard instruction properly.
103 void eliminateGuard(Instruction *GuardInst);
104
Sanjoy Das083f3892016-05-18 22:55:34 +0000105 /// Used to keep track of which widening potential is more effective.
106 enum WideningScore {
107 /// Don't widen.
108 WS_IllegalOrNegative,
109
110 /// Widening is performance neutral as far as the cycles spent in check
111 /// conditions goes (but can still help, e.g., code layout, having less
112 /// deopt state).
113 WS_Neutral,
114
115 /// Widening is profitable.
116 WS_Positive,
117
118 /// Widening is very profitable. Not significantly different from \c
119 /// WS_Positive, except by the order.
120 WS_VeryPositive
121 };
122
123 static StringRef scoreTypeToString(WideningScore WS);
124
125 /// Compute the score for widening the condition in \p DominatedGuard
126 /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
127 /// \p DominatingGuardLoop).
Max Kazantsev3327bca2018-07-30 07:07:32 +0000128 WideningScore computeWideningScore(Instruction *DominatedGuard,
Sanjoy Das083f3892016-05-18 22:55:34 +0000129 Loop *DominatedGuardLoop,
Max Kazantsev3327bca2018-07-30 07:07:32 +0000130 Instruction *DominatingGuard,
Sanjoy Das083f3892016-05-18 22:55:34 +0000131 Loop *DominatingGuardLoop);
132
133 /// Helper to check if \p V can be hoisted to \p InsertPos.
134 bool isAvailableAt(Value *V, Instruction *InsertPos) {
135 SmallPtrSet<Instruction *, 8> Visited;
136 return isAvailableAt(V, InsertPos, Visited);
137 }
138
139 bool isAvailableAt(Value *V, Instruction *InsertPos,
140 SmallPtrSetImpl<Instruction *> &Visited);
141
142 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
143 /// isAvailableAt returned true.
144 void makeAvailableAt(Value *V, Instruction *InsertPos);
145
146 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
147 /// to generate an expression computing the logical AND of \p Cond0 and \p
148 /// Cond1. Return true if the expression computing the AND is only as
149 /// expensive as computing one of the two. If \p InsertPt is true then
150 /// actually generate the resulting expression, make it available at \p
151 /// InsertPt and return it in \p Result (else no change to the IR is made).
152 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
153 Value *&Result);
154
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000155 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
156 /// with the constraint that \c Length is not negative. \c CheckInst is the
157 /// pre-existing instruction in the IR that computes the result of this range
158 /// check.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000159 class RangeCheck {
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000160 Value *Base;
161 ConstantInt *Offset;
162 Value *Length;
163 ICmpInst *CheckInst;
164
Sanjoy Dasbe991532016-05-24 20:54:45 +0000165 public:
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000166 explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
167 ICmpInst *CheckInst)
168 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
169
Sanjoy Dasbe991532016-05-24 20:54:45 +0000170 void setBase(Value *NewBase) { Base = NewBase; }
171 void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
172
173 Value *getBase() const { return Base; }
174 ConstantInt *getOffset() const { return Offset; }
175 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
176 Value *getLength() const { return Length; };
177 ICmpInst *getCheckInst() const { return CheckInst; }
178
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000179 void print(raw_ostream &OS, bool PrintTypes = false) {
180 OS << "Base: ";
181 Base->printAsOperand(OS, PrintTypes);
182 OS << " Offset: ";
183 Offset->printAsOperand(OS, PrintTypes);
184 OS << " Length: ";
185 Length->printAsOperand(OS, PrintTypes);
186 }
187
188 LLVM_DUMP_METHOD void dump() {
189 print(dbgs());
190 dbgs() << "\n";
191 }
192 };
193
194 /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
195 /// append them to \p Checks. Returns true on success, may clobber \c Checks
196 /// on failure.
197 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
198 SmallPtrSet<Value *, 8> Visited;
199 return parseRangeChecks(CheckCond, Checks, Visited);
200 }
201
202 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
203 SmallPtrSetImpl<Value *> &Visited);
204
205 /// Combine the checks in \p Checks into a smaller set of checks and append
206 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
207 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
208 /// and \p CombinedChecks on success and on failure.
209 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
210 SmallVectorImpl<RangeCheck> &CombinedChecks);
211
Sanjoy Das083f3892016-05-18 22:55:34 +0000212 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
213 /// computing only one of the two expressions?
214 bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
215 Value *ResultUnused;
216 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
217 }
218
219 /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
220 /// whatever it is already checking).
Max Kazantsev3327bca2018-07-30 07:07:32 +0000221 void widenGuard(Instruction *ToWiden, Value *NewCondition) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000222 Value *Result;
Max Kazantsev3327bca2018-07-30 07:07:32 +0000223 widenCondCommon(ToWiden->getOperand(0), NewCondition, ToWiden, Result);
224 setGuardCondition(ToWiden, Result);
Sanjoy Das083f3892016-05-18 22:55:34 +0000225 }
226
227public:
Philip Reames9258e9d2018-04-27 17:29:10 +0000228
Philip Reames502d44812018-04-27 23:15:56 +0000229 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
Philip Reames9258e9d2018-04-27 17:29:10 +0000230 LoopInfo &LI, DomTreeNode *Root,
231 std::function<bool(BasicBlock*)> BlockFilter)
232 : DT(DT), PDT(PDT), LI(LI), Root(Root), BlockFilter(BlockFilter) {}
Sanjoy Das083f3892016-05-18 22:55:34 +0000233
234 /// The entry point for this pass.
235 bool run();
236};
Sanjoy Das083f3892016-05-18 22:55:34 +0000237}
238
239bool GuardWideningImpl::run() {
Max Kazantsev3327bca2018-07-30 07:07:32 +0000240 DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
Sanjoy Das083f3892016-05-18 22:55:34 +0000241 bool Changed = false;
242
Philip Reames9258e9d2018-04-27 17:29:10 +0000243 for (auto DFI = df_begin(Root), DFE = df_end(Root);
Sanjoy Das083f3892016-05-18 22:55:34 +0000244 DFI != DFE; ++DFI) {
245 auto *BB = (*DFI)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000246 if (!BlockFilter(BB))
247 continue;
248
Sanjoy Das083f3892016-05-18 22:55:34 +0000249 auto &CurrentList = GuardsInBlock[BB];
250
251 for (auto &I : *BB)
Max Kazantsev3327bca2018-07-30 07:07:32 +0000252 if (isGuard(&I))
253 CurrentList.push_back(cast<Instruction>(&I));
Sanjoy Das083f3892016-05-18 22:55:34 +0000254
255 for (auto *II : CurrentList)
256 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
257 }
258
Philip Reames9258e9d2018-04-27 17:29:10 +0000259 assert(EliminatedGuards.empty() || Changed);
Sanjoy Das083f3892016-05-18 22:55:34 +0000260 for (auto *II : EliminatedGuards)
261 if (!WidenedGuards.count(II))
Max Kazantsev3327bca2018-07-30 07:07:32 +0000262 eliminateGuard(II);
Sanjoy Das083f3892016-05-18 22:55:34 +0000263
264 return Changed;
265}
266
267bool GuardWideningImpl::eliminateGuardViaWidening(
Max Kazantsev3327bca2018-07-30 07:07:32 +0000268 Instruction *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
269 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Sanjoy Das083f3892016-05-18 22:55:34 +0000270 GuardsInBlock) {
Max Kazantsev3327bca2018-07-30 07:07:32 +0000271 Instruction *BestSoFar = nullptr;
Sanjoy Das083f3892016-05-18 22:55:34 +0000272 auto BestScoreSoFar = WS_IllegalOrNegative;
273 auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
274
275 // In the set of dominating guards, find the one we can merge GuardInst with
276 // for the most profit.
277 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
278 auto *CurBB = DFSI.getPath(i)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000279 if (!BlockFilter(CurBB))
280 break;
Sanjoy Das083f3892016-05-18 22:55:34 +0000281 auto *CurLoop = LI.getLoopFor(CurBB);
282 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
283 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
284
285 auto I = GuardsInCurBB.begin();
286 auto E = GuardsInCurBB.end();
287
288#ifndef NDEBUG
289 {
290 unsigned Index = 0;
291 for (auto &I : *CurBB) {
292 if (Index == GuardsInCurBB.size())
293 break;
294 if (GuardsInCurBB[Index] == &I)
295 Index++;
296 }
297 assert(Index == GuardsInCurBB.size() &&
298 "Guards expected to be in order!");
299 }
300#endif
301
302 assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
303
304 if (i == (e - 1)) {
305 // Corner case: make sure we're only looking at guards strictly dominating
306 // GuardInst when visiting GuardInst->getParent().
307 auto NewEnd = std::find(I, E, GuardInst);
308 assert(NewEnd != E && "GuardInst not in its own block?");
309 E = NewEnd;
310 }
311
312 for (auto *Candidate : make_range(I, E)) {
313 auto Score =
314 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
Max Kazantsev3327bca2018-07-30 07:07:32 +0000315 LLVM_DEBUG(dbgs() << "Score between " << *getGuardCondition(GuardInst)
316 << " and " << *getGuardCondition(Candidate) << " is "
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000317 << scoreTypeToString(Score) << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000318 if (Score > BestScoreSoFar) {
319 BestScoreSoFar = Score;
320 BestSoFar = Candidate;
321 }
322 }
323 }
324
325 if (BestScoreSoFar == WS_IllegalOrNegative) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000326 LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000327 return false;
328 }
329
330 assert(BestSoFar != GuardInst && "Should have never visited same guard!");
331 assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
332
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000333 LLVM_DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
334 << " with score " << scoreTypeToString(BestScoreSoFar)
335 << "\n");
Max Kazantsev3327bca2018-07-30 07:07:32 +0000336 widenGuard(BestSoFar, getGuardCondition(GuardInst));
337 setGuardCondition(GuardInst, ConstantInt::getTrue(GuardInst->getContext()));
Sanjoy Das083f3892016-05-18 22:55:34 +0000338 EliminatedGuards.push_back(GuardInst);
339 WidenedGuards.insert(BestSoFar);
340 return true;
341}
342
Max Kazantsev3327bca2018-07-30 07:07:32 +0000343Value *GuardWideningImpl::getGuardCondition(Instruction *GuardInst) {
344 IntrinsicInst *GI = cast<IntrinsicInst>(GuardInst);
345 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
346 "Bad guard intrinsic?");
347 return GI->getArgOperand(0);
348}
349
350void GuardWideningImpl::setGuardCondition(Instruction *GuardInst,
351 Value *NewCond) {
352 IntrinsicInst *GI = cast<IntrinsicInst>(GuardInst);
353 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
354 "Bad guard intrinsic?");
355 GI->setArgOperand(0, NewCond);
356}
357
358bool GuardWideningImpl::isGuard(const Instruction* I) {
359 using namespace llvm::PatternMatch;
360 return match(I, m_Intrinsic<Intrinsic::experimental_guard>());
361}
362
363void GuardWideningImpl::eliminateGuard(Instruction *GuardInst) {
364 GuardInst->eraseFromParent();
365}
366
Sanjoy Das083f3892016-05-18 22:55:34 +0000367GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
Max Kazantsev3327bca2018-07-30 07:07:32 +0000368 Instruction *DominatedGuard, Loop *DominatedGuardLoop,
369 Instruction *DominatingGuard, Loop *DominatingGuardLoop) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000370 bool HoistingOutOfLoop = false;
371
372 if (DominatingGuardLoop != DominatedGuardLoop) {
Philip Reamesde5a1da2018-04-27 17:41:37 +0000373 // Be conservative and don't widen into a sibling loop. TODO: If the
374 // sibling is colder, we should consider allowing this.
Sanjoy Das083f3892016-05-18 22:55:34 +0000375 if (DominatingGuardLoop &&
376 !DominatingGuardLoop->contains(DominatedGuardLoop))
377 return WS_IllegalOrNegative;
378
379 HoistingOutOfLoop = true;
380 }
381
Max Kazantsev3327bca2018-07-30 07:07:32 +0000382 if (!isAvailableAt(getGuardCondition(DominatedGuard), DominatingGuard))
Sanjoy Das083f3892016-05-18 22:55:34 +0000383 return WS_IllegalOrNegative;
384
Philip Reamesde5a1da2018-04-27 17:41:37 +0000385 // If the guard was conditional executed, it may never be reached
386 // dynamically. There are two potential downsides to hoisting it out of the
387 // conditionally executed region: 1) we may spuriously deopt without need and
388 // 2) we have the extra cost of computing the guard condition in the common
389 // case. At the moment, we really only consider the second in our heuristic
390 // here. TODO: evaluate cost model for spurious deopt
Philip Reames502d44812018-04-27 23:15:56 +0000391 // NOTE: As written, this also lets us hoist right over another guard which
392 // is essentially just another spelling for control flow.
Max Kazantsev3327bca2018-07-30 07:07:32 +0000393 if (isWideningCondProfitable(getGuardCondition(DominatedGuard),
394 getGuardCondition(DominatingGuard)))
Sanjoy Das083f3892016-05-18 22:55:34 +0000395 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
396
397 if (HoistingOutOfLoop)
398 return WS_Positive;
399
Philip Reames502d44812018-04-27 23:15:56 +0000400 // Returns true if we might be hoisting above explicit control flow. Note
401 // that this completely ignores implicit control flow (guards, calls which
402 // throw, etc...). That choice appears arbitrary.
403 auto MaybeHoistingOutOfIf = [&]() {
404 auto *DominatingBlock = DominatingGuard->getParent();
405 auto *DominatedBlock = DominatedGuard->getParent();
406
407 // Same Block?
408 if (DominatedBlock == DominatingBlock)
409 return false;
410 // Obvious successor (common loop header/preheader case)
411 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
412 return false;
413 // TODO: diamond, triangle cases
414 if (!PDT) return true;
415 return !PDT->dominates(DominatedGuard->getParent(),
416 DominatingGuard->getParent());
417 };
418
419 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
Sanjoy Das083f3892016-05-18 22:55:34 +0000420}
421
422bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
423 SmallPtrSetImpl<Instruction *> &Visited) {
424 auto *Inst = dyn_cast<Instruction>(V);
425 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
426 return true;
427
428 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
429 Inst->mayReadFromMemory())
430 return false;
431
432 Visited.insert(Inst);
433
434 // We only want to go _up_ the dominance chain when recursing.
435 assert(!isa<PHINode>(Loc) &&
436 "PHIs should return false for isSafeToSpeculativelyExecute");
437 assert(DT.isReachableFromEntry(Inst->getParent()) &&
438 "We did a DFS from the block entry!");
439 return all_of(Inst->operands(),
440 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
441}
442
443void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
444 auto *Inst = dyn_cast<Instruction>(V);
445 if (!Inst || DT.dominates(Inst, Loc))
446 return;
447
448 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
449 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
450
451 for (Value *Op : Inst->operands())
452 makeAvailableAt(Op, Loc);
453
454 Inst->moveBefore(Loc);
455}
456
457bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
458 Instruction *InsertPt, Value *&Result) {
459 using namespace llvm::PatternMatch;
460
461 {
462 // L >u C0 && L >u C1 -> L >u max(C0, C1)
463 ConstantInt *RHS0, *RHS1;
464 Value *LHS;
465 ICmpInst::Predicate Pred0, Pred1;
466 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
467 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
468
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000469 ConstantRange CR0 =
470 ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
471 ConstantRange CR1 =
472 ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
Sanjoy Das083f3892016-05-18 22:55:34 +0000473
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000474 // SubsetIntersect is a subset of the actual mathematical intersection of
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000475 // CR0 and CR1, while SupersetIntersect is a superset of the actual
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000476 // mathematical intersection. If these two ConstantRanges are equal, then
477 // we know we were able to represent the actual mathematical intersection
478 // of CR0 and CR1, and can use the same to generate an icmp instruction.
479 //
480 // Given what we're doing here and the semantics of guards, it would
481 // actually be correct to just use SubsetIntersect, but that may be too
482 // aggressive in cases we care about.
483 auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
484 auto SupersetIntersect = CR0.intersectWith(CR1);
485
486 APInt NewRHSAP;
487 CmpInst::Predicate Pred;
488 if (SubsetIntersect == SupersetIntersect &&
489 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000490 if (InsertPt) {
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000491 ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
492 Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
Sanjoy Das083f3892016-05-18 22:55:34 +0000493 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000494 return true;
495 }
496 }
497 }
498
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000499 {
500 SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
501 if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
502 combineRangeChecks(Checks, CombinedChecks)) {
503 if (InsertPt) {
504 Result = nullptr;
505 for (auto &RC : CombinedChecks) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000506 makeAvailableAt(RC.getCheckInst(), InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000507 if (Result)
Sanjoy Dasbe991532016-05-24 20:54:45 +0000508 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
509 InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000510 else
Sanjoy Dasbe991532016-05-24 20:54:45 +0000511 Result = RC.getCheckInst();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000512 }
513
514 Result->setName("wide.chk");
515 }
516 return true;
517 }
518 }
519
Sanjoy Das083f3892016-05-18 22:55:34 +0000520 // Base case -- just logical-and the two conditions together.
521
522 if (InsertPt) {
523 makeAvailableAt(Cond0, InsertPt);
524 makeAvailableAt(Cond1, InsertPt);
525
526 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
527 }
528
529 // We were not able to compute Cond0 AND Cond1 for the price of one.
530 return false;
531}
532
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000533bool GuardWideningImpl::parseRangeChecks(
534 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
535 SmallPtrSetImpl<Value *> &Visited) {
536 if (!Visited.insert(CheckCond).second)
537 return true;
538
539 using namespace llvm::PatternMatch;
540
541 {
542 Value *AndLHS, *AndRHS;
543 if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
544 return parseRangeChecks(AndLHS, Checks) &&
545 parseRangeChecks(AndRHS, Checks);
546 }
547
548 auto *IC = dyn_cast<ICmpInst>(CheckCond);
549 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
550 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
551 IC->getPredicate() != ICmpInst::ICMP_UGT))
552 return false;
553
554 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
555 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
556 std::swap(CmpLHS, CmpRHS);
557
558 auto &DL = IC->getModule()->getDataLayout();
559
Sanjoy Dasbe991532016-05-24 20:54:45 +0000560 GuardWideningImpl::RangeCheck Check(
561 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
562 CmpRHS, IC);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000563
Sanjoy Dasbe991532016-05-24 20:54:45 +0000564 if (!isKnownNonNegative(Check.getLength(), DL))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000565 return false;
566
567 // What we have in \c Check now is a correct interpretation of \p CheckCond.
568 // Try to see if we can move some constant offsets into the \c Offset field.
569
570 bool Changed;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000571 auto &Ctx = CheckCond->getContext();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000572
573 do {
574 Value *OpLHS;
575 ConstantInt *OpRHS;
576 Changed = false;
577
578#ifndef NDEBUG
Sanjoy Dasbe991532016-05-24 20:54:45 +0000579 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000580 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
581 "Unreachable instruction?");
582#endif
583
Sanjoy Dasbe991532016-05-24 20:54:45 +0000584 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
585 Check.setBase(OpLHS);
586 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
587 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000588 Changed = true;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000589 } else if (match(Check.getBase(),
590 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000591 KnownBits Known = computeKnownBits(OpLHS, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000592 if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000593 Check.setBase(OpLHS);
594 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
595 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000596 Changed = true;
597 }
598 }
599 } while (Changed);
600
601 Checks.push_back(Check);
602 return true;
603}
604
605bool GuardWideningImpl::combineRangeChecks(
606 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
607 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
608 unsigned OldCount = Checks.size();
609 while (!Checks.empty()) {
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000610 // Pick all of the range checks with a specific base and length, and try to
611 // merge them.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000612 Value *CurrentBase = Checks.front().getBase();
613 Value *CurrentLength = Checks.front().getLength();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000614
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000615 SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000616
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000617 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000618 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000619 };
620
Sanjoy Das90208722017-02-21 00:38:44 +0000621 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000622 Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
623
624 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
625
626 if (CurrentChecks.size() < 3) {
627 RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
628 CurrentChecks.end());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000629 continue;
630 }
631
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000632 // CurrentChecks.size() will typically be 3 here, but so far there has been
633 // no need to hard-code that fact.
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000634
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000635 llvm::sort(CurrentChecks.begin(), CurrentChecks.end(),
636 [&](const GuardWideningImpl::RangeCheck &LHS,
637 const GuardWideningImpl::RangeCheck &RHS) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000638 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000639 });
640
641 // Note: std::sort should not invalidate the ChecksStart iterator.
642
Sanjoy Dasbe991532016-05-24 20:54:45 +0000643 ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
644 *MaxOffset = CurrentChecks.back().getOffset();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000645
646 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
647 if ((MaxOffset->getValue() - MinOffset->getValue())
648 .ugt(APInt::getSignedMinValue(BitWidth)))
649 return false;
650
651 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000652 const APInt &HighOffset = MaxOffset->getValue();
Sanjoy Das23519752016-05-19 23:15:59 +0000653 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000654 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000655 };
656
657 if (MaxDiff.isMinValue() ||
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000658 !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
659 OffsetOK))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000660 return false;
661
662 // We have a series of f+1 checks as:
663 //
664 // I+k_0 u< L ... Chk_0
Sanjoy Das23f314d2017-05-03 18:29:34 +0000665 // I+k_1 u< L ... Chk_1
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000666 // ...
Sanjoy Das23f314d2017-05-03 18:29:34 +0000667 // I+k_f u< L ... Chk_f
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000668 //
Sanjoy Das23f314d2017-05-03 18:29:34 +0000669 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000670 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
671 // k_f != k_0 ... Precond_2
672 //
673 // Claim:
Sanjoy Das23f314d2017-05-03 18:29:34 +0000674 // Chk_0 AND Chk_f implies all the other checks
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000675 //
676 // Informal proof sketch:
677 //
678 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
679 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
680 // thus I+k_f is the greatest unsigned value in that range.
681 //
682 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
683 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
684 // lie in [I+k_0,I+k_f], this proving our claim.
685 //
686 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
687 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
688 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
689 // range by definition, and the latter case is impossible:
690 //
691 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
692 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
693 //
694 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
695 // with 'x' above) to be at least >u INT_MIN.
696
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000697 RangeChecksOut.emplace_back(CurrentChecks.front());
698 RangeChecksOut.emplace_back(CurrentChecks.back());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000699 }
700
701 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
702 return RangeChecksOut.size() != OldCount;
703}
704
Florian Hahn6b3216a2017-07-31 10:07:49 +0000705#ifndef NDEBUG
Sanjoy Das083f3892016-05-18 22:55:34 +0000706StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
707 switch (WS) {
708 case WS_IllegalOrNegative:
709 return "IllegalOrNegative";
710 case WS_Neutral:
711 return "Neutral";
712 case WS_Positive:
713 return "Positive";
714 case WS_VeryPositive:
715 return "VeryPositive";
716 }
717
718 llvm_unreachable("Fully covered switch above!");
719}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000720#endif
Sanjoy Das083f3892016-05-18 22:55:34 +0000721
Philip Reames6a1f3442018-03-23 23:41:47 +0000722PreservedAnalyses GuardWideningPass::run(Function &F,
723 FunctionAnalysisManager &AM) {
724 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
725 auto &LI = AM.getResult<LoopAnalysis>(F);
726 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
Philip Reames502d44812018-04-27 23:15:56 +0000727 if (!GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000728 [](BasicBlock*) { return true; } ).run())
Philip Reames6a1f3442018-03-23 23:41:47 +0000729 return PreservedAnalyses::all();
730
731 PreservedAnalyses PA;
732 PA.preserveSet<CFGAnalyses>();
733 return PA;
734}
735
736namespace {
737struct GuardWideningLegacyPass : public FunctionPass {
738 static char ID;
Philip Reames6a1f3442018-03-23 23:41:47 +0000739
740 GuardWideningLegacyPass() : FunctionPass(ID) {
741 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
742 }
743
744 bool runOnFunction(Function &F) override {
745 if (skipFunction(F))
746 return false;
Philip Reames9258e9d2018-04-27 17:29:10 +0000747 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
748 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
749 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Philip Reames502d44812018-04-27 23:15:56 +0000750 return GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000751 [](BasicBlock*) { return true; } ).run();
Philip Reames6a1f3442018-03-23 23:41:47 +0000752 }
753
754 void getAnalysisUsage(AnalysisUsage &AU) const override {
755 AU.setPreservesCFG();
756 AU.addRequired<DominatorTreeWrapperPass>();
757 AU.addRequired<PostDominatorTreeWrapperPass>();
758 AU.addRequired<LoopInfoWrapperPass>();
759 }
760};
Philip Reames9258e9d2018-04-27 17:29:10 +0000761
762/// Same as above, but restricted to a single loop at a time. Can be
763/// scheduled with other loop passes w/o breaking out of LPM
764struct LoopGuardWideningLegacyPass : public LoopPass {
765 static char ID;
766
767 LoopGuardWideningLegacyPass() : LoopPass(ID) {
768 initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
769 }
770
771 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
772 if (skipLoop(L))
773 return false;
774 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
775 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Philip Reames502d44812018-04-27 23:15:56 +0000776 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
777 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
Philip Reames9258e9d2018-04-27 17:29:10 +0000778 BasicBlock *RootBB = L->getLoopPredecessor();
779 if (!RootBB)
780 RootBB = L->getHeader();
781 auto BlockFilter = [&](BasicBlock *BB) {
782 return BB == RootBB || L->contains(BB);
783 };
784 return GuardWideningImpl(DT, PDT, LI,
785 DT.getNode(RootBB), BlockFilter).run();
786 }
787
788 void getAnalysisUsage(AnalysisUsage &AU) const override {
789 AU.setPreservesCFG();
790 getLoopAnalysisUsage(AU);
Philip Reames9258e9d2018-04-27 17:29:10 +0000791 AU.addPreserved<PostDominatorTreeWrapperPass>();
792 }
793};
Philip Reames6a1f3442018-03-23 23:41:47 +0000794}
795
Sanjoy Das083f3892016-05-18 22:55:34 +0000796char GuardWideningLegacyPass::ID = 0;
Philip Reames9258e9d2018-04-27 17:29:10 +0000797char LoopGuardWideningLegacyPass::ID = 0;
Sanjoy Das083f3892016-05-18 22:55:34 +0000798
799INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
800 false, false)
801INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
802INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
803INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
804INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
805 false, false)
806
Philip Reames9258e9d2018-04-27 17:29:10 +0000807INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
808 "Widen guards (within a single loop, as a loop pass)",
809 false, false)
810INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
811INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
812INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
813INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
814 "Widen guards (within a single loop, as a loop pass)",
815 false, false)
816
Sanjoy Das083f3892016-05-18 22:55:34 +0000817FunctionPass *llvm::createGuardWideningPass() {
818 return new GuardWideningLegacyPass();
819}
Philip Reames9258e9d2018-04-27 17:29:10 +0000820
821Pass *llvm::createLoopGuardWideningPass() {
822 return new LoopGuardWideningLegacyPass();
823}