1 //===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the guard widening pass.  The semantics of the
10 // @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
11 // more often that it did before the transform.  This optimization is called
12 // "widening" and can be used hoist and common runtime checks in situations like
13 // these:
14 //
15 //    %cmp0 = 7 u< Length
16 //    call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
17 //    call @unknown_side_effects()
18 //    %cmp1 = 9 u< Length
19 //    call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
20 //    ...
21 //
22 // =>
23 //
24 //    %cmp0 = 9 u< Length
25 //    call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
26 //    call @unknown_side_effects()
27 //    ...
28 //
29 // If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
30 // generic implementation of the same function, which will have the correct
31 // semantics from that point onward.  It is always _legal_ to deoptimize (so
32 // replacing %cmp0 with false is "correct"), though it may not always be
33 // profitable to do so.
34 //
35 // NB! This pass is a work in progress.  It hasn't been tuned to be "production
36 // ready" yet.  It is known to have quadriatic running time and will not scale
37 // to large numbers of guards
38 //
39 //===----------------------------------------------------------------------===//
40 
41 #include "llvm/Transforms/Scalar/GuardWidening.h"
42 #include <functional>
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/DepthFirstIterator.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Analysis/BranchProbabilityInfo.h"
47 #include "llvm/Analysis/GuardUtils.h"
48 #include "llvm/Analysis/LoopInfo.h"
49 #include "llvm/Analysis/LoopPass.h"
50 #include "llvm/Analysis/PostDominators.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/ConstantRange.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/PatternMatch.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/KnownBits.h"
59 #include "llvm/Transforms/Scalar.h"
60 #include "llvm/Transforms/Utils/LoopUtils.h"
61 
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "guard-widening"
65 
66 STATISTIC(GuardsEliminated, "Number of eliminated guards");
67 STATISTIC(CondBranchEliminated, "Number of eliminated conditional branches");
68 
69 static cl::opt<bool> WidenFrequentBranches(
70     "guard-widening-widen-frequent-branches", cl::Hidden,
71     cl::desc("Widen conditions of explicit branches into dominating guards in "
72              "case if their taken frequency exceeds threshold set by "
73              "guard-widening-frequent-branch-threshold option"),
74     cl::init(false));
75 
76 static cl::opt<unsigned> FrequentBranchThreshold(
77     "guard-widening-frequent-branch-threshold", cl::Hidden,
78     cl::desc("When WidenFrequentBranches is set to true, this option is used "
79              "to determine which branches are frequently taken. The criteria "
80              "that a branch is taken more often than "
81              "((FrequentBranchThreshold - 1) / FrequentBranchThreshold), then "
82              "it is considered frequently taken"),
83     cl::init(1000));
84 
85 static cl::opt<bool>
86     WidenBranchGuards("guard-widening-widen-branch-guards", cl::Hidden,
87                       cl::desc("Whether or not we should widen guards  "
88                                "expressed as branches by widenable conditions"),
89                       cl::init(true));
90 
91 namespace {
92 
93 // Get the condition of \p I. It can either be a guard or a conditional branch.
94 static Value *getCondition(Instruction *I) {
95   if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
96     assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
97            "Bad guard intrinsic?");
98     return GI->getArgOperand(0);
99   }
100   if (isGuardAsWidenableBranch(I)) {
101     auto *Cond = cast<BranchInst>(I)->getCondition();
102     return cast<BinaryOperator>(Cond)->getOperand(0);
103   }
104   return cast<BranchInst>(I)->getCondition();
105 }
106 
107 // Set the condition for \p I to \p NewCond. \p I can either be a guard or a
108 // conditional branch.
109 static void setCondition(Instruction *I, Value *NewCond) {
110   if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
111     assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
112            "Bad guard intrinsic?");
113     GI->setArgOperand(0, NewCond);
114     return;
115   }
116   cast<BranchInst>(I)->setCondition(NewCond);
117 }
118 
119 // Eliminates the guard instruction properly.
120 static void eliminateGuard(Instruction *GuardInst) {
121   GuardInst->eraseFromParent();
122   ++GuardsEliminated;
123 }
124 
125 class GuardWideningImpl {
126   DominatorTree &DT;
127   PostDominatorTree *PDT;
128   LoopInfo &LI;
129   BranchProbabilityInfo *BPI;
130 
131   /// Together, these describe the region of interest.  This might be all of
132   /// the blocks within a function, or only a given loop's blocks and preheader.
133   DomTreeNode *Root;
134   std::function<bool(BasicBlock*)> BlockFilter;
135 
136   /// The set of guards and conditional branches whose conditions have been
137   /// widened into dominating guards.
138   SmallVector<Instruction *, 16> EliminatedGuardsAndBranches;
139 
140   /// The set of guards which have been widened to include conditions to other
141   /// guards.
142   DenseSet<Instruction *> WidenedGuards;
143 
144   /// Try to eliminate instruction \p Instr by widening it into an earlier
145   /// dominating guard.  \p DFSI is the DFS iterator on the dominator tree that
146   /// is currently visiting the block containing \p Guard, and \p GuardsPerBlock
147   /// maps BasicBlocks to the set of guards seen in that block.
148   bool eliminateInstrViaWidening(
149       Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
150       const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
151           GuardsPerBlock, bool InvertCondition = false);
152 
153   /// Used to keep track of which widening potential is more effective.
154   enum WideningScore {
155     /// Don't widen.
156     WS_IllegalOrNegative,
157 
158     /// Widening is performance neutral as far as the cycles spent in check
159     /// conditions goes (but can still help, e.g., code layout, having less
160     /// deopt state).
161     WS_Neutral,
162 
163     /// Widening is profitable.
164     WS_Positive,
165 
166     /// Widening is very profitable.  Not significantly different from \c
167     /// WS_Positive, except by the order.
168     WS_VeryPositive
169   };
170 
171   static StringRef scoreTypeToString(WideningScore WS);
172 
173   /// Compute the score for widening the condition in \p DominatedInstr
174   /// into \p DominatingGuard. If \p InvertCond is set, then we widen the
175   /// inverted condition of the dominating guard.
176   WideningScore computeWideningScore(Instruction *DominatedInstr,
177                                      Instruction *DominatingGuard,
178                                      bool InvertCond);
179 
180   /// Helper to check if \p V can be hoisted to \p InsertPos.
181   bool isAvailableAt(const Value *V, const Instruction *InsertPos) const {
182     SmallPtrSet<const Instruction *, 8> Visited;
183     return isAvailableAt(V, InsertPos, Visited);
184   }
185 
186   bool isAvailableAt(const Value *V, const Instruction *InsertPos,
187                      SmallPtrSetImpl<const Instruction *> &Visited) const;
188 
189   /// Helper to hoist \p V to \p InsertPos.  Guaranteed to succeed if \c
190   /// isAvailableAt returned true.
191   void makeAvailableAt(Value *V, Instruction *InsertPos) const;
192 
193   /// Common helper used by \c widenGuard and \c isWideningCondProfitable.  Try
194   /// to generate an expression computing the logical AND of \p Cond0 and (\p
195   /// Cond1 XOR \p InvertCondition).
196   /// Return true if the expression computing the AND is only as
197   /// expensive as computing one of the two. If \p InsertPt is true then
198   /// actually generate the resulting expression, make it available at \p
199   /// InsertPt and return it in \p Result (else no change to the IR is made).
200   bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
201                        Value *&Result, bool InvertCondition);
202 
203   /// Represents a range check of the form \c Base + \c Offset u< \c Length,
204   /// with the constraint that \c Length is not negative.  \c CheckInst is the
205   /// pre-existing instruction in the IR that computes the result of this range
206   /// check.
207   class RangeCheck {
208     const Value *Base;
209     const ConstantInt *Offset;
210     const Value *Length;
211     ICmpInst *CheckInst;
212 
213   public:
214     explicit RangeCheck(const Value *Base, const ConstantInt *Offset,
215                         const Value *Length, ICmpInst *CheckInst)
216         : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
217 
218     void setBase(const Value *NewBase) { Base = NewBase; }
219     void setOffset(const ConstantInt *NewOffset) { Offset = NewOffset; }
220 
221     const Value *getBase() const { return Base; }
222     const ConstantInt *getOffset() const { return Offset; }
223     const APInt &getOffsetValue() const { return getOffset()->getValue(); }
224     const Value *getLength() const { return Length; };
225     ICmpInst *getCheckInst() const { return CheckInst; }
226 
227     void print(raw_ostream &OS, bool PrintTypes = false) {
228       OS << "Base: ";
229       Base->printAsOperand(OS, PrintTypes);
230       OS << " Offset: ";
231       Offset->printAsOperand(OS, PrintTypes);
232       OS << " Length: ";
233       Length->printAsOperand(OS, PrintTypes);
234     }
235 
236     LLVM_DUMP_METHOD void dump() {
237       print(dbgs());
238       dbgs() << "\n";
239     }
240   };
241 
242   /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
243   /// append them to \p Checks.  Returns true on success, may clobber \c Checks
244   /// on failure.
245   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
246     SmallPtrSet<const Value *, 8> Visited;
247     return parseRangeChecks(CheckCond, Checks, Visited);
248   }
249 
250   bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
251                         SmallPtrSetImpl<const Value *> &Visited);
252 
253   /// Combine the checks in \p Checks into a smaller set of checks and append
254   /// them into \p CombinedChecks.  Return true on success (i.e. all of checks
255   /// in \p Checks were combined into \p CombinedChecks).  Clobbers \p Checks
256   /// and \p CombinedChecks on success and on failure.
257   bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
258                           SmallVectorImpl<RangeCheck> &CombinedChecks) const;
259 
260   /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
261   /// computing only one of the two expressions?
262   bool isWideningCondProfitable(Value *Cond0, Value *Cond1, bool InvertCond) {
263     Value *ResultUnused;
264     return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused,
265                            InvertCond);
266   }
267 
268   /// If \p InvertCondition is false, Widen \p ToWiden to fail if
269   /// \p NewCondition is false, otherwise make it fail if \p NewCondition is
270   /// true (in addition to whatever it is already checking).
271   void widenGuard(Instruction *ToWiden, Value *NewCondition,
272                   bool InvertCondition) {
273     Value *Result;
274 
275     widenCondCommon(getCondition(ToWiden), NewCondition, ToWiden, Result,
276                     InvertCondition);
277     if (isGuardAsWidenableBranch(ToWiden)) {
278       auto *BI = cast<BranchInst>(ToWiden);
279       auto *And = cast<Instruction>(BI->getCondition());
280       And->setOperand(0, Result);
281       And->moveBefore(ToWiden);
282       assert(isGuardAsWidenableBranch(ToWiden) && "still widenable?");
283       return;
284     }
285     setCondition(ToWiden, Result);
286   }
287 
288 public:
289 
290   explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
291                              LoopInfo &LI, BranchProbabilityInfo *BPI,
292                              DomTreeNode *Root,
293                              std::function<bool(BasicBlock*)> BlockFilter)
294     : DT(DT), PDT(PDT), LI(LI), BPI(BPI), Root(Root), BlockFilter(BlockFilter)
295         {}
296 
297   /// The entry point for this pass.
298   bool run();
299 };
300 }
301 
302 static bool isSupportedGuardInstruction(const Instruction *Insn) {
303   if (isGuard(Insn))
304     return true;
305   if (WidenBranchGuards && isGuardAsWidenableBranch(Insn))
306     return true;
307   return false;
308 }
309 
310 bool GuardWideningImpl::run() {
311   DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
312   bool Changed = false;
313   Optional<BranchProbability> LikelyTaken = None;
314   if (WidenFrequentBranches && BPI) {
315     unsigned Threshold = FrequentBranchThreshold;
316     assert(Threshold > 0 && "Zero threshold makes no sense!");
317     LikelyTaken = BranchProbability(Threshold - 1, Threshold);
318   }
319 
320   for (auto DFI = df_begin(Root), DFE = df_end(Root);
321        DFI != DFE; ++DFI) {
322     auto *BB = (*DFI)->getBlock();
323     if (!BlockFilter(BB))
324       continue;
325 
326     auto &CurrentList = GuardsInBlock[BB];
327 
328     for (auto &I : *BB)
329       if (isSupportedGuardInstruction(&I))
330         CurrentList.push_back(cast<Instruction>(&I));
331 
332     for (auto *II : CurrentList)
333       Changed |= eliminateInstrViaWidening(II, DFI, GuardsInBlock);
334     if (WidenFrequentBranches && BPI)
335       if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator()))
336         if (BI->isConditional()) {
337           // If one of branches of a conditional is likely taken, try to
338           // eliminate it.
339           if (BPI->getEdgeProbability(BB, 0U) >= *LikelyTaken)
340             Changed |= eliminateInstrViaWidening(BI, DFI, GuardsInBlock);
341           else if (BPI->getEdgeProbability(BB, 1U) >= *LikelyTaken)
342             Changed |= eliminateInstrViaWidening(BI, DFI, GuardsInBlock,
343                                                  /*InvertCondition*/true);
344         }
345   }
346 
347   assert(EliminatedGuardsAndBranches.empty() || Changed);
348   for (auto *I : EliminatedGuardsAndBranches)
349     if (!WidenedGuards.count(I)) {
350       assert(isa<ConstantInt>(getCondition(I)) && "Should be!");
351       if (isSupportedGuardInstruction(I))
352         eliminateGuard(I);
353       else {
354         assert(isa<BranchInst>(I) &&
355                "Eliminated something other than guard or branch?");
356         ++CondBranchEliminated;
357       }
358     }
359 
360   return Changed;
361 }
362 
363 bool GuardWideningImpl::eliminateInstrViaWidening(
364     Instruction *Instr, const df_iterator<DomTreeNode *> &DFSI,
365     const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
366         GuardsInBlock, bool InvertCondition) {
367   // Ignore trivial true or false conditions. These instructions will be
368   // trivially eliminated by any cleanup pass. Do not erase them because other
369   // guards can possibly be widened into them.
370   if (isa<ConstantInt>(getCondition(Instr)))
371     return false;
372 
373   Instruction *BestSoFar = nullptr;
374   auto BestScoreSoFar = WS_IllegalOrNegative;
375 
376   // In the set of dominating guards, find the one we can merge GuardInst with
377   // for the most profit.
378   for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
379     auto *CurBB = DFSI.getPath(i)->getBlock();
380     if (!BlockFilter(CurBB))
381       break;
382     assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
383     const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
384 
385     auto I = GuardsInCurBB.begin();
386     auto E = Instr->getParent() == CurBB
387                  ? std::find(GuardsInCurBB.begin(), GuardsInCurBB.end(), Instr)
388                  : GuardsInCurBB.end();
389 
390 #ifndef NDEBUG
391     {
392       unsigned Index = 0;
393       for (auto &I : *CurBB) {
394         if (Index == GuardsInCurBB.size())
395           break;
396         if (GuardsInCurBB[Index] == &I)
397           Index++;
398       }
399       assert(Index == GuardsInCurBB.size() &&
400              "Guards expected to be in order!");
401     }
402 #endif
403 
404     assert((i == (e - 1)) == (Instr->getParent() == CurBB) && "Bad DFS?");
405 
406     for (auto *Candidate : make_range(I, E)) {
407       auto Score = computeWideningScore(Instr, Candidate, InvertCondition);
408       LLVM_DEBUG(dbgs() << "Score between " << *getCondition(Instr)
409                         << " and " << *getCondition(Candidate) << " is "
410                         << scoreTypeToString(Score) << "\n");
411       if (Score > BestScoreSoFar) {
412         BestScoreSoFar = Score;
413         BestSoFar = Candidate;
414       }
415     }
416   }
417 
418   if (BestScoreSoFar == WS_IllegalOrNegative) {
419     LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *Instr << "\n");
420     return false;
421   }
422 
423   assert(BestSoFar != Instr && "Should have never visited same guard!");
424   assert(DT.dominates(BestSoFar, Instr) && "Should be!");
425 
426   LLVM_DEBUG(dbgs() << "Widening " << *Instr << " into " << *BestSoFar
427                     << " with score " << scoreTypeToString(BestScoreSoFar)
428                     << "\n");
429   widenGuard(BestSoFar, getCondition(Instr), InvertCondition);
430   auto NewGuardCondition = InvertCondition
431                                ? ConstantInt::getFalse(Instr->getContext())
432                                : ConstantInt::getTrue(Instr->getContext());
433   setCondition(Instr, NewGuardCondition);
434   EliminatedGuardsAndBranches.push_back(Instr);
435   WidenedGuards.insert(BestSoFar);
436   return true;
437 }
438 
439 GuardWideningImpl::WideningScore
440 GuardWideningImpl::computeWideningScore(Instruction *DominatedInstr,
441                                         Instruction *DominatingGuard,
442                                         bool InvertCond) {
443   Loop *DominatedInstrLoop = LI.getLoopFor(DominatedInstr->getParent());
444   Loop *DominatingGuardLoop = LI.getLoopFor(DominatingGuard->getParent());
445   bool HoistingOutOfLoop = false;
446 
447   if (DominatingGuardLoop != DominatedInstrLoop) {
448     // Be conservative and don't widen into a sibling loop.  TODO: If the
449     // sibling is colder, we should consider allowing this.
450     if (DominatingGuardLoop &&
451         !DominatingGuardLoop->contains(DominatedInstrLoop))
452       return WS_IllegalOrNegative;
453 
454     HoistingOutOfLoop = true;
455   }
456 
457   if (!isAvailableAt(getCondition(DominatedInstr), DominatingGuard))
458     return WS_IllegalOrNegative;
459 
460   // If the guard was conditional executed, it may never be reached
461   // dynamically.  There are two potential downsides to hoisting it out of the
462   // conditionally executed region: 1) we may spuriously deopt without need and
463   // 2) we have the extra cost of computing the guard condition in the common
464   // case.  At the moment, we really only consider the second in our heuristic
465   // here.  TODO: evaluate cost model for spurious deopt
466   // NOTE: As written, this also lets us hoist right over another guard which
467   // is essentially just another spelling for control flow.
468   if (isWideningCondProfitable(getCondition(DominatedInstr),
469                                getCondition(DominatingGuard), InvertCond))
470     return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
471 
472   if (HoistingOutOfLoop)
473     return WS_Positive;
474 
475   // Returns true if we might be hoisting above explicit control flow.  Note
476   // that this completely ignores implicit control flow (guards, calls which
477   // throw, etc...).  That choice appears arbitrary.
478   auto MaybeHoistingOutOfIf = [&]() {
479     auto *DominatingBlock = DominatingGuard->getParent();
480     auto *DominatedBlock = DominatedInstr->getParent();
481     if (isGuardAsWidenableBranch(DominatingGuard))
482       DominatingBlock = cast<BranchInst>(DominatingGuard)->getSuccessor(0);
483 
484     // Same Block?
485     if (DominatedBlock == DominatingBlock)
486       return false;
487     // Obvious successor (common loop header/preheader case)
488     if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
489       return false;
490     // TODO: diamond, triangle cases
491     if (!PDT) return true;
492     return !PDT->dominates(DominatedBlock, DominatingBlock);
493   };
494 
495   return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
496 }
497 
498 bool GuardWideningImpl::isAvailableAt(
499     const Value *V, const Instruction *Loc,
500     SmallPtrSetImpl<const Instruction *> &Visited) const {
501   auto *Inst = dyn_cast<Instruction>(V);
502   if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
503     return true;
504 
505   if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
506       Inst->mayReadFromMemory())
507     return false;
508 
509   Visited.insert(Inst);
510 
511   // We only want to go _up_ the dominance chain when recursing.
512   assert(!isa<PHINode>(Loc) &&
513          "PHIs should return false for isSafeToSpeculativelyExecute");
514   assert(DT.isReachableFromEntry(Inst->getParent()) &&
515          "We did a DFS from the block entry!");
516   return all_of(Inst->operands(),
517                 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
518 }
519 
520 void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) const {
521   auto *Inst = dyn_cast<Instruction>(V);
522   if (!Inst || DT.dominates(Inst, Loc))
523     return;
524 
525   assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
526          !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
527 
528   for (Value *Op : Inst->operands())
529     makeAvailableAt(Op, Loc);
530 
531   Inst->moveBefore(Loc);
532 }
533 
534 bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
535                                         Instruction *InsertPt, Value *&Result,
536                                         bool InvertCondition) {
537   using namespace llvm::PatternMatch;
538 
539   {
540     // L >u C0 && L >u C1  ->  L >u max(C0, C1)
541     ConstantInt *RHS0, *RHS1;
542     Value *LHS;
543     ICmpInst::Predicate Pred0, Pred1;
544     if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
545         match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
546       if (InvertCondition)
547         Pred1 = ICmpInst::getInversePredicate(Pred1);
548 
549       ConstantRange CR0 =
550           ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
551       ConstantRange CR1 =
552           ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
553 
554       // SubsetIntersect is a subset of the actual mathematical intersection of
555       // CR0 and CR1, while SupersetIntersect is a superset of the actual
556       // mathematical intersection.  If these two ConstantRanges are equal, then
557       // we know we were able to represent the actual mathematical intersection
558       // of CR0 and CR1, and can use the same to generate an icmp instruction.
559       //
560       // Given what we're doing here and the semantics of guards, it would
561       // actually be correct to just use SubsetIntersect, but that may be too
562       // aggressive in cases we care about.
563       auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
564       auto SupersetIntersect = CR0.intersectWith(CR1);
565 
566       APInt NewRHSAP;
567       CmpInst::Predicate Pred;
568       if (SubsetIntersect == SupersetIntersect &&
569           SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
570         if (InsertPt) {
571           ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
572           Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
573         }
574         return true;
575       }
576     }
577   }
578 
579   {
580     SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
581     // TODO: Support InvertCondition case?
582     if (!InvertCondition &&
583         parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
584         combineRangeChecks(Checks, CombinedChecks)) {
585       if (InsertPt) {
586         Result = nullptr;
587         for (auto &RC : CombinedChecks) {
588           makeAvailableAt(RC.getCheckInst(), InsertPt);
589           if (Result)
590             Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
591                                                InsertPt);
592           else
593             Result = RC.getCheckInst();
594         }
595         assert(Result && "Failed to find result value");
596         Result->setName("wide.chk");
597       }
598       return true;
599     }
600   }
601 
602   // Base case -- just logical-and the two conditions together.
603 
604   if (InsertPt) {
605     makeAvailableAt(Cond0, InsertPt);
606     makeAvailableAt(Cond1, InsertPt);
607     if (InvertCondition)
608       Cond1 = BinaryOperator::CreateNot(Cond1, "inverted", InsertPt);
609     Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
610   }
611 
612   // We were not able to compute Cond0 AND Cond1 for the price of one.
613   return false;
614 }
615 
616 bool GuardWideningImpl::parseRangeChecks(
617     Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
618     SmallPtrSetImpl<const Value *> &Visited) {
619   if (!Visited.insert(CheckCond).second)
620     return true;
621 
622   using namespace llvm::PatternMatch;
623 
624   {
625     Value *AndLHS, *AndRHS;
626     if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
627       return parseRangeChecks(AndLHS, Checks) &&
628              parseRangeChecks(AndRHS, Checks);
629   }
630 
631   auto *IC = dyn_cast<ICmpInst>(CheckCond);
632   if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
633       (IC->getPredicate() != ICmpInst::ICMP_ULT &&
634        IC->getPredicate() != ICmpInst::ICMP_UGT))
635     return false;
636 
637   const Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
638   if (IC->getPredicate() == ICmpInst::ICMP_UGT)
639     std::swap(CmpLHS, CmpRHS);
640 
641   auto &DL = IC->getModule()->getDataLayout();
642 
643   GuardWideningImpl::RangeCheck Check(
644       CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
645       CmpRHS, IC);
646 
647   if (!isKnownNonNegative(Check.getLength(), DL))
648     return false;
649 
650   // What we have in \c Check now is a correct interpretation of \p CheckCond.
651   // Try to see if we can move some constant offsets into the \c Offset field.
652 
653   bool Changed;
654   auto &Ctx = CheckCond->getContext();
655 
656   do {
657     Value *OpLHS;
658     ConstantInt *OpRHS;
659     Changed = false;
660 
661 #ifndef NDEBUG
662     auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
663     assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
664            "Unreachable instruction?");
665 #endif
666 
667     if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
668       Check.setBase(OpLHS);
669       APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
670       Check.setOffset(ConstantInt::get(Ctx, NewOffset));
671       Changed = true;
672     } else if (match(Check.getBase(),
673                      m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
674       KnownBits Known = computeKnownBits(OpLHS, DL);
675       if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
676         Check.setBase(OpLHS);
677         APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
678         Check.setOffset(ConstantInt::get(Ctx, NewOffset));
679         Changed = true;
680       }
681     }
682   } while (Changed);
683 
684   Checks.push_back(Check);
685   return true;
686 }
687 
688 bool GuardWideningImpl::combineRangeChecks(
689     SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
690     SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) const {
691   unsigned OldCount = Checks.size();
692   while (!Checks.empty()) {
693     // Pick all of the range checks with a specific base and length, and try to
694     // merge them.
695     const Value *CurrentBase = Checks.front().getBase();
696     const Value *CurrentLength = Checks.front().getLength();
697 
698     SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
699 
700     auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
701       return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
702     };
703 
704     copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
705     Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
706 
707     assert(CurrentChecks.size() != 0 && "We know we have at least one!");
708 
709     if (CurrentChecks.size() < 3) {
710       RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
711                             CurrentChecks.end());
712       continue;
713     }
714 
715     // CurrentChecks.size() will typically be 3 here, but so far there has been
716     // no need to hard-code that fact.
717 
718     llvm::sort(CurrentChecks, [&](const GuardWideningImpl::RangeCheck &LHS,
719                                   const GuardWideningImpl::RangeCheck &RHS) {
720       return LHS.getOffsetValue().slt(RHS.getOffsetValue());
721     });
722 
723     // Note: std::sort should not invalidate the ChecksStart iterator.
724 
725     const ConstantInt *MinOffset = CurrentChecks.front().getOffset();
726     const ConstantInt *MaxOffset = CurrentChecks.back().getOffset();
727 
728     unsigned BitWidth = MaxOffset->getValue().getBitWidth();
729     if ((MaxOffset->getValue() - MinOffset->getValue())
730             .ugt(APInt::getSignedMinValue(BitWidth)))
731       return false;
732 
733     APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
734     const APInt &HighOffset = MaxOffset->getValue();
735     auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
736       return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
737     };
738 
739     if (MaxDiff.isMinValue() ||
740         !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
741                      OffsetOK))
742       return false;
743 
744     // We have a series of f+1 checks as:
745     //
746     //   I+k_0 u< L   ... Chk_0
747     //   I+k_1 u< L   ... Chk_1
748     //   ...
749     //   I+k_f u< L   ... Chk_f
750     //
751     //     with forall i in [0,f]: k_f-k_i u< k_f-k_0  ... Precond_0
752     //          k_f-k_0 u< INT_MIN+k_f                 ... Precond_1
753     //          k_f != k_0                             ... Precond_2
754     //
755     // Claim:
756     //   Chk_0 AND Chk_f  implies all the other checks
757     //
758     // Informal proof sketch:
759     //
760     // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
761     // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
762     // thus I+k_f is the greatest unsigned value in that range.
763     //
764     // This combined with Ckh_(f+1) shows that everything in that range is u< L.
765     // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
766     // lie in [I+k_0,I+k_f], this proving our claim.
767     //
768     // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
769     // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
770     // since k_0 != k_f).  In the former case, [I+k_0,I+k_f] is not a wrapping
771     // range by definition, and the latter case is impossible:
772     //
773     //   0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
774     //   xxxxxx             xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
775     //
776     // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
777     // with 'x' above) to be at least >u INT_MIN.
778 
779     RangeChecksOut.emplace_back(CurrentChecks.front());
780     RangeChecksOut.emplace_back(CurrentChecks.back());
781   }
782 
783   assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
784   return RangeChecksOut.size() != OldCount;
785 }
786 
787 #ifndef NDEBUG
788 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
789   switch (WS) {
790   case WS_IllegalOrNegative:
791     return "IllegalOrNegative";
792   case WS_Neutral:
793     return "Neutral";
794   case WS_Positive:
795     return "Positive";
796   case WS_VeryPositive:
797     return "VeryPositive";
798   }
799 
800   llvm_unreachable("Fully covered switch above!");
801 }
802 #endif
803 
804 PreservedAnalyses GuardWideningPass::run(Function &F,
805                                          FunctionAnalysisManager &AM) {
806   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
807   auto &LI = AM.getResult<LoopAnalysis>(F);
808   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
809   BranchProbabilityInfo *BPI = nullptr;
810   if (WidenFrequentBranches)
811     BPI = AM.getCachedResult<BranchProbabilityAnalysis>(F);
812   if (!GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
813                          [](BasicBlock*) { return true; } ).run())
814     return PreservedAnalyses::all();
815 
816   PreservedAnalyses PA;
817   PA.preserveSet<CFGAnalyses>();
818   return PA;
819 }
820 
821 PreservedAnalyses GuardWideningPass::run(Loop &L, LoopAnalysisManager &AM,
822                                          LoopStandardAnalysisResults &AR,
823                                          LPMUpdater &U) {
824 
825   const auto &FAM =
826     AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
827   Function &F = *L.getHeader()->getParent();
828   BranchProbabilityInfo *BPI = nullptr;
829   if (WidenFrequentBranches)
830     BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(F);
831 
832   BasicBlock *RootBB = L.getLoopPredecessor();
833   if (!RootBB)
834     RootBB = L.getHeader();
835   auto BlockFilter = [&](BasicBlock *BB) {
836     return BB == RootBB || L.contains(BB);
837   };
838   if (!GuardWideningImpl(AR.DT, nullptr, AR.LI, BPI,
839                          AR.DT.getNode(RootBB),
840                          BlockFilter).run())
841     return PreservedAnalyses::all();
842 
843   return getLoopPassPreservedAnalyses();
844 }
845 
846 namespace {
847 struct GuardWideningLegacyPass : public FunctionPass {
848   static char ID;
849 
850   GuardWideningLegacyPass() : FunctionPass(ID) {
851     initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
852   }
853 
854   bool runOnFunction(Function &F) override {
855     if (skipFunction(F))
856       return false;
857     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
858     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
859     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
860     BranchProbabilityInfo *BPI = nullptr;
861     if (WidenFrequentBranches)
862       BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
863     return GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
864                          [](BasicBlock*) { return true; } ).run();
865   }
866 
867   void getAnalysisUsage(AnalysisUsage &AU) const override {
868     AU.setPreservesCFG();
869     AU.addRequired<DominatorTreeWrapperPass>();
870     AU.addRequired<PostDominatorTreeWrapperPass>();
871     AU.addRequired<LoopInfoWrapperPass>();
872     if (WidenFrequentBranches)
873       AU.addRequired<BranchProbabilityInfoWrapperPass>();
874   }
875 };
876 
877 /// Same as above, but restricted to a single loop at a time.  Can be
878 /// scheduled with other loop passes w/o breaking out of LPM
879 struct LoopGuardWideningLegacyPass : public LoopPass {
880   static char ID;
881 
882   LoopGuardWideningLegacyPass() : LoopPass(ID) {
883     initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
884   }
885 
886   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
887     if (skipLoop(L))
888       return false;
889     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
890     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
891     auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
892     auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
893     BasicBlock *RootBB = L->getLoopPredecessor();
894     if (!RootBB)
895       RootBB = L->getHeader();
896     auto BlockFilter = [&](BasicBlock *BB) {
897       return BB == RootBB || L->contains(BB);
898     };
899     BranchProbabilityInfo *BPI = nullptr;
900     if (WidenFrequentBranches)
901       BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
902     return GuardWideningImpl(DT, PDT, LI, BPI,
903                              DT.getNode(RootBB), BlockFilter).run();
904   }
905 
906   void getAnalysisUsage(AnalysisUsage &AU) const override {
907     if (WidenFrequentBranches)
908       AU.addRequired<BranchProbabilityInfoWrapperPass>();
909     AU.setPreservesCFG();
910     getLoopAnalysisUsage(AU);
911     AU.addPreserved<PostDominatorTreeWrapperPass>();
912   }
913 };
914 }
915 
916 char GuardWideningLegacyPass::ID = 0;
917 char LoopGuardWideningLegacyPass::ID = 0;
918 
919 INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
920                       false, false)
921 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
922 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
923 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
924 if (WidenFrequentBranches)
925   INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
926 INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
927                     false, false)
928 
929 INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
930                       "Widen guards (within a single loop, as a loop pass)",
931                       false, false)
932 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
933 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
934 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
935 if (WidenFrequentBranches)
936   INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
937 INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
938                     "Widen guards (within a single loop, as a loop pass)",
939                     false, false)
940 
941 FunctionPass *llvm::createGuardWideningPass() {
942   return new GuardWideningLegacyPass();
943 }
944 
945 Pass *llvm::createLoopGuardWideningPass() {
946   return new LoopGuardWideningLegacyPass();
947 }
948