blob: 55d2f6ee81c3eb81cd99635097c42e3d55313397 [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.
78 SmallVector<IntrinsicInst *, 16> EliminatedGuards;
79
80 /// The set of guards which have been widened to include conditions to other
81 /// guards.
82 DenseSet<IntrinsicInst *> WidenedGuards;
83
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(
89 IntrinsicInst *Guard, const df_iterator<DomTreeNode *> &DFSI,
90 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
91 GuardsPerBlock);
92
93 /// Used to keep track of which widening potential is more effective.
94 enum WideningScore {
95 /// Don't widen.
96 WS_IllegalOrNegative,
97
98 /// Widening is performance neutral as far as the cycles spent in check
99 /// conditions goes (but can still help, e.g., code layout, having less
100 /// deopt state).
101 WS_Neutral,
102
103 /// Widening is profitable.
104 WS_Positive,
105
106 /// Widening is very profitable. Not significantly different from \c
107 /// WS_Positive, except by the order.
108 WS_VeryPositive
109 };
110
111 static StringRef scoreTypeToString(WideningScore WS);
112
113 /// Compute the score for widening the condition in \p DominatedGuard
114 /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
115 /// \p DominatingGuardLoop).
116 WideningScore computeWideningScore(IntrinsicInst *DominatedGuard,
117 Loop *DominatedGuardLoop,
118 IntrinsicInst *DominatingGuard,
119 Loop *DominatingGuardLoop);
120
121 /// Helper to check if \p V can be hoisted to \p InsertPos.
122 bool isAvailableAt(Value *V, Instruction *InsertPos) {
123 SmallPtrSet<Instruction *, 8> Visited;
124 return isAvailableAt(V, InsertPos, Visited);
125 }
126
127 bool isAvailableAt(Value *V, Instruction *InsertPos,
128 SmallPtrSetImpl<Instruction *> &Visited);
129
130 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
131 /// isAvailableAt returned true.
132 void makeAvailableAt(Value *V, Instruction *InsertPos);
133
134 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
135 /// to generate an expression computing the logical AND of \p Cond0 and \p
136 /// Cond1. Return true if the expression computing the AND is only as
137 /// expensive as computing one of the two. If \p InsertPt is true then
138 /// actually generate the resulting expression, make it available at \p
139 /// InsertPt and return it in \p Result (else no change to the IR is made).
140 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
141 Value *&Result);
142
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000143 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
144 /// with the constraint that \c Length is not negative. \c CheckInst is the
145 /// pre-existing instruction in the IR that computes the result of this range
146 /// check.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000147 class RangeCheck {
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000148 Value *Base;
149 ConstantInt *Offset;
150 Value *Length;
151 ICmpInst *CheckInst;
152
Sanjoy Dasbe991532016-05-24 20:54:45 +0000153 public:
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000154 explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
155 ICmpInst *CheckInst)
156 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
157
Sanjoy Dasbe991532016-05-24 20:54:45 +0000158 void setBase(Value *NewBase) { Base = NewBase; }
159 void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
160
161 Value *getBase() const { return Base; }
162 ConstantInt *getOffset() const { return Offset; }
163 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
164 Value *getLength() const { return Length; };
165 ICmpInst *getCheckInst() const { return CheckInst; }
166
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000167 void print(raw_ostream &OS, bool PrintTypes = false) {
168 OS << "Base: ";
169 Base->printAsOperand(OS, PrintTypes);
170 OS << " Offset: ";
171 Offset->printAsOperand(OS, PrintTypes);
172 OS << " Length: ";
173 Length->printAsOperand(OS, PrintTypes);
174 }
175
176 LLVM_DUMP_METHOD void dump() {
177 print(dbgs());
178 dbgs() << "\n";
179 }
180 };
181
182 /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
183 /// append them to \p Checks. Returns true on success, may clobber \c Checks
184 /// on failure.
185 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
186 SmallPtrSet<Value *, 8> Visited;
187 return parseRangeChecks(CheckCond, Checks, Visited);
188 }
189
190 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
191 SmallPtrSetImpl<Value *> &Visited);
192
193 /// Combine the checks in \p Checks into a smaller set of checks and append
194 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
195 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
196 /// and \p CombinedChecks on success and on failure.
197 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
198 SmallVectorImpl<RangeCheck> &CombinedChecks);
199
Sanjoy Das083f3892016-05-18 22:55:34 +0000200 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
201 /// computing only one of the two expressions?
202 bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
203 Value *ResultUnused;
204 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
205 }
206
207 /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
208 /// whatever it is already checking).
209 void widenGuard(IntrinsicInst *ToWiden, Value *NewCondition) {
210 Value *Result;
211 widenCondCommon(ToWiden->getArgOperand(0), NewCondition, ToWiden, Result);
212 ToWiden->setArgOperand(0, Result);
213 }
214
215public:
Philip Reames9258e9d2018-04-27 17:29:10 +0000216
Philip Reames502d44812018-04-27 23:15:56 +0000217 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
Philip Reames9258e9d2018-04-27 17:29:10 +0000218 LoopInfo &LI, DomTreeNode *Root,
219 std::function<bool(BasicBlock*)> BlockFilter)
220 : DT(DT), PDT(PDT), LI(LI), Root(Root), BlockFilter(BlockFilter) {}
Sanjoy Das083f3892016-05-18 22:55:34 +0000221
222 /// The entry point for this pass.
223 bool run();
224};
Sanjoy Das083f3892016-05-18 22:55:34 +0000225}
226
227bool GuardWideningImpl::run() {
228 using namespace llvm::PatternMatch;
229
230 DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> GuardsInBlock;
231 bool Changed = false;
232
Philip Reames9258e9d2018-04-27 17:29:10 +0000233 for (auto DFI = df_begin(Root), DFE = df_end(Root);
Sanjoy Das083f3892016-05-18 22:55:34 +0000234 DFI != DFE; ++DFI) {
235 auto *BB = (*DFI)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000236 if (!BlockFilter(BB))
237 continue;
238
Sanjoy Das083f3892016-05-18 22:55:34 +0000239 auto &CurrentList = GuardsInBlock[BB];
240
241 for (auto &I : *BB)
242 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
243 CurrentList.push_back(cast<IntrinsicInst>(&I));
244
245 for (auto *II : CurrentList)
246 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
247 }
248
Philip Reames9258e9d2018-04-27 17:29:10 +0000249 assert(EliminatedGuards.empty() || Changed);
Sanjoy Das083f3892016-05-18 22:55:34 +0000250 for (auto *II : EliminatedGuards)
251 if (!WidenedGuards.count(II))
252 II->eraseFromParent();
253
254 return Changed;
255}
256
257bool GuardWideningImpl::eliminateGuardViaWidening(
258 IntrinsicInst *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
259 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
260 GuardsInBlock) {
261 IntrinsicInst *BestSoFar = nullptr;
262 auto BestScoreSoFar = WS_IllegalOrNegative;
263 auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
264
265 // In the set of dominating guards, find the one we can merge GuardInst with
266 // for the most profit.
267 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
268 auto *CurBB = DFSI.getPath(i)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000269 if (!BlockFilter(CurBB))
270 break;
Sanjoy Das083f3892016-05-18 22:55:34 +0000271 auto *CurLoop = LI.getLoopFor(CurBB);
272 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
273 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
274
275 auto I = GuardsInCurBB.begin();
276 auto E = GuardsInCurBB.end();
277
278#ifndef NDEBUG
279 {
280 unsigned Index = 0;
281 for (auto &I : *CurBB) {
282 if (Index == GuardsInCurBB.size())
283 break;
284 if (GuardsInCurBB[Index] == &I)
285 Index++;
286 }
287 assert(Index == GuardsInCurBB.size() &&
288 "Guards expected to be in order!");
289 }
290#endif
291
292 assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
293
294 if (i == (e - 1)) {
295 // Corner case: make sure we're only looking at guards strictly dominating
296 // GuardInst when visiting GuardInst->getParent().
297 auto NewEnd = std::find(I, E, GuardInst);
298 assert(NewEnd != E && "GuardInst not in its own block?");
299 E = NewEnd;
300 }
301
302 for (auto *Candidate : make_range(I, E)) {
303 auto Score =
304 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
305 DEBUG(dbgs() << "Score between " << *GuardInst->getArgOperand(0)
306 << " and " << *Candidate->getArgOperand(0) << " is "
307 << scoreTypeToString(Score) << "\n");
308 if (Score > BestScoreSoFar) {
309 BestScoreSoFar = Score;
310 BestSoFar = Candidate;
311 }
312 }
313 }
314
315 if (BestScoreSoFar == WS_IllegalOrNegative) {
316 DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
317 return false;
318 }
319
320 assert(BestSoFar != GuardInst && "Should have never visited same guard!");
321 assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
322
323 DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
324 << " with score " << scoreTypeToString(BestScoreSoFar) << "\n");
325 widenGuard(BestSoFar, GuardInst->getArgOperand(0));
326 GuardInst->setArgOperand(0, ConstantInt::getTrue(GuardInst->getContext()));
327 EliminatedGuards.push_back(GuardInst);
328 WidenedGuards.insert(BestSoFar);
329 return true;
330}
331
332GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
333 IntrinsicInst *DominatedGuard, Loop *DominatedGuardLoop,
334 IntrinsicInst *DominatingGuard, Loop *DominatingGuardLoop) {
335 bool HoistingOutOfLoop = false;
336
337 if (DominatingGuardLoop != DominatedGuardLoop) {
Philip Reamesde5a1da2018-04-27 17:41:37 +0000338 // Be conservative and don't widen into a sibling loop. TODO: If the
339 // sibling is colder, we should consider allowing this.
Sanjoy Das083f3892016-05-18 22:55:34 +0000340 if (DominatingGuardLoop &&
341 !DominatingGuardLoop->contains(DominatedGuardLoop))
342 return WS_IllegalOrNegative;
343
344 HoistingOutOfLoop = true;
345 }
346
347 if (!isAvailableAt(DominatedGuard->getArgOperand(0), DominatingGuard))
348 return WS_IllegalOrNegative;
349
Philip Reamesde5a1da2018-04-27 17:41:37 +0000350 // If the guard was conditional executed, it may never be reached
351 // dynamically. There are two potential downsides to hoisting it out of the
352 // conditionally executed region: 1) we may spuriously deopt without need and
353 // 2) we have the extra cost of computing the guard condition in the common
354 // case. At the moment, we really only consider the second in our heuristic
355 // here. TODO: evaluate cost model for spurious deopt
Philip Reames502d44812018-04-27 23:15:56 +0000356 // NOTE: As written, this also lets us hoist right over another guard which
357 // is essentially just another spelling for control flow.
Sanjoy Das083f3892016-05-18 22:55:34 +0000358 if (isWideningCondProfitable(DominatedGuard->getArgOperand(0),
359 DominatingGuard->getArgOperand(0)))
360 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
361
362 if (HoistingOutOfLoop)
363 return WS_Positive;
364
Philip Reames502d44812018-04-27 23:15:56 +0000365 // Returns true if we might be hoisting above explicit control flow. Note
366 // that this completely ignores implicit control flow (guards, calls which
367 // throw, etc...). That choice appears arbitrary.
368 auto MaybeHoistingOutOfIf = [&]() {
369 auto *DominatingBlock = DominatingGuard->getParent();
370 auto *DominatedBlock = DominatedGuard->getParent();
371
372 // Same Block?
373 if (DominatedBlock == DominatingBlock)
374 return false;
375 // Obvious successor (common loop header/preheader case)
376 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
377 return false;
378 // TODO: diamond, triangle cases
379 if (!PDT) return true;
380 return !PDT->dominates(DominatedGuard->getParent(),
381 DominatingGuard->getParent());
382 };
383
384 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
Sanjoy Das083f3892016-05-18 22:55:34 +0000385}
386
387bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
388 SmallPtrSetImpl<Instruction *> &Visited) {
389 auto *Inst = dyn_cast<Instruction>(V);
390 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
391 return true;
392
393 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
394 Inst->mayReadFromMemory())
395 return false;
396
397 Visited.insert(Inst);
398
399 // We only want to go _up_ the dominance chain when recursing.
400 assert(!isa<PHINode>(Loc) &&
401 "PHIs should return false for isSafeToSpeculativelyExecute");
402 assert(DT.isReachableFromEntry(Inst->getParent()) &&
403 "We did a DFS from the block entry!");
404 return all_of(Inst->operands(),
405 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
406}
407
408void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
409 auto *Inst = dyn_cast<Instruction>(V);
410 if (!Inst || DT.dominates(Inst, Loc))
411 return;
412
413 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
414 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
415
416 for (Value *Op : Inst->operands())
417 makeAvailableAt(Op, Loc);
418
419 Inst->moveBefore(Loc);
420}
421
422bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
423 Instruction *InsertPt, Value *&Result) {
424 using namespace llvm::PatternMatch;
425
426 {
427 // L >u C0 && L >u C1 -> L >u max(C0, C1)
428 ConstantInt *RHS0, *RHS1;
429 Value *LHS;
430 ICmpInst::Predicate Pred0, Pred1;
431 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
432 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
433
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000434 ConstantRange CR0 =
435 ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
436 ConstantRange CR1 =
437 ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
Sanjoy Das083f3892016-05-18 22:55:34 +0000438
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000439 // SubsetIntersect is a subset of the actual mathematical intersection of
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000440 // CR0 and CR1, while SupersetIntersect is a superset of the actual
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000441 // mathematical intersection. If these two ConstantRanges are equal, then
442 // we know we were able to represent the actual mathematical intersection
443 // of CR0 and CR1, and can use the same to generate an icmp instruction.
444 //
445 // Given what we're doing here and the semantics of guards, it would
446 // actually be correct to just use SubsetIntersect, but that may be too
447 // aggressive in cases we care about.
448 auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
449 auto SupersetIntersect = CR0.intersectWith(CR1);
450
451 APInt NewRHSAP;
452 CmpInst::Predicate Pred;
453 if (SubsetIntersect == SupersetIntersect &&
454 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000455 if (InsertPt) {
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000456 ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
457 Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
Sanjoy Das083f3892016-05-18 22:55:34 +0000458 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000459 return true;
460 }
461 }
462 }
463
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000464 {
465 SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
466 if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
467 combineRangeChecks(Checks, CombinedChecks)) {
468 if (InsertPt) {
469 Result = nullptr;
470 for (auto &RC : CombinedChecks) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000471 makeAvailableAt(RC.getCheckInst(), InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000472 if (Result)
Sanjoy Dasbe991532016-05-24 20:54:45 +0000473 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
474 InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000475 else
Sanjoy Dasbe991532016-05-24 20:54:45 +0000476 Result = RC.getCheckInst();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000477 }
478
479 Result->setName("wide.chk");
480 }
481 return true;
482 }
483 }
484
Sanjoy Das083f3892016-05-18 22:55:34 +0000485 // Base case -- just logical-and the two conditions together.
486
487 if (InsertPt) {
488 makeAvailableAt(Cond0, InsertPt);
489 makeAvailableAt(Cond1, InsertPt);
490
491 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
492 }
493
494 // We were not able to compute Cond0 AND Cond1 for the price of one.
495 return false;
496}
497
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000498bool GuardWideningImpl::parseRangeChecks(
499 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
500 SmallPtrSetImpl<Value *> &Visited) {
501 if (!Visited.insert(CheckCond).second)
502 return true;
503
504 using namespace llvm::PatternMatch;
505
506 {
507 Value *AndLHS, *AndRHS;
508 if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
509 return parseRangeChecks(AndLHS, Checks) &&
510 parseRangeChecks(AndRHS, Checks);
511 }
512
513 auto *IC = dyn_cast<ICmpInst>(CheckCond);
514 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
515 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
516 IC->getPredicate() != ICmpInst::ICMP_UGT))
517 return false;
518
519 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
520 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
521 std::swap(CmpLHS, CmpRHS);
522
523 auto &DL = IC->getModule()->getDataLayout();
524
Sanjoy Dasbe991532016-05-24 20:54:45 +0000525 GuardWideningImpl::RangeCheck Check(
526 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
527 CmpRHS, IC);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000528
Sanjoy Dasbe991532016-05-24 20:54:45 +0000529 if (!isKnownNonNegative(Check.getLength(), DL))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000530 return false;
531
532 // What we have in \c Check now is a correct interpretation of \p CheckCond.
533 // Try to see if we can move some constant offsets into the \c Offset field.
534
535 bool Changed;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000536 auto &Ctx = CheckCond->getContext();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000537
538 do {
539 Value *OpLHS;
540 ConstantInt *OpRHS;
541 Changed = false;
542
543#ifndef NDEBUG
Sanjoy Dasbe991532016-05-24 20:54:45 +0000544 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000545 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
546 "Unreachable instruction?");
547#endif
548
Sanjoy Dasbe991532016-05-24 20:54:45 +0000549 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
550 Check.setBase(OpLHS);
551 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
552 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000553 Changed = true;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000554 } else if (match(Check.getBase(),
555 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000556 KnownBits Known = computeKnownBits(OpLHS, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000557 if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000558 Check.setBase(OpLHS);
559 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
560 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000561 Changed = true;
562 }
563 }
564 } while (Changed);
565
566 Checks.push_back(Check);
567 return true;
568}
569
570bool GuardWideningImpl::combineRangeChecks(
571 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
572 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
573 unsigned OldCount = Checks.size();
574 while (!Checks.empty()) {
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000575 // Pick all of the range checks with a specific base and length, and try to
576 // merge them.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000577 Value *CurrentBase = Checks.front().getBase();
578 Value *CurrentLength = Checks.front().getLength();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000579
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000580 SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000581
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000582 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000583 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000584 };
585
Sanjoy Das90208722017-02-21 00:38:44 +0000586 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000587 Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
588
589 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
590
591 if (CurrentChecks.size() < 3) {
592 RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
593 CurrentChecks.end());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000594 continue;
595 }
596
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000597 // CurrentChecks.size() will typically be 3 here, but so far there has been
598 // no need to hard-code that fact.
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000599
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000600 llvm::sort(CurrentChecks.begin(), CurrentChecks.end(),
601 [&](const GuardWideningImpl::RangeCheck &LHS,
602 const GuardWideningImpl::RangeCheck &RHS) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000603 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000604 });
605
606 // Note: std::sort should not invalidate the ChecksStart iterator.
607
Sanjoy Dasbe991532016-05-24 20:54:45 +0000608 ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
609 *MaxOffset = CurrentChecks.back().getOffset();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000610
611 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
612 if ((MaxOffset->getValue() - MinOffset->getValue())
613 .ugt(APInt::getSignedMinValue(BitWidth)))
614 return false;
615
616 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000617 const APInt &HighOffset = MaxOffset->getValue();
Sanjoy Das23519752016-05-19 23:15:59 +0000618 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000619 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000620 };
621
622 if (MaxDiff.isMinValue() ||
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000623 !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
624 OffsetOK))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000625 return false;
626
627 // We have a series of f+1 checks as:
628 //
629 // I+k_0 u< L ... Chk_0
Sanjoy Das23f314d2017-05-03 18:29:34 +0000630 // I+k_1 u< L ... Chk_1
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000631 // ...
Sanjoy Das23f314d2017-05-03 18:29:34 +0000632 // I+k_f u< L ... Chk_f
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000633 //
Sanjoy Das23f314d2017-05-03 18:29:34 +0000634 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000635 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
636 // k_f != k_0 ... Precond_2
637 //
638 // Claim:
Sanjoy Das23f314d2017-05-03 18:29:34 +0000639 // Chk_0 AND Chk_f implies all the other checks
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000640 //
641 // Informal proof sketch:
642 //
643 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
644 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
645 // thus I+k_f is the greatest unsigned value in that range.
646 //
647 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
648 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
649 // lie in [I+k_0,I+k_f], this proving our claim.
650 //
651 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
652 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
653 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
654 // range by definition, and the latter case is impossible:
655 //
656 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
657 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
658 //
659 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
660 // with 'x' above) to be at least >u INT_MIN.
661
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000662 RangeChecksOut.emplace_back(CurrentChecks.front());
663 RangeChecksOut.emplace_back(CurrentChecks.back());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000664 }
665
666 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
667 return RangeChecksOut.size() != OldCount;
668}
669
Florian Hahn6b3216a2017-07-31 10:07:49 +0000670#ifndef NDEBUG
Sanjoy Das083f3892016-05-18 22:55:34 +0000671StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
672 switch (WS) {
673 case WS_IllegalOrNegative:
674 return "IllegalOrNegative";
675 case WS_Neutral:
676 return "Neutral";
677 case WS_Positive:
678 return "Positive";
679 case WS_VeryPositive:
680 return "VeryPositive";
681 }
682
683 llvm_unreachable("Fully covered switch above!");
684}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000685#endif
Sanjoy Das083f3892016-05-18 22:55:34 +0000686
Philip Reames6a1f3442018-03-23 23:41:47 +0000687PreservedAnalyses GuardWideningPass::run(Function &F,
688 FunctionAnalysisManager &AM) {
689 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
690 auto &LI = AM.getResult<LoopAnalysis>(F);
691 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
Philip Reames502d44812018-04-27 23:15:56 +0000692 if (!GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000693 [](BasicBlock*) { return true; } ).run())
Philip Reames6a1f3442018-03-23 23:41:47 +0000694 return PreservedAnalyses::all();
695
696 PreservedAnalyses PA;
697 PA.preserveSet<CFGAnalyses>();
698 return PA;
699}
700
701namespace {
702struct GuardWideningLegacyPass : public FunctionPass {
703 static char ID;
Philip Reames6a1f3442018-03-23 23:41:47 +0000704
705 GuardWideningLegacyPass() : FunctionPass(ID) {
706 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
707 }
708
709 bool runOnFunction(Function &F) override {
710 if (skipFunction(F))
711 return false;
Philip Reames9258e9d2018-04-27 17:29:10 +0000712 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
713 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
714 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Philip Reames502d44812018-04-27 23:15:56 +0000715 return GuardWideningImpl(DT, &PDT, LI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000716 [](BasicBlock*) { return true; } ).run();
Philip Reames6a1f3442018-03-23 23:41:47 +0000717 }
718
719 void getAnalysisUsage(AnalysisUsage &AU) const override {
720 AU.setPreservesCFG();
721 AU.addRequired<DominatorTreeWrapperPass>();
722 AU.addRequired<PostDominatorTreeWrapperPass>();
723 AU.addRequired<LoopInfoWrapperPass>();
724 }
725};
Philip Reames9258e9d2018-04-27 17:29:10 +0000726
727/// Same as above, but restricted to a single loop at a time. Can be
728/// scheduled with other loop passes w/o breaking out of LPM
729struct LoopGuardWideningLegacyPass : public LoopPass {
730 static char ID;
731
732 LoopGuardWideningLegacyPass() : LoopPass(ID) {
733 initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
734 }
735
736 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
737 if (skipLoop(L))
738 return false;
739 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
740 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Philip Reames502d44812018-04-27 23:15:56 +0000741 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
742 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
Philip Reames9258e9d2018-04-27 17:29:10 +0000743 BasicBlock *RootBB = L->getLoopPredecessor();
744 if (!RootBB)
745 RootBB = L->getHeader();
746 auto BlockFilter = [&](BasicBlock *BB) {
747 return BB == RootBB || L->contains(BB);
748 };
749 return GuardWideningImpl(DT, PDT, LI,
750 DT.getNode(RootBB), BlockFilter).run();
751 }
752
753 void getAnalysisUsage(AnalysisUsage &AU) const override {
754 AU.setPreservesCFG();
755 getLoopAnalysisUsage(AU);
Philip Reames9258e9d2018-04-27 17:29:10 +0000756 AU.addPreserved<PostDominatorTreeWrapperPass>();
757 }
758};
Philip Reames6a1f3442018-03-23 23:41:47 +0000759}
760
Sanjoy Das083f3892016-05-18 22:55:34 +0000761char GuardWideningLegacyPass::ID = 0;
Philip Reames9258e9d2018-04-27 17:29:10 +0000762char LoopGuardWideningLegacyPass::ID = 0;
Sanjoy Das083f3892016-05-18 22:55:34 +0000763
764INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
765 false, false)
766INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
767INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
768INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
769INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
770 false, false)
771
Philip Reames9258e9d2018-04-27 17:29:10 +0000772INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
773 "Widen guards (within a single loop, as a loop pass)",
774 false, false)
775INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
776INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
777INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
778INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
779 "Widen guards (within a single loop, as a loop pass)",
780 false, false)
781
Sanjoy Das083f3892016-05-18 22:55:34 +0000782FunctionPass *llvm::createGuardWideningPass() {
783 return new GuardWideningLegacyPass();
784}
Philip Reames9258e9d2018-04-27 17:29:10 +0000785
786Pass *llvm::createLoopGuardWideningPass() {
787 return new LoopGuardWideningLegacyPass();
788}