1 //===- 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"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/DepthFirstIterator.h"
45 #include "llvm/Analysis/LoopInfo.h"
46 #include "llvm/Analysis/PostDominators.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/IR/ConstantRange.h"
49 #include "llvm/IR/Dominators.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/PatternMatch.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/KnownBits.h"
55 #include "llvm/Transforms/Scalar.h"
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "guard-widening"
60 
61 namespace {
62 
63 class GuardWideningImpl {
64   DominatorTree &DT;
65   PostDominatorTree &PDT;
66   LoopInfo &LI;
67 
68   /// The set of guards whose conditions have been widened into dominating
69   /// guards.
70   SmallVector<IntrinsicInst *, 16> EliminatedGuards;
71 
72   /// The set of guards which have been widened to include conditions to other
73   /// guards.
74   DenseSet<IntrinsicInst *> WidenedGuards;
75 
76   /// Try to eliminate guard \p Guard by widening it into an earlier dominating
77   /// guard.  \p DFSI is the DFS iterator on the dominator tree that is
78   /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
79   /// maps BasicBlocks to the set of guards seen in that block.
80   bool eliminateGuardViaWidening(
81       IntrinsicInst *Guard, const df_iterator<DomTreeNode *> &DFSI,
82       const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
83           GuardsPerBlock);
84 
85   /// Used to keep track of which widening potential is more effective.
86   enum WideningScore {
87     /// Don't widen.
88     WS_IllegalOrNegative,
89 
90     /// Widening is performance neutral as far as the cycles spent in check
91     /// conditions goes (but can still help, e.g., code layout, having less
92     /// deopt state).
93     WS_Neutral,
94 
95     /// Widening is profitable.
96     WS_Positive,
97 
98     /// Widening is very profitable.  Not significantly different from \c
99     /// WS_Positive, except by the order.
100     WS_VeryPositive
101   };
102 
103   static StringRef scoreTypeToString(WideningScore WS);
104 
105   /// Compute the score for widening the condition in \p DominatedGuard
106   /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
107   /// \p DominatingGuardLoop).
108   WideningScore computeWideningScore(IntrinsicInst *DominatedGuard,
109                                      Loop *DominatedGuardLoop,
110                                      IntrinsicInst *DominatingGuard,
111                                      Loop *DominatingGuardLoop);
112 
113   /// Helper to check if \p V can be hoisted to \p InsertPos.
114   bool isAvailableAt(Value *V, Instruction *InsertPos) {
115     SmallPtrSet<Instruction *, 8> Visited;
116     return isAvailableAt(V, InsertPos, Visited);
117   }
118 
119   bool isAvailableAt(Value *V, Instruction *InsertPos,
120                      SmallPtrSetImpl<Instruction *> &Visited);
121 
122   /// Helper to hoist \p V to \p InsertPos.  Guaranteed to succeed if \c
123   /// isAvailableAt returned true.
124   void makeAvailableAt(Value *V, Instruction *InsertPos);
125 
126   /// Common helper used by \c widenGuard and \c isWideningCondProfitable.  Try
127   /// to generate an expression computing the logical AND of \p Cond0 and \p
128   /// Cond1.  Return true if the expression computing the AND is only as
129   /// expensive as computing one of the two. If \p InsertPt is true then
130   /// actually generate the resulting expression, make it available at \p
131   /// InsertPt and return it in \p Result (else no change to the IR is made).
132   bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
133                        Value *&Result);
134 
135   /// Represents a range check of the form \c Base + \c Offset u< \c Length,
136   /// with the constraint that \c Length is not negative.  \c CheckInst is the
137   /// pre-existing instruction in the IR that computes the result of this range
138   /// check.
139   class RangeCheck {
140     Value *Base;
141     ConstantInt *Offset;
142     Value *Length;
143     ICmpInst *CheckInst;
144 
145   public:
146     explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
147                         ICmpInst *CheckInst)
148         : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
149 
150     void setBase(Value *NewBase) { Base = NewBase; }
151     void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
152 
153     Value *getBase() const { return Base; }
154     ConstantInt *getOffset() const { return Offset; }
155     const APInt &getOffsetValue() const { return getOffset()->getValue(); }
156     Value *getLength() const { return Length; };
157     ICmpInst *getCheckInst() const { return CheckInst; }
158 
159     void print(raw_ostream &OS, bool PrintTypes = false) {
160       OS << "Base: ";
161       Base->printAsOperand(OS, PrintTypes);
162       OS << " Offset: ";
163       Offset->printAsOperand(OS, PrintTypes);
164       OS << " Length: ";
165       Length->printAsOperand(OS, PrintTypes);
166     }
167 
168     LLVM_DUMP_METHOD void dump() {
169       print(dbgs());
170       dbgs() << "\n";
171     }
172   };
173 
174   /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
175   /// append them to \p Checks.  Returns true on success, may clobber \c Checks
176   /// on failure.
177   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
178     SmallPtrSet<Value *, 8> Visited;
179     return parseRangeChecks(CheckCond, Checks, Visited);
180   }
181 
182   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
183                         SmallPtrSetImpl<Value *> &Visited);
184 
185   /// Combine the checks in \p Checks into a smaller set of checks and append
186   /// them into \p CombinedChecks.  Return true on success (i.e. all of checks
187   /// in \p Checks were combined into \p CombinedChecks).  Clobbers \p Checks
188   /// and \p CombinedChecks on success and on failure.
189   bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
190                           SmallVectorImpl<RangeCheck> &CombinedChecks);
191 
192   /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
193   /// computing only one of the two expressions?
194   bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
195     Value *ResultUnused;
196     return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
197   }
198 
199   /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
200   /// whatever it is already checking).
201   void widenGuard(IntrinsicInst *ToWiden, Value *NewCondition) {
202     Value *Result;
203     widenCondCommon(ToWiden->getArgOperand(0), NewCondition, ToWiden, Result);
204     ToWiden->setArgOperand(0, Result);
205   }
206 
207 public:
208   explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree &PDT,
209                              LoopInfo &LI)
210       : DT(DT), PDT(PDT), LI(LI) {}
211 
212   /// The entry point for this pass.
213   bool run();
214 };
215 }
216 
217 bool GuardWideningImpl::run() {
218   using namespace llvm::PatternMatch;
219 
220   DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> GuardsInBlock;
221   bool Changed = false;
222 
223   for (auto DFI = df_begin(DT.getRootNode()), DFE = df_end(DT.getRootNode());
224        DFI != DFE; ++DFI) {
225     auto *BB = (*DFI)->getBlock();
226     auto &CurrentList = GuardsInBlock[BB];
227 
228     for (auto &I : *BB)
229       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
230         CurrentList.push_back(cast<IntrinsicInst>(&I));
231 
232     for (auto *II : CurrentList)
233       Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
234   }
235 
236   for (auto *II : EliminatedGuards)
237     if (!WidenedGuards.count(II))
238       II->eraseFromParent();
239 
240   return Changed;
241 }
242 
243 bool GuardWideningImpl::eliminateGuardViaWidening(
244     IntrinsicInst *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
245     const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
246         GuardsInBlock) {
247   IntrinsicInst *BestSoFar = nullptr;
248   auto BestScoreSoFar = WS_IllegalOrNegative;
249   auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
250 
251   // In the set of dominating guards, find the one we can merge GuardInst with
252   // for the most profit.
253   for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
254     auto *CurBB = DFSI.getPath(i)->getBlock();
255     auto *CurLoop = LI.getLoopFor(CurBB);
256     assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
257     const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
258 
259     auto I = GuardsInCurBB.begin();
260     auto E = GuardsInCurBB.end();
261 
262 #ifndef NDEBUG
263     {
264       unsigned Index = 0;
265       for (auto &I : *CurBB) {
266         if (Index == GuardsInCurBB.size())
267           break;
268         if (GuardsInCurBB[Index] == &I)
269           Index++;
270       }
271       assert(Index == GuardsInCurBB.size() &&
272              "Guards expected to be in order!");
273     }
274 #endif
275 
276     assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
277 
278     if (i == (e - 1)) {
279       // Corner case: make sure we're only looking at guards strictly dominating
280       // GuardInst when visiting GuardInst->getParent().
281       auto NewEnd = std::find(I, E, GuardInst);
282       assert(NewEnd != E && "GuardInst not in its own block?");
283       E = NewEnd;
284     }
285 
286     for (auto *Candidate : make_range(I, E)) {
287       auto Score =
288           computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
289       DEBUG(dbgs() << "Score between " << *GuardInst->getArgOperand(0)
290                    << " and " << *Candidate->getArgOperand(0) << " is "
291                    << scoreTypeToString(Score) << "\n");
292       if (Score > BestScoreSoFar) {
293         BestScoreSoFar = Score;
294         BestSoFar = Candidate;
295       }
296     }
297   }
298 
299   if (BestScoreSoFar == WS_IllegalOrNegative) {
300     DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
301     return false;
302   }
303 
304   assert(BestSoFar != GuardInst && "Should have never visited same guard!");
305   assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
306 
307   DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
308                << " with score " << scoreTypeToString(BestScoreSoFar) << "\n");
309   widenGuard(BestSoFar, GuardInst->getArgOperand(0));
310   GuardInst->setArgOperand(0, ConstantInt::getTrue(GuardInst->getContext()));
311   EliminatedGuards.push_back(GuardInst);
312   WidenedGuards.insert(BestSoFar);
313   return true;
314 }
315 
316 GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
317     IntrinsicInst *DominatedGuard, Loop *DominatedGuardLoop,
318     IntrinsicInst *DominatingGuard, Loop *DominatingGuardLoop) {
319   bool HoistingOutOfLoop = false;
320 
321   if (DominatingGuardLoop != DominatedGuardLoop) {
322     if (DominatingGuardLoop &&
323         !DominatingGuardLoop->contains(DominatedGuardLoop))
324       return WS_IllegalOrNegative;
325 
326     HoistingOutOfLoop = true;
327   }
328 
329   if (!isAvailableAt(DominatedGuard->getArgOperand(0), DominatingGuard))
330     return WS_IllegalOrNegative;
331 
332   bool HoistingOutOfIf =
333       !PDT.dominates(DominatedGuard->getParent(), DominatingGuard->getParent());
334 
335   if (isWideningCondProfitable(DominatedGuard->getArgOperand(0),
336                                DominatingGuard->getArgOperand(0)))
337     return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
338 
339   if (HoistingOutOfLoop)
340     return WS_Positive;
341 
342   return HoistingOutOfIf ? WS_IllegalOrNegative : WS_Neutral;
343 }
344 
345 bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
346                                       SmallPtrSetImpl<Instruction *> &Visited) {
347   auto *Inst = dyn_cast<Instruction>(V);
348   if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
349     return true;
350 
351   if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
352       Inst->mayReadFromMemory())
353     return false;
354 
355   Visited.insert(Inst);
356 
357   // We only want to go _up_ the dominance chain when recursing.
358   assert(!isa<PHINode>(Loc) &&
359          "PHIs should return false for isSafeToSpeculativelyExecute");
360   assert(DT.isReachableFromEntry(Inst->getParent()) &&
361          "We did a DFS from the block entry!");
362   return all_of(Inst->operands(),
363                 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
364 }
365 
366 void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
367   auto *Inst = dyn_cast<Instruction>(V);
368   if (!Inst || DT.dominates(Inst, Loc))
369     return;
370 
371   assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
372          !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
373 
374   for (Value *Op : Inst->operands())
375     makeAvailableAt(Op, Loc);
376 
377   Inst->moveBefore(Loc);
378 }
379 
380 bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
381                                         Instruction *InsertPt, Value *&Result) {
382   using namespace llvm::PatternMatch;
383 
384   {
385     // L >u C0 && L >u C1  ->  L >u max(C0, C1)
386     ConstantInt *RHS0, *RHS1;
387     Value *LHS;
388     ICmpInst::Predicate Pred0, Pred1;
389     if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
390         match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
391 
392       ConstantRange CR0 =
393           ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
394       ConstantRange CR1 =
395           ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
396 
397       // SubsetIntersect is a subset of the actual mathematical intersection of
398       // CR0 and CR1, while SupersetIntersect is a superset of the actual
399       // mathematical intersection.  If these two ConstantRanges are equal, then
400       // we know we were able to represent the actual mathematical intersection
401       // of CR0 and CR1, and can use the same to generate an icmp instruction.
402       //
403       // Given what we're doing here and the semantics of guards, it would
404       // actually be correct to just use SubsetIntersect, but that may be too
405       // aggressive in cases we care about.
406       auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
407       auto SupersetIntersect = CR0.intersectWith(CR1);
408 
409       APInt NewRHSAP;
410       CmpInst::Predicate Pred;
411       if (SubsetIntersect == SupersetIntersect &&
412           SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
413         if (InsertPt) {
414           ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
415           Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
416         }
417         return true;
418       }
419     }
420   }
421 
422   {
423     SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
424     if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
425         combineRangeChecks(Checks, CombinedChecks)) {
426       if (InsertPt) {
427         Result = nullptr;
428         for (auto &RC : CombinedChecks) {
429           makeAvailableAt(RC.getCheckInst(), InsertPt);
430           if (Result)
431             Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
432                                                InsertPt);
433           else
434             Result = RC.getCheckInst();
435         }
436 
437         Result->setName("wide.chk");
438       }
439       return true;
440     }
441   }
442 
443   // Base case -- just logical-and the two conditions together.
444 
445   if (InsertPt) {
446     makeAvailableAt(Cond0, InsertPt);
447     makeAvailableAt(Cond1, InsertPt);
448 
449     Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
450   }
451 
452   // We were not able to compute Cond0 AND Cond1 for the price of one.
453   return false;
454 }
455 
456 bool GuardWideningImpl::parseRangeChecks(
457     Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
458     SmallPtrSetImpl<Value *> &Visited) {
459   if (!Visited.insert(CheckCond).second)
460     return true;
461 
462   using namespace llvm::PatternMatch;
463 
464   {
465     Value *AndLHS, *AndRHS;
466     if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
467       return parseRangeChecks(AndLHS, Checks) &&
468              parseRangeChecks(AndRHS, Checks);
469   }
470 
471   auto *IC = dyn_cast<ICmpInst>(CheckCond);
472   if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
473       (IC->getPredicate() != ICmpInst::ICMP_ULT &&
474        IC->getPredicate() != ICmpInst::ICMP_UGT))
475     return false;
476 
477   Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
478   if (IC->getPredicate() == ICmpInst::ICMP_UGT)
479     std::swap(CmpLHS, CmpRHS);
480 
481   auto &DL = IC->getModule()->getDataLayout();
482 
483   GuardWideningImpl::RangeCheck Check(
484       CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
485       CmpRHS, IC);
486 
487   if (!isKnownNonNegative(Check.getLength(), DL))
488     return false;
489 
490   // What we have in \c Check now is a correct interpretation of \p CheckCond.
491   // Try to see if we can move some constant offsets into the \c Offset field.
492 
493   bool Changed;
494   auto &Ctx = CheckCond->getContext();
495 
496   do {
497     Value *OpLHS;
498     ConstantInt *OpRHS;
499     Changed = false;
500 
501 #ifndef NDEBUG
502     auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
503     assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
504            "Unreachable instruction?");
505 #endif
506 
507     if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
508       Check.setBase(OpLHS);
509       APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
510       Check.setOffset(ConstantInt::get(Ctx, NewOffset));
511       Changed = true;
512     } else if (match(Check.getBase(),
513                      m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
514       KnownBits Known = computeKnownBits(OpLHS, DL);
515       if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
516         Check.setBase(OpLHS);
517         APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
518         Check.setOffset(ConstantInt::get(Ctx, NewOffset));
519         Changed = true;
520       }
521     }
522   } while (Changed);
523 
524   Checks.push_back(Check);
525   return true;
526 }
527 
528 bool GuardWideningImpl::combineRangeChecks(
529     SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
530     SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
531   unsigned OldCount = Checks.size();
532   while (!Checks.empty()) {
533     // Pick all of the range checks with a specific base and length, and try to
534     // merge them.
535     Value *CurrentBase = Checks.front().getBase();
536     Value *CurrentLength = Checks.front().getLength();
537 
538     SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
539 
540     auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
541       return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
542     };
543 
544     copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
545     Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
546 
547     assert(CurrentChecks.size() != 0 && "We know we have at least one!");
548 
549     if (CurrentChecks.size() < 3) {
550       RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
551                             CurrentChecks.end());
552       continue;
553     }
554 
555     // CurrentChecks.size() will typically be 3 here, but so far there has been
556     // no need to hard-code that fact.
557 
558     std::sort(CurrentChecks.begin(), CurrentChecks.end(),
559               [&](const GuardWideningImpl::RangeCheck &LHS,
560                   const GuardWideningImpl::RangeCheck &RHS) {
561       return LHS.getOffsetValue().slt(RHS.getOffsetValue());
562     });
563 
564     // Note: std::sort should not invalidate the ChecksStart iterator.
565 
566     ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
567                 *MaxOffset = CurrentChecks.back().getOffset();
568 
569     unsigned BitWidth = MaxOffset->getValue().getBitWidth();
570     if ((MaxOffset->getValue() - MinOffset->getValue())
571             .ugt(APInt::getSignedMinValue(BitWidth)))
572       return false;
573 
574     APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
575     const APInt &HighOffset = MaxOffset->getValue();
576     auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
577       return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
578     };
579 
580     if (MaxDiff.isMinValue() ||
581         !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
582                      OffsetOK))
583       return false;
584 
585     // We have a series of f+1 checks as:
586     //
587     //   I+k_0 u< L   ... Chk_0
588     //   I+k_1 u< L   ... Chk_1
589     //   ...
590     //   I+k_f u< L   ... Chk_f
591     //
592     //     with forall i in [0,f]: k_f-k_i u< k_f-k_0  ... Precond_0
593     //          k_f-k_0 u< INT_MIN+k_f                 ... Precond_1
594     //          k_f != k_0                             ... Precond_2
595     //
596     // Claim:
597     //   Chk_0 AND Chk_f  implies all the other checks
598     //
599     // Informal proof sketch:
600     //
601     // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
602     // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
603     // thus I+k_f is the greatest unsigned value in that range.
604     //
605     // This combined with Ckh_(f+1) shows that everything in that range is u< L.
606     // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
607     // lie in [I+k_0,I+k_f], this proving our claim.
608     //
609     // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
610     // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
611     // since k_0 != k_f).  In the former case, [I+k_0,I+k_f] is not a wrapping
612     // range by definition, and the latter case is impossible:
613     //
614     //   0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
615     //   xxxxxx             xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
616     //
617     // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
618     // with 'x' above) to be at least >u INT_MIN.
619 
620     RangeChecksOut.emplace_back(CurrentChecks.front());
621     RangeChecksOut.emplace_back(CurrentChecks.back());
622   }
623 
624   assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
625   return RangeChecksOut.size() != OldCount;
626 }
627 
628 #ifndef NDEBUG
629 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
630   switch (WS) {
631   case WS_IllegalOrNegative:
632     return "IllegalOrNegative";
633   case WS_Neutral:
634     return "Neutral";
635   case WS_Positive:
636     return "Positive";
637   case WS_VeryPositive:
638     return "VeryPositive";
639   }
640 
641   llvm_unreachable("Fully covered switch above!");
642 }
643 #endif
644 
645 PreservedAnalyses GuardWideningPass::run(Function &F,
646                                          FunctionAnalysisManager &AM) {
647   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
648   auto &LI = AM.getResult<LoopAnalysis>(F);
649   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
650   if (!GuardWideningImpl(DT, PDT, LI).run())
651     return PreservedAnalyses::all();
652 
653   PreservedAnalyses PA;
654   PA.preserveSet<CFGAnalyses>();
655   return PA;
656 }
657 
658 namespace {
659 struct GuardWideningLegacyPass : public FunctionPass {
660   static char ID;
661   GuardWideningPass Impl;
662 
663   GuardWideningLegacyPass() : FunctionPass(ID) {
664     initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
665   }
666 
667   bool runOnFunction(Function &F) override {
668     if (skipFunction(F))
669       return false;
670     return GuardWideningImpl(
671                getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
672                getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(),
673                getAnalysis<LoopInfoWrapperPass>().getLoopInfo()).run();
674   }
675 
676   void getAnalysisUsage(AnalysisUsage &AU) const override {
677     AU.setPreservesCFG();
678     AU.addRequired<DominatorTreeWrapperPass>();
679     AU.addRequired<PostDominatorTreeWrapperPass>();
680     AU.addRequired<LoopInfoWrapperPass>();
681   }
682 };
683 }
684 
685 char GuardWideningLegacyPass::ID = 0;
686 
687 INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
688                       false, false)
689 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
690 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
691 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
692 INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
693                     false, false)
694 
695 FunctionPass *llvm::createGuardWideningPass() {
696   return new GuardWideningLegacyPass();
697 }
698