LLVM  14.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
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 contains routines that help analyze properties that chains of
10 // computations have.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/IR/Argument.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/ConstantRange.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalAlias.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/Intrinsics.h"
55 #include "llvm/IR/IntrinsicsAArch64.h"
56 #include "llvm/IR/IntrinsicsRISCV.h"
57 #include "llvm/IR/IntrinsicsX86.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Metadata.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/User.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/KnownBits.h"
72 #include <algorithm>
73 #include <array>
74 #include <cassert>
75 #include <cstdint>
76 #include <iterator>
77 #include <utility>
78 
79 using namespace llvm;
80 using namespace llvm::PatternMatch;
81 
82 // Controls the number of uses of the value searched for possible
83 // dominating comparisons.
84 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
85  cl::Hidden, cl::init(20));
86 
87 /// Returns the bitwidth of the given scalar or pointer type. For vector types,
88 /// returns the element type's bitwidth.
89 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
90  if (unsigned BitWidth = Ty->getScalarSizeInBits())
91  return BitWidth;
92 
93  return DL.getPointerTypeSizeInBits(Ty);
94 }
95 
96 namespace {
97 
98 // Simplifying using an assume can only be done in a particular control-flow
99 // context (the context instruction provides that context). If an assume and
100 // the context instruction are not in the same block then the DT helps in
101 // figuring out if we can use it.
102 struct Query {
103  const DataLayout &DL;
104  AssumptionCache *AC;
105  const Instruction *CxtI;
106  const DominatorTree *DT;
107 
108  // Unlike the other analyses, this may be a nullptr because not all clients
109  // provide it currently.
111 
112  /// If true, it is safe to use metadata during simplification.
113  InstrInfoQuery IIQ;
114 
115  Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
116  const DominatorTree *DT, bool UseInstrInfo,
117  OptimizationRemarkEmitter *ORE = nullptr)
118  : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
119 };
120 
121 } // end anonymous namespace
122 
123 // Given the provided Value and, potentially, a context instruction, return
124 // the preferred context instruction (if any).
125 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
126  // If we've been provided with a context instruction, then use that (provided
127  // it has been inserted).
128  if (CxtI && CxtI->getParent())
129  return CxtI;
130 
131  // If the value is really an already-inserted instruction, then use that.
132  CxtI = dyn_cast<Instruction>(V);
133  if (CxtI && CxtI->getParent())
134  return CxtI;
135 
136  return nullptr;
137 }
138 
139 static const Instruction *safeCxtI(const Value *V1, const Value *V2, const Instruction *CxtI) {
140  // If we've been provided with a context instruction, then use that (provided
141  // it has been inserted).
142  if (CxtI && CxtI->getParent())
143  return CxtI;
144 
145  // If the value is really an already-inserted instruction, then use that.
146  CxtI = dyn_cast<Instruction>(V1);
147  if (CxtI && CxtI->getParent())
148  return CxtI;
149 
150  CxtI = dyn_cast<Instruction>(V2);
151  if (CxtI && CxtI->getParent())
152  return CxtI;
153 
154  return nullptr;
155 }
156 
158  const APInt &DemandedElts,
159  APInt &DemandedLHS, APInt &DemandedRHS) {
160  // The length of scalable vectors is unknown at compile time, thus we
161  // cannot check their values
162  if (isa<ScalableVectorType>(Shuf->getType()))
163  return false;
164 
165  int NumElts =
166  cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
167  int NumMaskElts = cast<FixedVectorType>(Shuf->getType())->getNumElements();
168  DemandedLHS = DemandedRHS = APInt::getZero(NumElts);
169  if (DemandedElts.isZero())
170  return true;
171  // Simple case of a shuffle with zeroinitializer.
172  if (all_of(Shuf->getShuffleMask(), [](int Elt) { return Elt == 0; })) {
173  DemandedLHS.setBit(0);
174  return true;
175  }
176  for (int i = 0; i != NumMaskElts; ++i) {
177  if (!DemandedElts[i])
178  continue;
179  int M = Shuf->getMaskValue(i);
180  assert(M < (NumElts * 2) && "Invalid shuffle mask constant");
181 
182  // For undef elements, we don't know anything about the common state of
183  // the shuffle result.
184  if (M == -1)
185  return false;
186  if (M < NumElts)
187  DemandedLHS.setBit(M % NumElts);
188  else
189  DemandedRHS.setBit(M % NumElts);
190  }
191 
192  return true;
193 }
194 
195 static void computeKnownBits(const Value *V, const APInt &DemandedElts,
196  KnownBits &Known, unsigned Depth, const Query &Q);
197 
198 static void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
199  const Query &Q) {
200  // FIXME: We currently have no way to represent the DemandedElts of a scalable
201  // vector
202  if (isa<ScalableVectorType>(V->getType())) {
203  Known.resetAll();
204  return;
205  }
206 
207  auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
208  APInt DemandedElts =
209  FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
210  computeKnownBits(V, DemandedElts, Known, Depth, Q);
211 }
212 
213 void llvm::computeKnownBits(const Value *V, KnownBits &Known,
214  const DataLayout &DL, unsigned Depth,
215  AssumptionCache *AC, const Instruction *CxtI,
216  const DominatorTree *DT,
217  OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
218  ::computeKnownBits(V, Known, Depth,
219  Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
220 }
221 
222 void llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
223  KnownBits &Known, const DataLayout &DL,
224  unsigned Depth, AssumptionCache *AC,
225  const Instruction *CxtI, const DominatorTree *DT,
226  OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
227  ::computeKnownBits(V, DemandedElts, Known, Depth,
228  Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
229 }
230 
231 static KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
232  unsigned Depth, const Query &Q);
233 
234 static KnownBits computeKnownBits(const Value *V, unsigned Depth,
235  const Query &Q);
236 
238  unsigned Depth, AssumptionCache *AC,
239  const Instruction *CxtI,
240  const DominatorTree *DT,
242  bool UseInstrInfo) {
244  V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
245 }
246 
247 KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
248  const DataLayout &DL, unsigned Depth,
249  AssumptionCache *AC, const Instruction *CxtI,
250  const DominatorTree *DT,
252  bool UseInstrInfo) {
254  V, DemandedElts, Depth,
255  Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
256 }
257 
258 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
259  const DataLayout &DL, AssumptionCache *AC,
260  const Instruction *CxtI, const DominatorTree *DT,
261  bool UseInstrInfo) {
262  assert(LHS->getType() == RHS->getType() &&
263  "LHS and RHS should have the same type");
264  assert(LHS->getType()->isIntOrIntVectorTy() &&
265  "LHS and RHS should be integers");
266  // Look for an inverted mask: (X & ~M) op (Y & M).
267  Value *M;
268  if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
269  match(RHS, m_c_And(m_Specific(M), m_Value())))
270  return true;
271  if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
272  match(LHS, m_c_And(m_Specific(M), m_Value())))
273  return true;
274  IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
275  KnownBits LHSKnown(IT->getBitWidth());
276  KnownBits RHSKnown(IT->getBitWidth());
277  computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
278  computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
279  return KnownBits::haveNoCommonBitsSet(LHSKnown, RHSKnown);
280 }
281 
283  return !I->user_empty() && all_of(I->users(), [](const User *U) {
284  ICmpInst::Predicate P;
285  return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
286  });
287 }
288 
289 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
290  const Query &Q);
291 
293  bool OrZero, unsigned Depth,
294  AssumptionCache *AC, const Instruction *CxtI,
295  const DominatorTree *DT, bool UseInstrInfo) {
297  V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
298 }
299 
300 static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
301  unsigned Depth, const Query &Q);
302 
303 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
304 
305 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
306  AssumptionCache *AC, const Instruction *CxtI,
307  const DominatorTree *DT, bool UseInstrInfo) {
309  Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
310 }
311 
313  unsigned Depth, AssumptionCache *AC,
314  const Instruction *CxtI, const DominatorTree *DT,
315  bool UseInstrInfo) {
316  KnownBits Known =
317  computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
318  return Known.isNonNegative();
319 }
320 
321 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
322  AssumptionCache *AC, const Instruction *CxtI,
323  const DominatorTree *DT, bool UseInstrInfo) {
324  if (auto *CI = dyn_cast<ConstantInt>(V))
325  return CI->getValue().isStrictlyPositive();
326 
327  // TODO: We'd doing two recursive queries here. We should factor this such
328  // that only a single query is needed.
329  return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
330  isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
331 }
332 
333 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
334  AssumptionCache *AC, const Instruction *CxtI,
335  const DominatorTree *DT, bool UseInstrInfo) {
336  KnownBits Known =
337  computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
338  return Known.isNegative();
339 }
340 
341 static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
342  const Query &Q);
343 
344 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
345  const DataLayout &DL, AssumptionCache *AC,
346  const Instruction *CxtI, const DominatorTree *DT,
347  bool UseInstrInfo) {
349  Query(DL, AC, safeCxtI(V2, V1, CxtI), DT,
350  UseInstrInfo, /*ORE=*/nullptr));
351 }
352 
353 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
354  const Query &Q);
355 
356 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
357  const DataLayout &DL, unsigned Depth,
358  AssumptionCache *AC, const Instruction *CxtI,
359  const DominatorTree *DT, bool UseInstrInfo) {
361  V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
362 }
363 
364 static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
365  unsigned Depth, const Query &Q);
366 
367 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
368  const Query &Q) {
369  // FIXME: We currently have no way to represent the DemandedElts of a scalable
370  // vector
371  if (isa<ScalableVectorType>(V->getType()))
372  return 1;
373 
374  auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
375  APInt DemandedElts =
376  FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
377  return ComputeNumSignBits(V, DemandedElts, Depth, Q);
378 }
379 
380 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
381  unsigned Depth, AssumptionCache *AC,
382  const Instruction *CxtI,
383  const DominatorTree *DT, bool UseInstrInfo) {
385  V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
386 }
387 
388 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
389  bool NSW, const APInt &DemandedElts,
390  KnownBits &KnownOut, KnownBits &Known2,
391  unsigned Depth, const Query &Q) {
392  computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q);
393 
394  // If one operand is unknown and we have no nowrap information,
395  // the result will be unknown independently of the second operand.
396  if (KnownOut.isUnknown() && !NSW)
397  return;
398 
399  computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
400  KnownOut = KnownBits::computeForAddSub(Add, NSW, Known2, KnownOut);
401 }
402 
403 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
404  const APInt &DemandedElts, KnownBits &Known,
405  KnownBits &Known2, unsigned Depth,
406  const Query &Q) {
407  computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q);
408  computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
409 
410  bool isKnownNegative = false;
411  bool isKnownNonNegative = false;
412  // If the multiplication is known not to overflow, compute the sign bit.
413  if (NSW) {
414  if (Op0 == Op1) {
415  // The product of a number with itself is non-negative.
416  isKnownNonNegative = true;
417  } else {
418  bool isKnownNonNegativeOp1 = Known.isNonNegative();
419  bool isKnownNonNegativeOp0 = Known2.isNonNegative();
420  bool isKnownNegativeOp1 = Known.isNegative();
421  bool isKnownNegativeOp0 = Known2.isNegative();
422  // The product of two numbers with the same sign is non-negative.
423  isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
424  (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
425  // The product of a negative number and a non-negative number is either
426  // negative or zero.
427  if (!isKnownNonNegative)
429  (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
430  Known2.isNonZero()) ||
431  (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
432  }
433  }
434 
435  Known = KnownBits::mul(Known, Known2);
436 
437  // Only make use of no-wrap flags if we failed to compute the sign bit
438  // directly. This matters if the multiplication always overflows, in
439  // which case we prefer to follow the result of the direct computation,
440  // though as the program is invoking undefined behaviour we can choose
441  // whatever we like here.
442  if (isKnownNonNegative && !Known.isNegative())
443  Known.makeNonNegative();
444  else if (isKnownNegative && !Known.isNonNegative())
445  Known.makeNegative();
446 }
447 
449  KnownBits &Known) {
450  unsigned BitWidth = Known.getBitWidth();
451  unsigned NumRanges = Ranges.getNumOperands() / 2;
452  assert(NumRanges >= 1);
453 
454  Known.Zero.setAllBits();
455  Known.One.setAllBits();
456 
457  for (unsigned i = 0; i < NumRanges; ++i) {
458  ConstantInt *Lower =
459  mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
460  ConstantInt *Upper =
461  mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
462  ConstantRange Range(Lower->getValue(), Upper->getValue());
463 
464  // The first CommonPrefixBits of all values in Range are equal.
465  unsigned CommonPrefixBits =
466  (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
467  APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
468  APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
469  Known.One &= UnsignedMax & Mask;
470  Known.Zero &= ~UnsignedMax & Mask;
471  }
472 }
473 
474 static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
475  SmallVector<const Value *, 16> WorkSet(1, I);
478 
479  // The instruction defining an assumption's condition itself is always
480  // considered ephemeral to that assumption (even if it has other
481  // non-ephemeral users). See r246696's test case for an example.
482  if (is_contained(I->operands(), E))
483  return true;
484 
485  while (!WorkSet.empty()) {
486  const Value *V = WorkSet.pop_back_val();
487  if (!Visited.insert(V).second)
488  continue;
489 
490  // If all uses of this value are ephemeral, then so is this value.
491  if (llvm::all_of(V->users(), [&](const User *U) {
492  return EphValues.count(U);
493  })) {
494  if (V == E)
495  return true;
496 
497  if (V == I || (isa<Instruction>(V) &&
498  !cast<Instruction>(V)->mayHaveSideEffects() &&
499  !cast<Instruction>(V)->isTerminator())) {
500  EphValues.insert(V);
501  if (const User *U = dyn_cast<User>(V))
502  append_range(WorkSet, U->operands());
503  }
504  }
505  }
506 
507  return false;
508 }
509 
510 // Is this an intrinsic that cannot be speculated but also cannot trap?
512  if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
513  return CI->isAssumeLikeIntrinsic();
514 
515  return false;
516 }
517 
519  const Instruction *CxtI,
520  const DominatorTree *DT) {
521  // There are two restrictions on the use of an assume:
522  // 1. The assume must dominate the context (or the control flow must
523  // reach the assume whenever it reaches the context).
524  // 2. The context must not be in the assume's set of ephemeral values
525  // (otherwise we will use the assume to prove that the condition
526  // feeding the assume is trivially true, thus causing the removal of
527  // the assume).
528 
529  if (Inv->getParent() == CxtI->getParent()) {
530  // If Inv and CtxI are in the same block, check if the assume (Inv) is first
531  // in the BB.
532  if (Inv->comesBefore(CxtI))
533  return true;
534 
535  // Don't let an assume affect itself - this would cause the problems
536  // `isEphemeralValueOf` is trying to prevent, and it would also make
537  // the loop below go out of bounds.
538  if (Inv == CxtI)
539  return false;
540 
541  // The context comes first, but they're both in the same block.
542  // Make sure there is nothing in between that might interrupt
543  // the control flow, not even CxtI itself.
544  // We limit the scan distance between the assume and its context instruction
545  // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
546  // it can be adjusted if needed (could be turned into a cl::opt).
547  auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
549  return false;
550 
551  return !isEphemeralValueOf(Inv, CxtI);
552  }
553 
554  // Inv and CxtI are in different blocks.
555  if (DT) {
556  if (DT->dominates(Inv, CxtI))
557  return true;
558  } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
559  // We don't have a DT, but this trivially dominates.
560  return true;
561  }
562 
563  return false;
564 }
565 
566 static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
567  // v u> y implies v != 0.
568  if (Pred == ICmpInst::ICMP_UGT)
569  return true;
570 
571  // Special-case v != 0 to also handle v != null.
572  if (Pred == ICmpInst::ICMP_NE)
573  return match(RHS, m_Zero());
574 
575  // All other predicates - rely on generic ConstantRange handling.
576  const APInt *C;
577  if (!match(RHS, m_APInt(C)))
578  return false;
579 
581  return !TrueValues.contains(APInt::getZero(C->getBitWidth()));
582 }
583 
584 static bool isKnownNonZeroFromAssume(const Value *V, const Query &Q) {
585  // Use of assumptions is context-sensitive. If we don't have a context, we
586  // cannot use them!
587  if (!Q.AC || !Q.CxtI)
588  return false;
589 
590  if (Q.CxtI && V->getType()->isPointerTy()) {
591  SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NonNull};
592  if (!NullPointerIsDefined(Q.CxtI->getFunction(),
594  AttrKinds.push_back(Attribute::Dereferenceable);
595 
596  if (getKnowledgeValidInContext(V, AttrKinds, Q.CxtI, Q.DT, Q.AC))
597  return true;
598  }
599 
600  for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
601  if (!AssumeVH)
602  continue;
603  CallInst *I = cast<CallInst>(AssumeVH);
604  assert(I->getFunction() == Q.CxtI->getFunction() &&
605  "Got assumption for the wrong function!");
606 
607  // Warning: This loop can end up being somewhat performance sensitive.
608  // We're running this loop for once for each value queried resulting in a
609  // runtime of ~O(#assumes * #values).
610 
611  assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
612  "must be an assume intrinsic");
613 
614  Value *RHS;
615  CmpInst::Predicate Pred;
616  auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
617  if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
618  return false;
619 
620  if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT))
621  return true;
622  }
623 
624  return false;
625 }
626 
627 static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
628  unsigned Depth, const Query &Q) {
629  // Use of assumptions is context-sensitive. If we don't have a context, we
630  // cannot use them!
631  if (!Q.AC || !Q.CxtI)
632  return;
633 
634  unsigned BitWidth = Known.getBitWidth();
635 
636  // Refine Known set if the pointer alignment is set by assume bundles.
637  if (V->getType()->isPointerTy()) {
639  V, {Attribute::Alignment}, Q.CxtI, Q.DT, Q.AC)) {
640  Known.Zero.setLowBits(Log2_64(RK.ArgValue));
641  }
642  }
643 
644  // Note that the patterns below need to be kept in sync with the code
645  // in AssumptionCache::updateAffectedValues.
646 
647  for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
648  if (!AssumeVH)
649  continue;
650  CallInst *I = cast<CallInst>(AssumeVH);
651  assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
652  "Got assumption for the wrong function!");
653 
654  // Warning: This loop can end up being somewhat performance sensitive.
655  // We're running this loop for once for each value queried resulting in a
656  // runtime of ~O(#assumes * #values).
657 
658  assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
659  "must be an assume intrinsic");
660 
661  Value *Arg = I->getArgOperand(0);
662 
663  if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
664  assert(BitWidth == 1 && "assume operand is not i1?");
665  Known.setAllOnes();
666  return;
667  }
668  if (match(Arg, m_Not(m_Specific(V))) &&
669  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
670  assert(BitWidth == 1 && "assume operand is not i1?");
671  Known.setAllZero();
672  return;
673  }
674 
675  // The remaining tests are all recursive, so bail out if we hit the limit.
677  continue;
678 
679  ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
680  if (!Cmp)
681  continue;
682 
683  // We are attempting to compute known bits for the operands of an assume.
684  // Do not try to use other assumptions for those recursive calls because
685  // that can lead to mutual recursion and a compile-time explosion.
686  // An example of the mutual recursion: computeKnownBits can call
687  // isKnownNonZero which calls computeKnownBitsFromAssume (this function)
688  // and so on.
689  Query QueryNoAC = Q;
690  QueryNoAC.AC = nullptr;
691 
692  // Note that ptrtoint may change the bitwidth.
693  Value *A, *B;
694  auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
695 
696  CmpInst::Predicate Pred;
697  uint64_t C;
698  switch (Cmp->getPredicate()) {
699  default:
700  break;
701  case ICmpInst::ICMP_EQ:
702  // assume(v = a)
703  if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
704  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
705  KnownBits RHSKnown =
706  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
707  Known.Zero |= RHSKnown.Zero;
708  Known.One |= RHSKnown.One;
709  // assume(v & b = a)
710  } else if (match(Cmp,
711  m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
712  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
713  KnownBits RHSKnown =
714  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
715  KnownBits MaskKnown =
716  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
717 
718  // For those bits in the mask that are known to be one, we can propagate
719  // known bits from the RHS to V.
720  Known.Zero |= RHSKnown.Zero & MaskKnown.One;
721  Known.One |= RHSKnown.One & MaskKnown.One;
722  // assume(~(v & b) = a)
723  } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
724  m_Value(A))) &&
725  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
726  KnownBits RHSKnown =
727  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
728  KnownBits MaskKnown =
729  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
730 
731  // For those bits in the mask that are known to be one, we can propagate
732  // inverted known bits from the RHS to V.
733  Known.Zero |= RHSKnown.One & MaskKnown.One;
734  Known.One |= RHSKnown.Zero & MaskKnown.One;
735  // assume(v | b = a)
736  } else if (match(Cmp,
737  m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
738  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
739  KnownBits RHSKnown =
740  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
741  KnownBits BKnown =
742  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
743 
744  // For those bits in B that are known to be zero, we can propagate known
745  // bits from the RHS to V.
746  Known.Zero |= RHSKnown.Zero & BKnown.Zero;
747  Known.One |= RHSKnown.One & BKnown.Zero;
748  // assume(~(v | b) = a)
749  } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
750  m_Value(A))) &&
751  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
752  KnownBits RHSKnown =
753  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
754  KnownBits BKnown =
755  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
756 
757  // For those bits in B that are known to be zero, we can propagate
758  // inverted known bits from the RHS to V.
759  Known.Zero |= RHSKnown.One & BKnown.Zero;
760  Known.One |= RHSKnown.Zero & BKnown.Zero;
761  // assume(v ^ b = a)
762  } else if (match(Cmp,
763  m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
764  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
765  KnownBits RHSKnown =
766  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
767  KnownBits BKnown =
768  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
769 
770  // For those bits in B that are known to be zero, we can propagate known
771  // bits from the RHS to V. For those bits in B that are known to be one,
772  // we can propagate inverted known bits from the RHS to V.
773  Known.Zero |= RHSKnown.Zero & BKnown.Zero;
774  Known.One |= RHSKnown.One & BKnown.Zero;
775  Known.Zero |= RHSKnown.One & BKnown.One;
776  Known.One |= RHSKnown.Zero & BKnown.One;
777  // assume(~(v ^ b) = a)
778  } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
779  m_Value(A))) &&
780  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
781  KnownBits RHSKnown =
782  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
783  KnownBits BKnown =
784  computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
785 
786  // For those bits in B that are known to be zero, we can propagate
787  // inverted known bits from the RHS to V. For those bits in B that are
788  // known to be one, we can propagate known bits from the RHS to V.
789  Known.Zero |= RHSKnown.One & BKnown.Zero;
790  Known.One |= RHSKnown.Zero & BKnown.Zero;
791  Known.Zero |= RHSKnown.Zero & BKnown.One;
792  Known.One |= RHSKnown.One & BKnown.One;
793  // assume(v << c = a)
794  } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
795  m_Value(A))) &&
796  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
797  KnownBits RHSKnown =
798  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
799 
800  // For those bits in RHS that are known, we can propagate them to known
801  // bits in V shifted to the right by C.
802  RHSKnown.Zero.lshrInPlace(C);
803  Known.Zero |= RHSKnown.Zero;
804  RHSKnown.One.lshrInPlace(C);
805  Known.One |= RHSKnown.One;
806  // assume(~(v << c) = a)
807  } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
808  m_Value(A))) &&
809  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
810  KnownBits RHSKnown =
811  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
812  // For those bits in RHS that are known, we can propagate them inverted
813  // to known bits in V shifted to the right by C.
814  RHSKnown.One.lshrInPlace(C);
815  Known.Zero |= RHSKnown.One;
816  RHSKnown.Zero.lshrInPlace(C);
817  Known.One |= RHSKnown.Zero;
818  // assume(v >> c = a)
819  } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
820  m_Value(A))) &&
821  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
822  KnownBits RHSKnown =
823  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
824  // For those bits in RHS that are known, we can propagate them to known
825  // bits in V shifted to the right by C.
826  Known.Zero |= RHSKnown.Zero << C;
827  Known.One |= RHSKnown.One << C;
828  // assume(~(v >> c) = a)
829  } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
830  m_Value(A))) &&
831  isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
832  KnownBits RHSKnown =
833  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
834  // For those bits in RHS that are known, we can propagate them inverted
835  // to known bits in V shifted to the right by C.
836  Known.Zero |= RHSKnown.One << C;
837  Known.One |= RHSKnown.Zero << C;
838  }
839  break;
840  case ICmpInst::ICMP_SGE:
841  // assume(v >=_s c) where c is non-negative
842  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
843  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
844  KnownBits RHSKnown =
845  computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
846 
847  if (RHSKnown.isNonNegative()) {
848  // We know that the sign bit is zero.
849  Known.makeNonNegative();
850  }
851  }
852  break;
853  case ICmpInst::ICMP_SGT:
854  // assume(v >_s c) where c is at least -1.
855  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
856  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
857  KnownBits RHSKnown =
858  computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
859 
860  if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
861  // We know that the sign bit is zero.
862  Known.makeNonNegative();
863  }
864  }
865  break;
866  case ICmpInst::ICMP_SLE:
867  // assume(v <=_s c) where c is negative
868  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
869  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
870  KnownBits RHSKnown =
871  computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
872 
873  if (RHSKnown.isNegative()) {
874  // We know that the sign bit is one.
875  Known.makeNegative();
876  }
877  }
878  break;
879  case ICmpInst::ICMP_SLT:
880  // assume(v <_s c) where c is non-positive
881  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
882  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
883  KnownBits RHSKnown =
884  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
885 
886  if (RHSKnown.isZero() || RHSKnown.isNegative()) {
887  // We know that the sign bit is one.
888  Known.makeNegative();
889  }
890  }
891  break;
892  case ICmpInst::ICMP_ULE:
893  // assume(v <=_u c)
894  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
895  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
896  KnownBits RHSKnown =
897  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
898 
899  // Whatever high bits in c are zero are known to be zero.
900  Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
901  }
902  break;
903  case ICmpInst::ICMP_ULT:
904  // assume(v <_u c)
905  if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
906  isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
907  KnownBits RHSKnown =
908  computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
909 
910  // If the RHS is known zero, then this assumption must be wrong (nothing
911  // is unsigned less than zero). Signal a conflict and get out of here.
912  if (RHSKnown.isZero()) {
913  Known.Zero.setAllBits();
914  Known.One.setAllBits();
915  break;
916  }
917 
918  // Whatever high bits in c are zero are known to be zero (if c is a power
919  // of 2, then one more).
920  if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, QueryNoAC))
921  Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
922  else
923  Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
924  }
925  break;
926  }
927  }
928 
929  // If assumptions conflict with each other or previous known bits, then we
930  // have a logical fallacy. It's possible that the assumption is not reachable,
931  // so this isn't a real bug. On the other hand, the program may have undefined
932  // behavior, or we might have a bug in the compiler. We can't assert/crash, so
933  // clear out the known bits, try to warn the user, and hope for the best.
934  if (Known.Zero.intersects(Known.One)) {
935  Known.resetAll();
936 
937  if (Q.ORE)
938  Q.ORE->emit([&]() {
939  auto *CxtI = const_cast<Instruction *>(Q.CxtI);
940  return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
941  CxtI)
942  << "Detected conflicting code assumptions. Program may "
943  "have undefined behavior, or compiler may have "
944  "internal error.";
945  });
946  }
947 }
948 
949 /// Compute known bits from a shift operator, including those with a
950 /// non-constant shift amount. Known is the output of this function. Known2 is a
951 /// pre-allocated temporary with the same bit width as Known and on return
952 /// contains the known bit of the shift value source. KF is an
953 /// operator-specific function that, given the known-bits and a shift amount,
954 /// compute the implied known-bits of the shift operator's result respectively
955 /// for that shift amount. The results from calling KF are conservatively
956 /// combined for all permitted shift amounts.
958  const Operator *I, const APInt &DemandedElts, KnownBits &Known,
959  KnownBits &Known2, unsigned Depth, const Query &Q,
960  function_ref<KnownBits(const KnownBits &, const KnownBits &)> KF) {
961  unsigned BitWidth = Known.getBitWidth();
962  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
963  computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
964 
965  // Note: We cannot use Known.Zero.getLimitedValue() here, because if
966  // BitWidth > 64 and any upper bits are known, we'll end up returning the
967  // limit value (which implies all bits are known).
968  uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
969  uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
970  bool ShiftAmtIsConstant = Known.isConstant();
971  bool MaxShiftAmtIsOutOfRange = Known.getMaxValue().uge(BitWidth);
972 
973  if (ShiftAmtIsConstant) {
974  Known = KF(Known2, Known);
975 
976  // If the known bits conflict, this must be an overflowing left shift, so
977  // the shift result is poison. We can return anything we want. Choose 0 for
978  // the best folding opportunity.
979  if (Known.hasConflict())
980  Known.setAllZero();
981 
982  return;
983  }
984 
985  // If the shift amount could be greater than or equal to the bit-width of the
986  // LHS, the value could be poison, but bail out because the check below is
987  // expensive.
988  // TODO: Should we just carry on?
989  if (MaxShiftAmtIsOutOfRange) {
990  Known.resetAll();
991  return;
992  }
993 
994  // It would be more-clearly correct to use the two temporaries for this
995  // calculation. Reusing the APInts here to prevent unnecessary allocations.
996  Known.resetAll();
997 
998  // If we know the shifter operand is nonzero, we can sometimes infer more
999  // known bits. However this is expensive to compute, so be lazy about it and
1000  // only compute it when absolutely necessary.
1001  Optional<bool> ShifterOperandIsNonZero;
1002 
1003  // Early exit if we can't constrain any well-defined shift amount.
1004  if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
1005  !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
1006  ShifterOperandIsNonZero =
1007  isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
1008  if (!*ShifterOperandIsNonZero)
1009  return;
1010  }
1011 
1012  Known.Zero.setAllBits();
1013  Known.One.setAllBits();
1014  for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
1015  // Combine the shifted known input bits only for those shift amounts
1016  // compatible with its known constraints.
1017  if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
1018  continue;
1019  if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
1020  continue;
1021  // If we know the shifter is nonzero, we may be able to infer more known
1022  // bits. This check is sunk down as far as possible to avoid the expensive
1023  // call to isKnownNonZero if the cheaper checks above fail.
1024  if (ShiftAmt == 0) {
1025  if (!ShifterOperandIsNonZero.hasValue())
1026  ShifterOperandIsNonZero =
1027  isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
1028  if (*ShifterOperandIsNonZero)
1029  continue;
1030  }
1031 
1032  Known = KnownBits::commonBits(
1033  Known, KF(Known2, KnownBits::makeConstant(APInt(32, ShiftAmt))));
1034  }
1035 
1036  // If the known bits conflict, the result is poison. Return a 0 and hope the
1037  // caller can further optimize that.
1038  if (Known.hasConflict())
1039  Known.setAllZero();
1040 }
1041 
1043  const APInt &DemandedElts,
1044  KnownBits &Known, unsigned Depth,
1045  const Query &Q) {
1046  unsigned BitWidth = Known.getBitWidth();
1047 
1048  KnownBits Known2(BitWidth);
1049  switch (I->getOpcode()) {
1050  default: break;
1051  case Instruction::Load:
1052  if (MDNode *MD =
1053  Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1055  break;
1056  case Instruction::And: {
1057  // If either the LHS or the RHS are Zero, the result is zero.
1058  computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1059  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1060 
1061  Known &= Known2;
1062 
1063  // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1064  // here we handle the more general case of adding any odd number by
1065  // matching the form add(x, add(x, y)) where y is odd.
1066  // TODO: This could be generalized to clearing any bit set in y where the
1067  // following bit is known to be unset in y.
1068  Value *X = nullptr, *Y = nullptr;
1069  if (!Known.Zero[0] && !Known.One[0] &&
1071  Known2.resetAll();
1072  computeKnownBits(Y, DemandedElts, Known2, Depth + 1, Q);
1073  if (Known2.countMinTrailingOnes() > 0)
1074  Known.Zero.setBit(0);
1075  }
1076  break;
1077  }
1078  case Instruction::Or:
1079  computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1080  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1081 
1082  Known |= Known2;
1083  break;
1084  case Instruction::Xor:
1085  computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1086  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1087 
1088  Known ^= Known2;
1089  break;
1090  case Instruction::Mul: {
1091  bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1092  computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, DemandedElts,
1093  Known, Known2, Depth, Q);
1094  break;
1095  }
1096  case Instruction::UDiv: {
1097  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1098  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1099  Known = KnownBits::udiv(Known, Known2);
1100  break;
1101  }
1102  case Instruction::Select: {
1103  const Value *LHS = nullptr, *RHS = nullptr;
1106  computeKnownBits(RHS, Known, Depth + 1, Q);
1107  computeKnownBits(LHS, Known2, Depth + 1, Q);
1108  switch (SPF) {
1109  default:
1110  llvm_unreachable("Unhandled select pattern flavor!");
1111  case SPF_SMAX:
1112  Known = KnownBits::smax(Known, Known2);
1113  break;
1114  case SPF_SMIN:
1115  Known = KnownBits::smin(Known, Known2);
1116  break;
1117  case SPF_UMAX:
1118  Known = KnownBits::umax(Known, Known2);
1119  break;
1120  case SPF_UMIN:
1121  Known = KnownBits::umin(Known, Known2);
1122  break;
1123  }
1124  break;
1125  }
1126 
1127  computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1128  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1129 
1130  // Only known if known in both the LHS and RHS.
1131  Known = KnownBits::commonBits(Known, Known2);
1132 
1133  if (SPF == SPF_ABS) {
1134  // RHS from matchSelectPattern returns the negation part of abs pattern.
1135  // If the negate has an NSW flag we can assume the sign bit of the result
1136  // will be 0 because that makes abs(INT_MIN) undefined.
1137  if (match(RHS, m_Neg(m_Specific(LHS))) &&
1138  Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
1139  Known.Zero.setSignBit();
1140  }
1141 
1142  break;
1143  }
1144  case Instruction::FPTrunc:
1145  case Instruction::FPExt:
1146  case Instruction::FPToUI:
1147  case Instruction::FPToSI:
1148  case Instruction::SIToFP:
1149  case Instruction::UIToFP:
1150  break; // Can't work with floating point.
1151  case Instruction::PtrToInt:
1152  case Instruction::IntToPtr:
1153  // Fall through and handle them the same as zext/trunc.
1155  case Instruction::ZExt:
1156  case Instruction::Trunc: {
1157  Type *SrcTy = I->getOperand(0)->getType();
1158 
1159  unsigned SrcBitWidth;
1160  // Note that we handle pointer operands here because of inttoptr/ptrtoint
1161  // which fall through here.
1162  Type *ScalarTy = SrcTy->getScalarType();
1163  SrcBitWidth = ScalarTy->isPointerTy() ?
1164  Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1165  Q.DL.getTypeSizeInBits(ScalarTy);
1166 
1167  assert(SrcBitWidth && "SrcBitWidth can't be zero");
1168  Known = Known.anyextOrTrunc(SrcBitWidth);
1169  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1170  Known = Known.zextOrTrunc(BitWidth);
1171  break;
1172  }
1173  case Instruction::BitCast: {
1174  Type *SrcTy = I->getOperand(0)->getType();
1175  if (SrcTy->isIntOrPtrTy() &&
1176  // TODO: For now, not handling conversions like:
1177  // (bitcast i64 %x to <2 x i32>)
1178  !I->getType()->isVectorTy()) {
1179  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1180  break;
1181  }
1182 
1183  // Handle cast from vector integer type to scalar or vector integer.
1184  auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1185  if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1186  !I->getType()->isIntOrIntVectorTy())
1187  break;
1188 
1189  // Look through a cast from narrow vector elements to wider type.
1190  // Examples: v4i32 -> v2i64, v3i8 -> v24
1191  unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1192  if (BitWidth % SubBitWidth == 0) {
1193  // Known bits are automatically intersected across demanded elements of a
1194  // vector. So for example, if a bit is computed as known zero, it must be
1195  // zero across all demanded elements of the vector.
1196  //
1197  // For this bitcast, each demanded element of the output is sub-divided
1198  // across a set of smaller vector elements in the source vector. To get
1199  // the known bits for an entire element of the output, compute the known
1200  // bits for each sub-element sequentially. This is done by shifting the
1201  // one-set-bit demanded elements parameter across the sub-elements for
1202  // consecutive calls to computeKnownBits. We are using the demanded
1203  // elements parameter as a mask operator.
1204  //
1205  // The known bits of each sub-element are then inserted into place
1206  // (dependent on endian) to form the full result of known bits.
1207  unsigned NumElts = DemandedElts.getBitWidth();
1208  unsigned SubScale = BitWidth / SubBitWidth;
1209  APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1210  for (unsigned i = 0; i != NumElts; ++i) {
1211  if (DemandedElts[i])
1212  SubDemandedElts.setBit(i * SubScale);
1213  }
1214 
1215  KnownBits KnownSrc(SubBitWidth);
1216  for (unsigned i = 0; i != SubScale; ++i) {
1217  computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc,
1218  Depth + 1, Q);
1219  unsigned ShiftElt = Q.DL.isLittleEndian() ? i : SubScale - 1 - i;
1220  Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1221  }
1222  }
1223  break;
1224  }
1225  case Instruction::SExt: {
1226  // Compute the bits in the result that are not present in the input.
1227  unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1228 
1229  Known = Known.trunc(SrcBitWidth);
1230  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1231  // If the sign bit of the input is known set or clear, then we know the
1232  // top bits of the result.
1233  Known = Known.sext(BitWidth);
1234  break;
1235  }
1236  case Instruction::Shl: {
1237  bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1238  auto KF = [NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1239  KnownBits Result = KnownBits::shl(KnownVal, KnownAmt);
1240  // If this shift has "nsw" keyword, then the result is either a poison
1241  // value or has the same sign bit as the first operand.
1242  if (NSW) {
1243  if (KnownVal.Zero.isSignBitSet())
1244  Result.Zero.setSignBit();
1245  if (KnownVal.One.isSignBitSet())
1246  Result.One.setSignBit();
1247  }
1248  return Result;
1249  };
1250  computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1251  KF);
1252  // Trailing zeros of a right-shifted constant never decrease.
1253  const APInt *C;
1254  if (match(I->getOperand(0), m_APInt(C)))
1255  Known.Zero.setLowBits(C->countTrailingZeros());
1256  break;
1257  }
1258  case Instruction::LShr: {
1259  auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1260  return KnownBits::lshr(KnownVal, KnownAmt);
1261  };
1262  computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1263  KF);
1264  // Leading zeros of a left-shifted constant never decrease.
1265  const APInt *C;
1266  if (match(I->getOperand(0), m_APInt(C)))
1267  Known.Zero.setHighBits(C->countLeadingZeros());
1268  break;
1269  }
1270  case Instruction::AShr: {
1271  auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1272  return KnownBits::ashr(KnownVal, KnownAmt);
1273  };
1274  computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1275  KF);
1276  break;
1277  }
1278  case Instruction::Sub: {
1279  bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1280  computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1281  DemandedElts, Known, Known2, Depth, Q);
1282  break;
1283  }
1284  case Instruction::Add: {
1285  bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1286  computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1287  DemandedElts, Known, Known2, Depth, Q);
1288  break;
1289  }
1290  case Instruction::SRem:
1291  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1292  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1293  Known = KnownBits::srem(Known, Known2);
1294  break;
1295 
1296  case Instruction::URem:
1297  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1298  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1299  Known = KnownBits::urem(Known, Known2);
1300  break;
1301  case Instruction::Alloca:
1302  Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1303  break;
1304  case Instruction::GetElementPtr: {
1305  // Analyze all of the subscripts of this getelementptr instruction
1306  // to determine if we can prove known low zero bits.
1307  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1308  // Accumulate the constant indices in a separate variable
1309  // to minimize the number of calls to computeForAddSub.
1310  APInt AccConstIndices(BitWidth, 0, /*IsSigned*/ true);
1311 
1313  for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1314  // TrailZ can only become smaller, short-circuit if we hit zero.
1315  if (Known.isUnknown())
1316  break;
1317 
1318  Value *Index = I->getOperand(i);
1319 
1320  // Handle case when index is zero.
1321  Constant *CIndex = dyn_cast<Constant>(Index);
1322  if (CIndex && CIndex->isZeroValue())
1323  continue;
1324 
1325  if (StructType *STy = GTI.getStructTypeOrNull()) {
1326  // Handle struct member offset arithmetic.
1327 
1328  assert(CIndex &&
1329  "Access to structure field must be known at compile time");
1330 
1331  if (CIndex->getType()->isVectorTy())
1332  Index = CIndex->getSplatValue();
1333 
1334  unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1335  const StructLayout *SL = Q.DL.getStructLayout(STy);
1336  uint64_t Offset = SL->getElementOffset(Idx);
1337  AccConstIndices += Offset;
1338  continue;
1339  }
1340 
1341  // Handle array index arithmetic.
1342  Type *IndexedTy = GTI.getIndexedType();
1343  if (!IndexedTy->isSized()) {
1344  Known.resetAll();
1345  break;
1346  }
1347 
1348  unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits();
1349  KnownBits IndexBits(IndexBitWidth);
1350  computeKnownBits(Index, IndexBits, Depth + 1, Q);
1351  TypeSize IndexTypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1352  uint64_t TypeSizeInBytes = IndexTypeSize.getKnownMinSize();
1353  KnownBits ScalingFactor(IndexBitWidth);
1354  // Multiply by current sizeof type.
1355  // &A[i] == A + i * sizeof(*A[i]).
1356  if (IndexTypeSize.isScalable()) {
1357  // For scalable types the only thing we know about sizeof is
1358  // that this is a multiple of the minimum size.
1359  ScalingFactor.Zero.setLowBits(countTrailingZeros(TypeSizeInBytes));
1360  } else if (IndexBits.isConstant()) {
1361  APInt IndexConst = IndexBits.getConstant();
1362  APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes);
1363  IndexConst *= ScalingFactor;
1364  AccConstIndices += IndexConst.sextOrTrunc(BitWidth);
1365  continue;
1366  } else {
1367  ScalingFactor =
1368  KnownBits::makeConstant(APInt(IndexBitWidth, TypeSizeInBytes));
1369  }
1370  IndexBits = KnownBits::mul(IndexBits, ScalingFactor);
1371 
1372  // If the offsets have a different width from the pointer, according
1373  // to the language reference we need to sign-extend or truncate them
1374  // to the width of the pointer.
1375  IndexBits = IndexBits.sextOrTrunc(BitWidth);
1376 
1377  // Note that inbounds does *not* guarantee nsw for the addition, as only
1378  // the offset is signed, while the base address is unsigned.
1380  /*Add=*/true, /*NSW=*/false, Known, IndexBits);
1381  }
1382  if (!Known.isUnknown() && !AccConstIndices.isZero()) {
1383  KnownBits Index = KnownBits::makeConstant(AccConstIndices);
1385  /*Add=*/true, /*NSW=*/false, Known, Index);
1386  }
1387  break;
1388  }
1389  case Instruction::PHI: {
1390  const PHINode *P = cast<PHINode>(I);
1391  BinaryOperator *BO = nullptr;
1392  Value *R = nullptr, *L = nullptr;
1393  if (matchSimpleRecurrence(P, BO, R, L)) {
1394  // Handle the case of a simple two-predecessor recurrence PHI.
1395  // There's a lot more that could theoretically be done here, but
1396  // this is sufficient to catch some interesting cases.
1397  unsigned Opcode = BO->getOpcode();
1398 
1399  // If this is a shift recurrence, we know the bits being shifted in.
1400  // We can combine that with information about the start value of the
1401  // recurrence to conclude facts about the result.
1402  if ((Opcode == Instruction::LShr || Opcode == Instruction::AShr ||
1403  Opcode == Instruction::Shl) &&
1404  BO->getOperand(0) == I) {
1405 
1406  // We have matched a recurrence of the form:
1407  // %iv = [R, %entry], [%iv.next, %backedge]
1408  // %iv.next = shift_op %iv, L
1409 
1410  // Recurse with the phi context to avoid concern about whether facts
1411  // inferred hold at original context instruction. TODO: It may be
1412  // correct to use the original context. IF warranted, explore and
1413  // add sufficient tests to cover.
1414  Query RecQ = Q;
1415  RecQ.CxtI = P;
1416  computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ);
1417  switch (Opcode) {
1418  case Instruction::Shl:
1419  // A shl recurrence will only increase the tailing zeros
1420  Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1421  break;
1422  case Instruction::LShr:
1423  // A lshr recurrence will preserve the leading zeros of the
1424  // start value
1425  Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1426  break;
1427  case Instruction::AShr:
1428  // An ashr recurrence will extend the initial sign bit
1429  Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1430  Known.One.setHighBits(Known2.countMinLeadingOnes());
1431  break;
1432  };
1433  }
1434 
1435  // Check for operations that have the property that if
1436  // both their operands have low zero bits, the result
1437  // will have low zero bits.
1438  if (Opcode == Instruction::Add ||
1439  Opcode == Instruction::Sub ||
1440  Opcode == Instruction::And ||
1441  Opcode == Instruction::Or ||
1442  Opcode == Instruction::Mul) {
1443  // Change the context instruction to the "edge" that flows into the
1444  // phi. This is important because that is where the value is actually
1445  // "evaluated" even though it is used later somewhere else. (see also
1446  // D69571).
1447  Query RecQ = Q;
1448 
1449  unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1450  Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1451  Instruction *LInst = P->getIncomingBlock(1-OpNum)->getTerminator();
1452 
1453  // Ok, we have a PHI of the form L op= R. Check for low
1454  // zero bits.
1455  RecQ.CxtI = RInst;
1456  computeKnownBits(R, Known2, Depth + 1, RecQ);
1457 
1458  // We need to take the minimum number of known bits
1459  KnownBits Known3(BitWidth);
1460  RecQ.CxtI = LInst;
1461  computeKnownBits(L, Known3, Depth + 1, RecQ);
1462 
1464  Known3.countMinTrailingZeros()));
1465 
1466  auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1467  if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
1468  // If initial value of recurrence is nonnegative, and we are adding
1469  // a nonnegative number with nsw, the result can only be nonnegative
1470  // or poison value regardless of the number of times we execute the
1471  // add in phi recurrence. If initial value is negative and we are
1472  // adding a negative number with nsw, the result can only be
1473  // negative or poison value. Similar arguments apply to sub and mul.
1474  //
1475  // (add non-negative, non-negative) --> non-negative
1476  // (add negative, negative) --> negative
1477  if (Opcode == Instruction::Add) {
1478  if (Known2.isNonNegative() && Known3.isNonNegative())
1479  Known.makeNonNegative();
1480  else if (Known2.isNegative() && Known3.isNegative())
1481  Known.makeNegative();
1482  }
1483 
1484  // (sub nsw non-negative, negative) --> non-negative
1485  // (sub nsw negative, non-negative) --> negative
1486  else if (Opcode == Instruction::Sub && BO->getOperand(0) == I) {
1487  if (Known2.isNonNegative() && Known3.isNegative())
1488  Known.makeNonNegative();
1489  else if (Known2.isNegative() && Known3.isNonNegative())
1490  Known.makeNegative();
1491  }
1492 
1493  // (mul nsw non-negative, non-negative) --> non-negative
1494  else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1495  Known3.isNonNegative())
1496  Known.makeNonNegative();
1497  }
1498 
1499  break;
1500  }
1501  }
1502 
1503  // Unreachable blocks may have zero-operand PHI nodes.
1504  if (P->getNumIncomingValues() == 0)
1505  break;
1506 
1507  // Otherwise take the unions of the known bit sets of the operands,
1508  // taking conservative care to avoid excessive recursion.
1509  if (Depth < MaxAnalysisRecursionDepth - 1 && !Known.Zero && !Known.One) {
1510  // Skip if every incoming value references to ourself.
1511  if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1512  break;
1513 
1514  Known.Zero.setAllBits();
1515  Known.One.setAllBits();
1516  for (unsigned u = 0, e = P->getNumIncomingValues(); u < e; ++u) {
1517  Value *IncValue = P->getIncomingValue(u);
1518  // Skip direct self references.
1519  if (IncValue == P) continue;
1520 
1521  // Change the context instruction to the "edge" that flows into the
1522  // phi. This is important because that is where the value is actually
1523  // "evaluated" even though it is used later somewhere else. (see also
1524  // D69571).
1525  Query RecQ = Q;
1526  RecQ.CxtI = P->getIncomingBlock(u)->getTerminator();
1527 
1528  Known2 = KnownBits(BitWidth);
1529  // Recurse, but cap the recursion to one level, because we don't
1530  // want to waste time spinning around in loops.
1531  computeKnownBits(IncValue, Known2, MaxAnalysisRecursionDepth - 1, RecQ);
1532  Known = KnownBits::commonBits(Known, Known2);
1533  // If all bits have been ruled out, there's no need to check
1534  // more operands.
1535  if (Known.isUnknown())
1536  break;
1537  }
1538  }
1539  break;
1540  }
1541  case Instruction::Call:
1542  case Instruction::Invoke:
1543  // If range metadata is attached to this call, set known bits from that,
1544  // and then intersect with known bits based on other properties of the
1545  // function.
1546  if (MDNode *MD =
1547  Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
1549  if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) {
1550  computeKnownBits(RV, Known2, Depth + 1, Q);
1551  Known.Zero |= Known2.Zero;
1552  Known.One |= Known2.One;
1553  }
1554  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1555  switch (II->getIntrinsicID()) {
1556  default: break;
1557  case Intrinsic::abs: {
1558  computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1559  bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
1560  Known = Known2.abs(IntMinIsPoison);
1561  break;
1562  }
1563  case Intrinsic::bitreverse:
1564  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1565  Known.Zero |= Known2.Zero.reverseBits();
1566  Known.One |= Known2.One.reverseBits();
1567  break;
1568  case Intrinsic::bswap:
1569  computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1570  Known.Zero |= Known2.Zero.byteSwap();
1571  Known.One |= Known2.One.byteSwap();
1572  break;
1573  case Intrinsic::ctlz: {
1574  computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1575  // If we have a known 1, its position is our upper bound.
1576  unsigned PossibleLZ = Known2.countMaxLeadingZeros();
1577  // If this call is undefined for 0, the result will be less than 2^n.
1578  if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1579  PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1580  unsigned LowBits = Log2_32(PossibleLZ)+1;
1581  Known.Zero.setBitsFrom(LowBits);
1582  break;
1583  }
1584  case Intrinsic::cttz: {
1585  computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1586  // If we have a known 1, its position is our upper bound.
1587  unsigned PossibleTZ = Known2.countMaxTrailingZeros();
1588  // If this call is undefined for 0, the result will be less than 2^n.
1589  if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1590  PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1591  unsigned LowBits = Log2_32(PossibleTZ)+1;
1592  Known.Zero.setBitsFrom(LowBits);
1593  break;
1594  }
1595  case Intrinsic::ctpop: {
1596  computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1597  // We can bound the space the count needs. Also, bits known to be zero
1598  // can't contribute to the population.
1599  unsigned BitsPossiblySet = Known2.countMaxPopulation();
1600  unsigned LowBits = Log2_32(BitsPossiblySet)+1;
1601  Known.Zero.setBitsFrom(LowBits);
1602  // TODO: we could bound KnownOne using the lower bound on the number
1603  // of bits which might be set provided by popcnt KnownOne2.
1604  break;
1605  }
1606  case Intrinsic::fshr:
1607  case Intrinsic::fshl: {
1608  const APInt *SA;
1609  if (!match(I->getOperand(2), m_APInt(SA)))
1610  break;
1611 
1612  // Normalize to funnel shift left.
1613  uint64_t ShiftAmt = SA->urem(BitWidth);
1614  if (II->getIntrinsicID() == Intrinsic::fshr)
1615  ShiftAmt = BitWidth - ShiftAmt;
1616 
1617  KnownBits Known3(BitWidth);
1618  computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1619  computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1620 
1621  Known.Zero =
1622  Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1623  Known.One =
1624  Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1625  break;
1626  }
1627  case Intrinsic::uadd_sat:
1628  case Intrinsic::usub_sat: {
1629  bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1630  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1631  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1632 
1633  // Add: Leading ones of either operand are preserved.
1634  // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1635  // as leading zeros in the result.
1636  unsigned LeadingKnown;
1637  if (IsAdd)
1638  LeadingKnown = std::max(Known.countMinLeadingOnes(),
1639  Known2.countMinLeadingOnes());
1640  else
1641  LeadingKnown = std::max(Known.countMinLeadingZeros(),
1642  Known2.countMinLeadingOnes());
1643 
1645  IsAdd, /* NSW */ false, Known, Known2);
1646 
1647  // We select between the operation result and all-ones/zero
1648  // respectively, so we can preserve known ones/zeros.
1649  if (IsAdd) {
1650  Known.One.setHighBits(LeadingKnown);
1651  Known.Zero.clearAllBits();
1652  } else {
1653  Known.Zero.setHighBits(LeadingKnown);
1654  Known.One.clearAllBits();
1655  }
1656  break;
1657  }
1658  case Intrinsic::umin:
1659  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1660  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1661  Known = KnownBits::umin(Known, Known2);
1662  break;
1663  case Intrinsic::umax:
1664  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1665  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1666  Known = KnownBits::umax(Known, Known2);
1667  break;
1668  case Intrinsic::smin:
1669  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1670  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1671  Known = KnownBits::smin(Known, Known2);
1672  break;
1673  case Intrinsic::smax:
1674  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1675  computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1676  Known = KnownBits::smax(Known, Known2);
1677  break;
1678  case Intrinsic::x86_sse42_crc32_64_64:
1679  Known.Zero.setBitsFrom(32);
1680  break;
1681  case Intrinsic::riscv_vsetvli:
1682  case Intrinsic::riscv_vsetvlimax:
1683  // Assume that VL output is positive and would fit in an int32_t.
1684  // TODO: VLEN might be capped at 16 bits in a future V spec update.
1685  if (BitWidth >= 32)
1686  Known.Zero.setBitsFrom(31);
1687  break;
1688  case Intrinsic::vscale: {
1689  if (!II->getParent() || !II->getFunction() ||
1690  !II->getFunction()->hasFnAttribute(Attribute::VScaleRange))
1691  break;
1692 
1693  auto VScaleRange = II->getFunction()
1694  ->getFnAttribute(Attribute::VScaleRange)
1695  .getVScaleRangeArgs();
1696 
1697  if (VScaleRange.second == 0)
1698  break;
1699 
1700  // If vscale min = max then we know the exact value at compile time
1701  // and hence we know the exact bits.
1702  if (VScaleRange.first == VScaleRange.second) {
1703  Known.One = VScaleRange.first;
1704  Known.Zero = VScaleRange.first;
1705  Known.Zero.flipAllBits();
1706  break;
1707  }
1708 
1709  unsigned FirstZeroHighBit = 32 - countLeadingZeros(VScaleRange.second);
1710  if (FirstZeroHighBit < BitWidth)
1711  Known.Zero.setBitsFrom(FirstZeroHighBit);
1712 
1713  break;
1714  }
1715  }
1716  }
1717  break;
1718  case Instruction::ShuffleVector: {
1719  auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
1720  // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
1721  if (!Shuf) {
1722  Known.resetAll();
1723  return;
1724  }
1725  // For undef elements, we don't know anything about the common state of
1726  // the shuffle result.
1727  APInt DemandedLHS, DemandedRHS;
1728  if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
1729  Known.resetAll();
1730  return;
1731  }
1732  Known.One.setAllBits();
1733  Known.Zero.setAllBits();
1734  if (!!DemandedLHS) {
1735  const Value *LHS = Shuf->getOperand(0);
1736  computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q);
1737  // If we don't know any bits, early out.
1738  if (Known.isUnknown())
1739  break;
1740  }
1741  if (!!DemandedRHS) {
1742  const Value *RHS = Shuf->getOperand(1);
1743  computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q);
1744  Known = KnownBits::commonBits(Known, Known2);
1745  }
1746  break;
1747  }
1748  case Instruction::InsertElement: {
1749  const Value *Vec = I->getOperand(0);
1750  const Value *Elt = I->getOperand(1);
1751  auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
1752  // Early out if the index is non-constant or out-of-range.
1753  unsigned NumElts = DemandedElts.getBitWidth();
1754  if (!CIdx || CIdx->getValue().uge(NumElts)) {
1755  Known.resetAll();
1756  return;
1757  }
1758  Known.One.setAllBits();
1759  Known.Zero.setAllBits();
1760  unsigned EltIdx = CIdx->getZExtValue();
1761  // Do we demand the inserted element?
1762  if (DemandedElts[EltIdx]) {
1763  computeKnownBits(Elt, Known, Depth + 1, Q);
1764  // If we don't know any bits, early out.
1765  if (Known.isUnknown())
1766  break;
1767  }
1768  // We don't need the base vector element that has been inserted.
1769  APInt DemandedVecElts = DemandedElts;
1770  DemandedVecElts.clearBit(EltIdx);
1771  if (!!DemandedVecElts) {
1772  computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q);
1773  Known = KnownBits::commonBits(Known, Known2);
1774  }
1775  break;
1776  }
1777  case Instruction::ExtractElement: {
1778  // Look through extract element. If the index is non-constant or
1779  // out-of-range demand all elements, otherwise just the extracted element.
1780  const Value *Vec = I->getOperand(0);
1781  const Value *Idx = I->getOperand(1);
1782  auto *CIdx = dyn_cast<ConstantInt>(Idx);
1783  if (isa<ScalableVectorType>(Vec->getType())) {
1784  // FIXME: there's probably *something* we can do with scalable vectors
1785  Known.resetAll();
1786  break;
1787  }
1788  unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1789  APInt DemandedVecElts = APInt::getAllOnes(NumElts);
1790  if (CIdx && CIdx->getValue().ult(NumElts))
1791  DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1792  computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q);
1793  break;
1794  }
1795  case Instruction::ExtractValue:
1796  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1797  const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1798  if (EVI->getNumIndices() != 1) break;
1799  if (EVI->getIndices()[0] == 0) {
1800  switch (II->getIntrinsicID()) {
1801  default: break;
1802  case Intrinsic::uadd_with_overflow:
1803  case Intrinsic::sadd_with_overflow:
1804  computeKnownBitsAddSub(true, II->getArgOperand(0),
1805  II->getArgOperand(1), false, DemandedElts,
1806  Known, Known2, Depth, Q);
1807  break;
1808  case Intrinsic::usub_with_overflow:
1809  case Intrinsic::ssub_with_overflow:
1810  computeKnownBitsAddSub(false, II->getArgOperand(0),
1811  II->getArgOperand(1), false, DemandedElts,
1812  Known, Known2, Depth, Q);
1813  break;
1814  case Intrinsic::umul_with_overflow:
1815  case Intrinsic::smul_with_overflow:
1816  computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1817  DemandedElts, Known, Known2, Depth, Q);
1818  break;
1819  }
1820  }
1821  }
1822  break;
1823  case Instruction::Freeze:
1824  if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
1825  Depth + 1))
1826  computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1827  break;
1828  }
1829 }
1830 
1831 /// Determine which bits of V are known to be either zero or one and return
1832 /// them.
1833 KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
1834  unsigned Depth, const Query &Q) {
1835  KnownBits Known(getBitWidth(V->getType(), Q.DL));
1836  computeKnownBits(V, DemandedElts, Known, Depth, Q);
1837  return Known;
1838 }
1839 
1840 /// Determine which bits of V are known to be either zero or one and return
1841 /// them.
1842 KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1843  KnownBits Known(getBitWidth(V->getType(), Q.DL));
1844  computeKnownBits(V, Known, Depth, Q);
1845  return Known;
1846 }
1847 
1848 /// Determine which bits of V are known to be either zero or one and return
1849 /// them in the Known bit set.
1850 ///
1851 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1852 /// we cannot optimize based on the assumption that it is zero without changing
1853 /// it to be an explicit zero. If we don't change it to zero, other code could
1854 /// optimized based on the contradictory assumption that it is non-zero.
1855 /// Because instcombine aggressively folds operations with undef args anyway,
1856 /// this won't lose us code quality.
1857 ///
1858 /// This function is defined on values with integer type, values with pointer
1859 /// type, and vectors of integers. In the case
1860 /// where V is a vector, known zero, and known one values are the
1861 /// same width as the vector element, and the bit is set only if it is true
1862 /// for all of the demanded elements in the vector specified by DemandedElts.
1863 void computeKnownBits(const Value *V, const APInt &DemandedElts,
1864  KnownBits &Known, unsigned Depth, const Query &Q) {
1865  if (!DemandedElts || isa<ScalableVectorType>(V->getType())) {
1866  // No demanded elts or V is a scalable vector, better to assume we don't
1867  // know anything.
1868  Known.resetAll();
1869  return;
1870  }
1871 
1872  assert(V && "No Value?");
1873  assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1874 
1875 #ifndef NDEBUG
1876  Type *Ty = V->getType();
1877  unsigned BitWidth = Known.getBitWidth();
1878 
1880  "Not integer or pointer type!");
1881 
1882  if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
1883  assert(
1884  FVTy->getNumElements() == DemandedElts.getBitWidth() &&
1885  "DemandedElt width should equal the fixed vector number of elements");
1886  } else {
1887  assert(DemandedElts == APInt(1, 1) &&
1888  "DemandedElt width should be 1 for scalars");
1889  }
1890 
1891  Type *ScalarTy = Ty->getScalarType();
1892  if (ScalarTy->isPointerTy()) {
1893  assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
1894  "V and Known should have same BitWidth");
1895  } else {
1896  assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
1897  "V and Known should have same BitWidth");
1898  }
1899 #endif
1900 
1901  const APInt *C;
1902  if (match(V, m_APInt(C))) {
1903  // We know all of the bits for a scalar constant or a splat vector constant!
1904  Known = KnownBits::makeConstant(*C);
1905  return;
1906  }
1907  // Null and aggregate-zero are all-zeros.
1908  if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1909  Known.setAllZero();
1910  return;
1911  }
1912  // Handle a constant vector by taking the intersection of the known bits of
1913  // each element.
1914  if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
1915  // We know that CDV must be a vector of integers. Take the intersection of
1916  // each element.
1917  Known.Zero.setAllBits(); Known.One.setAllBits();
1918  for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
1919  if (!DemandedElts[i])
1920  continue;
1921  APInt Elt = CDV->getElementAsAPInt(i);
1922  Known.Zero &= ~Elt;
1923  Known.One &= Elt;
1924  }
1925  return;
1926  }
1927 
1928  if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1929  // We know that CV must be a vector of integers. Take the intersection of
1930  // each element.
1931  Known.Zero.setAllBits(); Known.One.setAllBits();
1932  for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1933  if (!DemandedElts[i])
1934  continue;
1935  Constant *Element = CV->getAggregateElement(i);
1936  auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1937  if (!ElementCI) {
1938  Known.resetAll();
1939  return;
1940  }
1941  const APInt &Elt = ElementCI->getValue();
1942  Known.Zero &= ~Elt;
1943  Known.One &= Elt;
1944  }
1945  return;
1946  }
1947 
1948  // Start out not knowing anything.
1949  Known.resetAll();
1950 
1951  // We can't imply anything about undefs.
1952  if (isa<UndefValue>(V))
1953  return;
1954 
1955  // There's no point in looking through other users of ConstantData for
1956  // assumptions. Confirm that we've handled them all.
1957  assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1958 
1959  // All recursive calls that increase depth must come after this.
1961  return;
1962 
1963  // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1964  // the bits of its aliasee.
1965  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1966  if (!GA->isInterposable())
1967  computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1968  return;
1969  }
1970 
1971  if (const Operator *I = dyn_cast<Operator>(V))
1972  computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q);
1973 
1974  // Aligned pointers have trailing zeros - refine Known.Zero set
1975  if (isa<PointerType>(V->getType())) {
1976  Align Alignment = V->getPointerAlignment(Q.DL);
1977  Known.Zero.setLowBits(Log2(Alignment));
1978  }
1979 
1980  // computeKnownBitsFromAssume strictly refines Known.
1981  // Therefore, we run them after computeKnownBitsFromOperator.
1982 
1983  // Check whether a nearby assume intrinsic can determine some known bits.
1984  computeKnownBitsFromAssume(V, Known, Depth, Q);
1985 
1986  assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1987 }
1988 
1989 /// Return true if the given value is known to have exactly one
1990 /// bit set when defined. For vectors return true if every element is known to
1991 /// be a power of two when defined. Supports values with integer or pointer
1992 /// types and vectors of integers.
1993 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1994  const Query &Q) {
1995  assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1996 
1997  // Attempt to match against constants.
1998  if (OrZero && match(V, m_Power2OrZero()))
1999  return true;
2000  if (match(V, m_Power2()))
2001  return true;
2002 
2003  // 1 << X is clearly a power of two if the one is not shifted off the end. If
2004  // it is shifted off the end then the result is undefined.
2005  if (match(V, m_Shl(m_One(), m_Value())))
2006  return true;
2007 
2008  // (signmask) >>l X is clearly a power of two if the one is not shifted off
2009  // the bottom. If it is shifted off the bottom then the result is undefined.
2010  if (match(V, m_LShr(m_SignMask(), m_Value())))
2011  return true;
2012 
2013  // The remaining tests are all recursive, so bail out if we hit the limit.
2015  return false;
2016 
2017  Value *X = nullptr, *Y = nullptr;
2018  // A shift left or a logical shift right of a power of two is a power of two
2019  // or zero.
2020  if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
2021  match(V, m_LShr(m_Value(X), m_Value()))))
2022  return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
2023 
2024  if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
2025  return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
2026 
2027  if (const SelectInst *SI = dyn_cast<SelectInst>(V))
2028  return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
2029  isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
2030 
2031  // Peek through min/max.
2032  if (match(V, m_MaxOrMin(m_Value(X), m_Value(Y)))) {
2033  return isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q) &&
2034  isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q);
2035  }
2036 
2037  if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
2038  // A power of two and'd with anything is a power of two or zero.
2039  if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
2040  isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
2041  return true;
2042  // X & (-X) is always a power of two or zero.
2043  if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
2044  return true;
2045  return false;
2046  }
2047 
2048  // Adding a power-of-two or zero to the same power-of-two or zero yields
2049  // either the original power-of-two, a larger power-of-two or zero.
2050  if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2051  const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
2052  if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2053  Q.IIQ.hasNoSignedWrap(VOBO)) {
2054  if (match(X, m_And(m_Specific(Y), m_Value())) ||
2055  match(X, m_And(m_Value(), m_Specific(Y))))
2056  if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
2057  return true;
2058  if (match(Y, m_And(m_Specific(X), m_Value())) ||
2059  match(Y, m_And(m_Value(), m_Specific(X))))
2060  if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
2061  return true;
2062 
2063  unsigned BitWidth = V->getType()->getScalarSizeInBits();
2064  KnownBits LHSBits(BitWidth);
2065  computeKnownBits(X, LHSBits, Depth, Q);
2066 
2067  KnownBits RHSBits(BitWidth);
2068  computeKnownBits(Y, RHSBits, Depth, Q);
2069  // If i8 V is a power of two or zero:
2070  // ZeroBits: 1 1 1 0 1 1 1 1
2071  // ~ZeroBits: 0 0 0 1 0 0 0 0
2072  if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2073  // If OrZero isn't set, we cannot give back a zero result.
2074  // Make sure either the LHS or RHS has a bit set.
2075  if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2076  return true;
2077  }
2078  }
2079 
2080  // An exact divide or right shift can only shift off zero bits, so the result
2081  // is a power of two only if the first operand is a power of two and not
2082  // copying a sign bit (sdiv int_min, 2).
2083  if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
2084  match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
2085  return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
2086  Depth, Q);
2087  }
2088 
2089  return false;
2090 }
2091 
2092 /// Test whether a GEP's result is known to be non-null.
2093 ///
2094 /// Uses properties inherent in a GEP to try to determine whether it is known
2095 /// to be non-null.
2096 ///
2097 /// Currently this routine does not support vector GEPs.
2098 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
2099  const Query &Q) {
2100  const Function *F = nullptr;
2101  if (const Instruction *I = dyn_cast<Instruction>(GEP))
2102  F = I->getFunction();
2103 
2104  if (!GEP->isInBounds() ||
2105  NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
2106  return false;
2107 
2108  // FIXME: Support vector-GEPs.
2109  assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2110 
2111  // If the base pointer is non-null, we cannot walk to a null address with an
2112  // inbounds GEP in address space zero.
2113  if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
2114  return true;
2115 
2116  // Walk the GEP operands and see if any operand introduces a non-zero offset.
2117  // If so, then the GEP cannot produce a null pointer, as doing so would
2118  // inherently violate the inbounds contract within address space zero.
2119  for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
2120  GTI != GTE; ++GTI) {
2121  // Struct types are easy -- they must always be indexed by a constant.
2122  if (StructType *STy = GTI.getStructTypeOrNull()) {
2123  ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2124  unsigned ElementIdx = OpC->getZExtValue();
2125  const StructLayout *SL = Q.DL.getStructLayout(STy);
2126  uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2127  if (ElementOffset > 0)
2128  return true;
2129  continue;
2130  }
2131 
2132  // If we have a zero-sized type, the index doesn't matter. Keep looping.
2133  if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).getKnownMinSize() == 0)
2134  continue;
2135 
2136  // Fast path the constant operand case both for efficiency and so we don't
2137  // increment Depth when just zipping down an all-constant GEP.
2138  if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2139  if (!OpC->isZero())
2140  return true;
2141  continue;
2142  }
2143 
2144  // We post-increment Depth here because while isKnownNonZero increments it
2145  // as well, when we pop back up that increment won't persist. We don't want
2146  // to recurse 10k times just because we have 10k GEP operands. We don't
2147  // bail completely out because we want to handle constant GEPs regardless
2148  // of depth.
2150  continue;
2151 
2152  if (isKnownNonZero(GTI.getOperand(), Depth, Q))
2153  return true;
2154  }
2155 
2156  return false;
2157 }
2158 
2160  const Instruction *CtxI,
2161  const DominatorTree *DT) {
2162  if (isa<Constant>(V))
2163  return false;
2164 
2165  if (!CtxI || !DT)
2166  return false;
2167 
2168  unsigned NumUsesExplored = 0;
2169  for (auto *U : V->users()) {
2170  // Avoid massive lists
2171  if (NumUsesExplored >= DomConditionsMaxUses)
2172  break;
2173  NumUsesExplored++;
2174 
2175  // If the value is used as an argument to a call or invoke, then argument
2176  // attributes may provide an answer about null-ness.
2177  if (const auto *CB = dyn_cast<CallBase>(U))
2178  if (auto *CalledFunc = CB->getCalledFunction())
2179  for (const Argument &Arg : CalledFunc->args())
2180  if (CB->getArgOperand(Arg.getArgNo()) == V &&
2181  Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) &&
2182  DT->dominates(CB, CtxI))
2183  return true;
2184 
2185  // If the value is used as a load/store, then the pointer must be non null.
2186  if (V == getLoadStorePointerOperand(U)) {
2187  const Instruction *I = cast<Instruction>(U);
2188  if (!NullPointerIsDefined(I->getFunction(),
2189  V->getType()->getPointerAddressSpace()) &&
2190  DT->dominates(I, CtxI))
2191  return true;
2192  }
2193 
2194  // Consider only compare instructions uniquely controlling a branch
2195  Value *RHS;
2196  CmpInst::Predicate Pred;
2197  if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2198  continue;
2199 
2200  bool NonNullIfTrue;
2201  if (cmpExcludesZero(Pred, RHS))
2202  NonNullIfTrue = true;
2203  else if (cmpExcludesZero(CmpInst::getInversePredicate(Pred), RHS))
2204  NonNullIfTrue = false;
2205  else
2206  continue;
2207 
2210  for (auto *CmpU : U->users()) {
2211  assert(WorkList.empty() && "Should be!");
2212  if (Visited.insert(CmpU).second)
2213  WorkList.push_back(CmpU);
2214 
2215  while (!WorkList.empty()) {
2216  auto *Curr = WorkList.pop_back_val();
2217 
2218  // If a user is an AND, add all its users to the work list. We only
2219  // propagate "pred != null" condition through AND because it is only
2220  // correct to assume that all conditions of AND are met in true branch.
2221  // TODO: Support similar logic of OR and EQ predicate?
2222  if (NonNullIfTrue)
2223  if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
2224  for (auto *CurrU : Curr->users())
2225  if (Visited.insert(CurrU).second)
2226  WorkList.push_back(CurrU);
2227  continue;
2228  }
2229 
2230  if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
2231  assert(BI->isConditional() && "uses a comparison!");
2232 
2233  BasicBlock *NonNullSuccessor =
2234  BI->getSuccessor(NonNullIfTrue ? 0 : 1);
2235  BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
2236  if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
2237  return true;
2238  } else if (NonNullIfTrue && isGuard(Curr) &&
2239  DT->dominates(cast<Instruction>(Curr), CtxI)) {
2240  return true;
2241  }
2242  }
2243  }
2244  }
2245 
2246  return false;
2247 }
2248 
2249 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
2250 /// ensure that the value it's attached to is never Value? 'RangeType' is
2251 /// is the type of the value described by the range.
2252 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
2253  const unsigned NumRanges = Ranges->getNumOperands() / 2;
2254  assert(NumRanges >= 1);
2255  for (unsigned i = 0; i < NumRanges; ++i) {
2256  ConstantInt *Lower =
2257  mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
2258  ConstantInt *Upper =
2259  mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
2260  ConstantRange Range(Lower->getValue(), Upper->getValue());
2261  if (Range.contains(Value))
2262  return false;
2263  }
2264  return true;
2265 }
2266 
2267 /// Try to detect a recurrence that monotonically increases/decreases from a
2268 /// non-zero starting value. These are common as induction variables.
2269 static bool isNonZeroRecurrence(const PHINode *PN) {
2270  BinaryOperator *BO = nullptr;
2271  Value *Start = nullptr, *Step = nullptr;
2272  const APInt *StartC, *StepC;
2273  if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
2274  !match(Start, m_APInt(StartC)) || StartC->isZero())
2275  return false;
2276 
2277  switch (BO->getOpcode()) {
2278  case Instruction::Add:
2279  // Starting from non-zero and stepping away from zero can never wrap back
2280  // to zero.
2281  return BO->hasNoUnsignedWrap() ||
2282  (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
2283  StartC->isNegative() == StepC->isNegative());
2284  case Instruction::Mul:
2285  return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
2286  match(Step, m_APInt(StepC)) && !StepC->isZero();
2287  case Instruction::Shl:
2288  return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
2289  case Instruction::AShr:
2290  case Instruction::LShr:
2291  return BO->isExact();
2292  default:
2293  return false;
2294  }
2295 }
2296 
2297 /// Return true if the given value is known to be non-zero when defined. For
2298 /// vectors, return true if every demanded element is known to be non-zero when
2299 /// defined. For pointers, if the context instruction and dominator tree are
2300 /// specified, perform context-sensitive analysis and return true if the
2301 /// pointer couldn't possibly be null at the specified instruction.
2302 /// Supports values with integer or pointer type and vectors of integers.
2303 bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth,
2304  const Query &Q) {
2305  // FIXME: We currently have no way to represent the DemandedElts of a scalable
2306  // vector
2307  if (isa<ScalableVectorType>(V->getType()))
2308  return false;
2309 
2310  if (auto *C = dyn_cast<Constant>(V)) {
2311  if (C->isNullValue())
2312  return false;
2313  if (isa<ConstantInt>(C))
2314  // Must be non-zero due to null test above.
2315  return true;
2316 
2317  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2318  // See the comment for IntToPtr/PtrToInt instructions below.
2319  if (CE->getOpcode() == Instruction::IntToPtr ||
2320  CE->getOpcode() == Instruction::PtrToInt)
2321  if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType())
2322  .getFixedSize() <=
2323  Q.DL.getTypeSizeInBits(CE->getType()).getFixedSize())
2324  return isKnownNonZero(CE->getOperand(0), Depth, Q);
2325  }
2326 
2327  // For constant vectors, check that all elements are undefined or known
2328  // non-zero to determine that the whole vector is known non-zero.
2329  if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) {
2330  for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2331  if (!DemandedElts[i])
2332  continue;
2333  Constant *Elt = C->getAggregateElement(i);
2334  if (!Elt || Elt->isNullValue())
2335  return false;
2336  if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2337  return false;
2338  }
2339  return true;
2340  }
2341 
2342  // A global variable in address space 0 is non null unless extern weak
2343  // or an absolute symbol reference. Other address spaces may have null as a
2344  // valid address for a global, so we can't assume anything.
2345  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2346  if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2347  GV->getType()->getAddressSpace() == 0)
2348  return true;
2349  } else
2350  return false;
2351  }
2352 
2353  if (auto *I = dyn_cast<Instruction>(V)) {
2354  if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
2355  // If the possible ranges don't contain zero, then the value is
2356  // definitely non-zero.
2357  if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
2358  const APInt ZeroValue(Ty->getBitWidth(), 0);
2359  if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2360  return true;
2361  }
2362  }
2363  }
2364 
2365  if (isKnownNonZeroFromAssume(V, Q))
2366  return true;
2367 
2368  // Some of the tests below are recursive, so bail out if we hit the limit.
2370  return false;
2371 
2372  // Check for pointer simplifications.
2373 
2374  if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) {
2375  // Alloca never returns null, malloc might.
2376  if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2377  return true;
2378 
2379  // A byval, inalloca may not be null in a non-default addres space. A
2380  // nonnull argument is assumed never 0.
2381  if (const Argument *A = dyn_cast<Argument>(V)) {
2382  if (((A->hasPassPointeeByValueCopyAttr() &&
2383  !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
2384  A->hasNonNullAttr()))
2385  return true;
2386  }
2387 
2388  // A Load tagged with nonnull metadata is never null.
2389  if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2390  if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
2391  return true;
2392 
2393  if (const auto *Call = dyn_cast<CallBase>(V)) {
2394  if (Call->isReturnNonNull())
2395  return true;
2396  if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
2397  return isKnownNonZero(RP, Depth, Q);
2398  }
2399  }
2400 
2401  if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2402  return true;
2403 
2404  // Check for recursive pointer simplifications.
2405  if (V->getType()->isPointerTy()) {
2406  // Look through bitcast operations, GEPs, and int2ptr instructions as they
2407  // do not alter the value, or at least not the nullness property of the
2408  // value, e.g., int2ptr is allowed to zero/sign extend the value.
2409  //
2410  // Note that we have to take special care to avoid looking through
2411  // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2412  // as casts that can alter the value, e.g., AddrSpaceCasts.
2413  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
2414  return isGEPKnownNonNull(GEP, Depth, Q);
2415 
2416  if (auto *BCO = dyn_cast<BitCastOperator>(V))
2417  return isKnownNonZero(BCO->getOperand(0), Depth, Q);
2418 
2419  if (auto *I2P = dyn_cast<IntToPtrInst>(V))
2420  if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()).getFixedSize() <=
2421  Q.DL.getTypeSizeInBits(I2P->getDestTy()).getFixedSize())
2422  return isKnownNonZero(I2P->getOperand(0), Depth, Q);
2423  }
2424 
2425  // Similar to int2ptr above, we can look through ptr2int here if the cast
2426  // is a no-op or an extend and not a truncate.
2427  if (auto *P2I = dyn_cast<PtrToIntInst>(V))
2428  if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()).getFixedSize() <=
2429  Q.DL.getTypeSizeInBits(P2I->getDestTy()).getFixedSize())
2430  return isKnownNonZero(P2I->getOperand(0), Depth, Q);
2431 
2432  unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
2433 
2434  // X | Y != 0 if X != 0 or Y != 0.
2435  Value *X = nullptr, *Y = nullptr;
2436  if (match(V, m_Or(m_Value(X), m_Value(Y))))
2437  return isKnownNonZero(X, DemandedElts, Depth, Q) ||
2438  isKnownNonZero(Y, DemandedElts, Depth, Q);
2439 
2440  // ext X != 0 if X != 0.
2441  if (isa<SExtInst>(V) || isa<ZExtInst>(V))
2442  return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
2443 
2444  // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
2445  // if the lowest bit is shifted off the end.
2446  if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
2447  // shl nuw can't remove any non-zero bits.
2448  const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2449  if (Q.IIQ.hasNoUnsignedWrap(BO))
2450  return isKnownNonZero(X, Depth, Q);
2451 
2452  KnownBits Known(BitWidth);
2453  computeKnownBits(X, DemandedElts, Known, Depth, Q);
2454  if (Known.One[0])
2455  return true;
2456  }
2457  // shr X, Y != 0 if X is negative. Note that the value of the shift is not
2458  // defined if the sign bit is shifted off the end.
2459  else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
2460  // shr exact can only shift out zero bits.
2461  const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
2462  if (BO->isExact())
2463  return isKnownNonZero(X, Depth, Q);
2464 
2465  KnownBits Known = computeKnownBits(X, DemandedElts, Depth, Q);
2466  if (Known.isNegative())
2467  return true;
2468 
2469  // If the shifter operand is a constant, and all of the bits shifted
2470  // out are known to be zero, and X is known non-zero then at least one
2471  // non-zero bit must remain.
2472  if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
2473  auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2474  // Is there a known one in the portion not shifted out?
2475  if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
2476  return true;
2477  // Are all the bits to be shifted out known zero?
2478  if (Known.countMinTrailingZeros() >= ShiftVal)
2479  return isKnownNonZero(X, DemandedElts, Depth, Q);
2480  }
2481  }
2482  // div exact can only produce a zero if the dividend is zero.
2483  else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
2484  return isKnownNonZero(X, DemandedElts, Depth, Q);
2485  }
2486  // X + Y.
2487  else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2488  KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q);
2489  KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q);
2490 
2491  // If X and Y are both non-negative (as signed values) then their sum is not
2492  // zero unless both X and Y are zero.
2493  if (XKnown.isNonNegative() && YKnown.isNonNegative())
2494  if (isKnownNonZero(X, DemandedElts, Depth, Q) ||
2495  isKnownNonZero(Y, DemandedElts, Depth, Q))
2496  return true;
2497 
2498  // If X and Y are both negative (as signed values) then their sum is not
2499  // zero unless both X and Y equal INT_MIN.
2500  if (XKnown.isNegative() && YKnown.isNegative()) {
2502  // The sign bit of X is set. If some other bit is set then X is not equal
2503  // to INT_MIN.
2504  if (XKnown.One.intersects(Mask))
2505  return true;
2506  // The sign bit of Y is set. If some other bit is set then Y is not equal
2507  // to INT_MIN.
2508  if (YKnown.One.intersects(Mask))
2509  return true;
2510  }
2511 
2512  // The sum of a non-negative number and a power of two is not zero.
2513  if (XKnown.isNonNegative() &&
2514  isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2515  return true;
2516  if (YKnown.isNonNegative() &&
2517  isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2518  return true;
2519  }
2520  // X * Y.
2521  else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2522  const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2523  // If X and Y are non-zero then so is X * Y as long as the multiplication
2524  // does not overflow.
2525  if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2526  isKnownNonZero(X, DemandedElts, Depth, Q) &&
2527  isKnownNonZero(Y, DemandedElts, Depth, Q))
2528  return true;
2529  }
2530  // (C ? X : Y) != 0 if X != 0 and Y != 0.
2531  else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
2532  if (isKnownNonZero(SI->getTrueValue(), DemandedElts, Depth, Q) &&
2533  isKnownNonZero(SI->getFalseValue(), DemandedElts, Depth, Q))
2534  return true;
2535  }
2536  // PHI
2537  else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2538  if (Q.IIQ.UseInstrInfo && isNonZeroRecurrence(PN))
2539  return true;
2540 
2541  // Check if all incoming values are non-zero using recursion.
2542  Query RecQ = Q;
2543  unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2544  return llvm::all_of(PN->operands(), [&](const Use &U) {
2545  if (U.get() == PN)
2546  return true;
2547  RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2548  return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ);
2549  });
2550  }
2551  // ExtractElement
2552  else if (const auto *EEI = dyn_cast<ExtractElementInst>(V)) {
2553  const Value *Vec = EEI->getVectorOperand();
2554  const Value *Idx = EEI->getIndexOperand();
2555  auto *CIdx = dyn_cast<ConstantInt>(Idx);
2556  if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
2557  unsigned NumElts = VecTy->getNumElements();
2558  APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2559  if (CIdx && CIdx->getValue().ult(NumElts))
2560  DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2561  return isKnownNonZero(Vec, DemandedVecElts, Depth, Q);
2562  }
2563  }
2564  // Freeze
2565  else if (const FreezeInst *FI = dyn_cast<FreezeInst>(V)) {
2566  auto *Op = FI->getOperand(0);
2567  if (isKnownNonZero(Op, Depth, Q) &&
2568  isGuaranteedNotToBePoison(Op, Q.AC, Q.CxtI, Q.DT, Depth))
2569  return true;
2570  }
2571 
2572  KnownBits Known(BitWidth);
2573  computeKnownBits(V, DemandedElts, Known, Depth, Q);
2574  return Known.One != 0;
2575 }
2576 
2577 bool isKnownNonZero(const Value* V, unsigned Depth, const Query& Q) {
2578  // FIXME: We currently have no way to represent the DemandedElts of a scalable
2579  // vector
2580  if (isa<ScalableVectorType>(V->getType()))
2581  return false;
2582 
2583  auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
2584  APInt DemandedElts =
2585  FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
2586  return isKnownNonZero(V, DemandedElts, Depth, Q);
2587 }
2588 
2589 /// If the pair of operators are the same invertible function, return the
2590 /// the operands of the function corresponding to each input. Otherwise,
2591 /// return None. An invertible function is one that is 1-to-1 and maps
2592 /// every input value to exactly one output value. This is equivalent to
2593 /// saying that Op1 and Op2 are equal exactly when the specified pair of
2594 /// operands are equal, (except that Op1 and Op2 may be poison more often.)
2597  const Operator *Op2) {
2598  if (Op1->getOpcode() != Op2->getOpcode())
2599  return None;
2600 
2601  auto getOperands = [&](unsigned OpNum) -> auto {
2602  return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
2603  };
2604 
2605  switch (Op1->getOpcode()) {
2606  default:
2607  break;
2608  case Instruction::Add:
2609  case Instruction::Sub:
2610  if (Op1->getOperand(0) == Op2->getOperand(0))
2611  return getOperands(1);
2612  if (Op1->getOperand(1) == Op2->getOperand(1))
2613  return getOperands(0);
2614  break;
2615  case Instruction::Mul: {
2616  // invertible if A * B == (A * B) mod 2^N where A, and B are integers
2617  // and N is the bitwdith. The nsw case is non-obvious, but proven by
2618  // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
2619  auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2620  auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2621  if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2622  (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2623  break;
2624 
2625  // Assume operand order has been canonicalized
2626  if (Op1->getOperand(1) == Op2->getOperand(1) &&
2627  isa<ConstantInt>(Op1->getOperand(1)) &&
2628  !cast<ConstantInt>(Op1->getOperand(1))->isZero())
2629  return getOperands(0);
2630  break;
2631  }
2632  case Instruction::Shl: {
2633  // Same as multiplies, with the difference that we don't need to check
2634  // for a non-zero multiply. Shifts always multiply by non-zero.
2635  auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2636  auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2637  if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2638  (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2639  break;
2640 
2641  if (Op1->getOperand(1) == Op2->getOperand(1))
2642  return getOperands(0);
2643  break;
2644  }
2645  case Instruction::AShr:
2646  case Instruction::LShr: {
2647  auto *PEO1 = cast<PossiblyExactOperator>(Op1);
2648  auto *PEO2 = cast<PossiblyExactOperator>(Op2);
2649  if (!PEO1->isExact() || !PEO2->isExact())
2650  break;
2651 
2652  if (Op1->getOperand(1) == Op2->getOperand(1))
2653  return getOperands(0);
2654  break;
2655  }
2656  case Instruction::SExt:
2657  case Instruction::ZExt:
2658  if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
2659  return getOperands(0);
2660  break;
2661  case Instruction::PHI: {
2662  const PHINode *PN1 = cast<PHINode>(Op1);
2663  const PHINode *PN2 = cast<PHINode>(Op2);
2664 
2665  // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
2666  // are a single invertible function of the start values? Note that repeated
2667  // application of an invertible function is also invertible
2668  BinaryOperator *BO1 = nullptr;
2669  Value *Start1 = nullptr, *Step1 = nullptr;
2670  BinaryOperator *BO2 = nullptr;
2671  Value *Start2 = nullptr, *Step2 = nullptr;
2672  if (PN1->getParent() != PN2->getParent() ||
2673  !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
2674  !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
2675  break;
2676 
2677  auto Values = getInvertibleOperands(cast<Operator>(BO1),
2678  cast<Operator>(BO2));
2679  if (!Values)
2680  break;
2681 
2682  // We have to be careful of mutually defined recurrences here. Ex:
2683  // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
2684  // * X_i = Y_i = X_(i-1) OP Y_(i-1)
2685  // The invertibility of these is complicated, and not worth reasoning
2686  // about (yet?).
2687  if (Values->first != PN1 || Values->second != PN2)
2688  break;
2689 
2690  return std::make_pair(Start1, Start2);
2691  }
2692  }
2693  return None;
2694 }
2695 
2696 /// Return true if V2 == V1 + X, where X is known non-zero.
2697 static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth,
2698  const Query &Q) {
2699  const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2700  if (!BO || BO->getOpcode() != Instruction::Add)
2701  return false;
2702  Value *Op = nullptr;
2703  if (V2 == BO->getOperand(0))
2704  Op = BO->getOperand(1);
2705  else if (V2 == BO->getOperand(1))
2706  Op = BO->getOperand(0);
2707  else
2708  return false;
2709  return isKnownNonZero(Op, Depth + 1, Q);
2710 }
2711 
2712 /// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
2713 /// the multiplication is nuw or nsw.
2714 static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth,
2715  const Query &Q) {
2716  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2717  const APInt *C;
2718  return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
2719  (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2720  !C->isZero() && !C->isOne() && isKnownNonZero(V1, Depth + 1, Q);
2721  }
2722  return false;
2723 }
2724 
2725 /// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
2726 /// the shift is nuw or nsw.
2727 static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth,
2728  const Query &Q) {
2729  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2730  const APInt *C;
2731  return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
2732  (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2733  !C->isZero() && isKnownNonZero(V1, Depth + 1, Q);
2734  }
2735  return false;
2736 }
2737 
2738 static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
2739  unsigned Depth, const Query &Q) {
2740  // Check two PHIs are in same block.
2741  if (PN1->getParent() != PN2->getParent())
2742  return false;
2743 
2745  bool UsedFullRecursion = false;
2746  for (const BasicBlock *IncomBB : PN1->blocks()) {
2747  if (!VisitedBBs.insert(IncomBB).second)
2748  continue; // Don't reprocess blocks that we have dealt with already.
2749  const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
2750  const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
2751  const APInt *C1, *C2;
2752  if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
2753  continue;
2754 
2755  // Only one pair of phi operands is allowed for full recursion.
2756  if (UsedFullRecursion)
2757  return false;
2758 
2759  Query RecQ = Q;
2760  RecQ.CxtI = IncomBB->getTerminator();
2761  if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ))
2762  return false;
2763  UsedFullRecursion = true;
2764  }
2765  return true;
2766 }
2767 
2768 /// Return true if it is known that V1 != V2.
2769 static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
2770  const Query &Q) {
2771  if (V1 == V2)
2772  return false;
2773  if (V1->getType() != V2->getType())
2774  // We can't look through casts yet.
2775  return false;
2776 
2778  return false;
2779 
2780  // See if we can recurse through (exactly one of) our operands. This
2781  // requires our operation be 1-to-1 and map every input value to exactly
2782  // one output value. Such an operation is invertible.
2783  auto *O1 = dyn_cast<Operator>(V1);
2784  auto *O2 = dyn_cast<Operator>(V2);
2785  if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
2786  if (auto Values = getInvertibleOperands(O1, O2))
2787  return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q);
2788 
2789  if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
2790  const PHINode *PN2 = cast<PHINode>(V2);
2791  // FIXME: This is missing a generalization to handle the case where one is
2792  // a PHI and another one isn't.
2793  if (isNonEqualPHIs(PN1, PN2, Depth, Q))
2794  return true;
2795  };
2796  }
2797 
2798  if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q))
2799  return true;
2800 
2801  if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q))
2802  return true;
2803 
2804  if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q))
2805  return true;
2806 
2807  if (V1->getType()->isIntOrIntVectorTy()) {
2808  // Are any known bits in V1 contradictory to known bits in V2? If V1
2809  // has a known zero where V2 has a known one, they must not be equal.
2810  KnownBits Known1 = computeKnownBits(V1, Depth, Q);
2811  KnownBits Known2 = computeKnownBits(V2, Depth, Q);
2812 
2813  if (Known1.Zero.intersects(Known2.One) ||
2814  Known2.Zero.intersects(Known1.One))
2815  return true;
2816  }
2817  return false;
2818 }
2819 
2820 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
2821 /// simplify operations downstream. Mask is known to be zero for bits that V
2822 /// cannot have.
2823 ///
2824 /// This function is defined on values with integer type, values with pointer
2825 /// type, and vectors of integers. In the case
2826 /// where V is a vector, the mask, known zero, and known one values are the
2827 /// same width as the vector element, and the bit is set only if it is true
2828 /// for all of the elements in the vector.
2829 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2830  const Query &Q) {
2831  KnownBits Known(Mask.getBitWidth());
2832  computeKnownBits(V, Known, Depth, Q);
2833  return Mask.isSubsetOf(Known.Zero);
2834 }
2835 
2836 // Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2837 // Returns the input and lower/upper bounds.
2838 static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2839  const APInt *&CLow, const APInt *&CHigh) {
2840  assert(isa<Operator>(Select) &&
2841  cast<Operator>(Select)->getOpcode() == Instruction::Select &&
2842  "Input should be a Select!");
2843 
2844  const Value *LHS = nullptr, *RHS = nullptr;
2846  if (SPF != SPF_SMAX && SPF != SPF_SMIN)
2847  return false;
2848 
2849  if (!match(RHS, m_APInt(CLow)))
2850  return false;
2851 
2852  const Value *LHS2 = nullptr, *RHS2 = nullptr;
2853  SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
2854  if (getInverseMinMaxFlavor(SPF) != SPF2)
2855  return false;
2856 
2857  if (!match(RHS2, m_APInt(CHigh)))
2858  return false;
2859 
2860  if (SPF == SPF_SMIN)
2861  std::swap(CLow, CHigh);
2862 
2863  In = LHS2;
2864  return CLow->sle(*CHigh);
2865 }
2866 
2867 /// For vector constants, loop over the elements and find the constant with the
2868 /// minimum number of sign bits. Return 0 if the value is not a vector constant
2869 /// or if any element was not analyzed; otherwise, return the count for the
2870 /// element with the minimum number of sign bits.
2871 static unsigned computeNumSignBitsVectorConstant(const Value *V,
2872  const APInt &DemandedElts,
2873  unsigned TyBits) {
2874  const auto *CV = dyn_cast<Constant>(V);
2875  if (!CV || !isa<FixedVectorType>(CV->getType()))
2876  return 0;
2877 
2878  unsigned MinSignBits = TyBits;
2879  unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
2880  for (unsigned i = 0; i != NumElts; ++i) {
2881  if (!DemandedElts[i])
2882  continue;
2883  // If we find a non-ConstantInt, bail out.
2884  auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2885  if (!Elt)
2886  return 0;
2887 
2888  MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
2889  }
2890 
2891  return MinSignBits;
2892 }
2893 
2894 static unsigned ComputeNumSignBitsImpl(const Value *V,
2895  const APInt &DemandedElts,
2896  unsigned Depth, const Query &Q);
2897 
2898 static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
2899  unsigned Depth, const Query &Q) {
2900  unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q);
2901  assert(Result > 0 && "At least one sign bit needs to be present!");
2902  return Result;
2903 }
2904 
2905 /// Return the number of times the sign bit of the register is replicated into
2906 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2907 /// (itself), but other cases can give us information. For example, immediately
2908 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2909 /// other, so we return 3. For vectors, return the number of sign bits for the
2910 /// vector element with the minimum number of known sign bits of the demanded
2911 /// elements in the vector specified by DemandedElts.
2912 static unsigned ComputeNumSignBitsImpl(const Value *V,
2913  const APInt &DemandedElts,
2914  unsigned Depth, const Query &Q) {
2915  Type *Ty = V->getType();
2916 
2917  // FIXME: We currently have no way to represent the DemandedElts of a scalable
2918  // vector
2919  if (isa<ScalableVectorType>(Ty))
2920  return 1;
2921 
2922 #ifndef NDEBUG
2923  assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2924 
2925  if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2926  assert(
2927  FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2928  "DemandedElt width should equal the fixed vector number of elements");
2929  } else {
2930  assert(DemandedElts == APInt(1, 1) &&
2931  "DemandedElt width should be 1 for scalars");
2932  }
2933 #endif
2934 
2935  // We return the minimum number of sign bits that are guaranteed to be present
2936  // in V, so for undef we have to conservatively return 1. We don't have the
2937  // same behavior for poison though -- that's a FIXME today.
2938 
2939  Type *ScalarTy = Ty->getScalarType();
2940  unsigned TyBits = ScalarTy->isPointerTy() ?
2941  Q.DL.getPointerTypeSizeInBits(ScalarTy) :
2942  Q.DL.getTypeSizeInBits(ScalarTy);
2943 
2944  unsigned Tmp, Tmp2;
2945  unsigned FirstAnswer = 1;
2946 
2947  // Note that ConstantInt is handled by the general computeKnownBits case
2948  // below.
2949 
2951  return 1;
2952 
2953  if (auto *U = dyn_cast<Operator>(V)) {
2954  switch (Operator::getOpcode(V)) {
2955  default: break;
2956  case Instruction::SExt:
2957  Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2958  return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2959 
2960  case Instruction::SDiv: {
2961  const APInt *Denominator;
2962  // sdiv X, C -> adds log(C) sign bits.
2963  if (match(U->getOperand(1), m_APInt(Denominator))) {
2964 
2965  // Ignore non-positive denominator.
2966  if (!Denominator->isStrictlyPositive())
2967  break;
2968 
2969  // Calculate the incoming numerator bits.
2970  unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2971 
2972  // Add floor(log(C)) bits to the numerator bits.
2973  return std::min(TyBits, NumBits + Denominator->logBase2());
2974  }
2975  break;
2976  }
2977 
2978  case Instruction::SRem: {
2979  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2980 
2981  const APInt *Denominator;
2982  // srem X, C -> we know that the result is within [-C+1,C) when C is a
2983  // positive constant. This let us put a lower bound on the number of sign
2984  // bits.
2985  if (match(U->getOperand(1), m_APInt(Denominator))) {
2986 
2987  // Ignore non-positive denominator.
2988  if (Denominator->isStrictlyPositive()) {
2989  // Calculate the leading sign bit constraints by examining the
2990  // denominator. Given that the denominator is positive, there are two
2991  // cases:
2992  //
2993  // 1. The numerator is positive. The result range is [0,C) and
2994  // [0,C) u< (1 << ceilLogBase2(C)).
2995  //
2996  // 2. The numerator is negative. Then the result range is (-C,0] and
2997  // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2998  //
2999  // Thus a lower bound on the number of sign bits is `TyBits -
3000  // ceilLogBase2(C)`.
3001 
3002  unsigned ResBits = TyBits - Denominator->ceilLogBase2();
3003  Tmp = std::max(Tmp, ResBits);
3004  }
3005  }
3006  return Tmp;
3007  }
3008 
3009  case Instruction::AShr: {
3010  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3011  // ashr X, C -> adds C sign bits. Vectors too.
3012  const APInt *ShAmt;
3013  if (match(U->getOperand(1), m_APInt(ShAmt))) {
3014  if (ShAmt->uge(TyBits))
3015  break; // Bad shift.
3016  unsigned ShAmtLimited = ShAmt->getZExtValue();
3017  Tmp += ShAmtLimited;
3018  if (Tmp > TyBits) Tmp = TyBits;
3019  }
3020  return Tmp;
3021  }
3022  case Instruction::Shl: {
3023  const APInt *ShAmt;
3024  if (match(U->getOperand(1), m_APInt(ShAmt))) {
3025  // shl destroys sign bits.
3026  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3027  if (ShAmt->uge(TyBits) || // Bad shift.
3028  ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
3029  Tmp2 = ShAmt->getZExtValue();
3030  return Tmp - Tmp2;
3031  }
3032  break;
3033  }
3034  case Instruction::And:
3035  case Instruction::Or:
3036  case Instruction::Xor: // NOT is handled here.
3037  // Logical binary ops preserve the number of sign bits at the worst.
3038  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3039  if (Tmp != 1) {
3040  Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3041  FirstAnswer = std::min(Tmp, Tmp2);
3042  // We computed what we know about the sign bits as our first
3043  // answer. Now proceed to the generic code that uses
3044  // computeKnownBits, and pick whichever answer is better.
3045  }
3046  break;
3047 
3048  case Instruction::Select: {
3049  // If we have a clamp pattern, we know that the number of sign bits will
3050  // be the minimum of the clamp min/max range.
3051  const Value *X;
3052  const APInt *CLow, *CHigh;
3053  if (isSignedMinMaxClamp(U, X, CLow, CHigh))
3054  return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3055 
3056  Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3057  if (Tmp == 1) break;
3058  Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
3059  return std::min(Tmp, Tmp2);
3060  }
3061 
3062  case Instruction::Add:
3063  // Add can have at most one carry bit. Thus we know that the output
3064  // is, at worst, one more bit than the inputs.
3065  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3066  if (Tmp == 1) break;
3067 
3068  // Special case decrementing a value (ADD X, -1):
3069  if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
3070  if (CRHS->isAllOnesValue()) {
3071  KnownBits Known(TyBits);
3072  computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
3073 
3074  // If the input is known to be 0 or 1, the output is 0/-1, which is
3075  // all sign bits set.
3076  if ((Known.Zero | 1).isAllOnes())
3077  return TyBits;
3078 
3079  // If we are subtracting one from a positive number, there is no carry
3080  // out of the result.
3081  if (Known.isNonNegative())
3082  return Tmp;
3083  }
3084 
3085  Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3086  if (Tmp2 == 1) break;
3087  return std::min(Tmp, Tmp2) - 1;
3088 
3089  case Instruction::Sub:
3090  Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3091  if (Tmp2 == 1) break;
3092 
3093  // Handle NEG.
3094  if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
3095  if (CLHS->isNullValue()) {
3096  KnownBits Known(TyBits);
3097  computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
3098  // If the input is known to be 0 or 1, the output is 0/-1, which is
3099  // all sign bits set.
3100  if ((Known.Zero | 1).isAllOnes())
3101  return TyBits;
3102 
3103  // If the input is known to be positive (the sign bit is known clear),
3104  // the output of the NEG has the same number of sign bits as the
3105  // input.
3106  if (Known.isNonNegative())
3107  return Tmp2;
3108 
3109  // Otherwise, we treat this like a SUB.
3110  }
3111 
3112  // Sub can have at most one carry bit. Thus we know that the output
3113  // is, at worst, one more bit than the inputs.
3114  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3115  if (Tmp == 1) break;
3116  return std::min(Tmp, Tmp2) - 1;
3117 
3118  case Instruction::Mul: {
3119  // The output of the Mul can be at most twice the valid bits in the
3120  // inputs.
3121  unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3122  if (SignBitsOp0 == 1) break;
3123  unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3124  if (SignBitsOp1 == 1) break;
3125  unsigned OutValidBits =
3126  (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
3127  return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
3128  }
3129 
3130  case Instruction::PHI: {
3131  const PHINode *PN = cast<PHINode>(U);
3132  unsigned NumIncomingValues = PN->getNumIncomingValues();
3133  // Don't analyze large in-degree PHIs.
3134  if (NumIncomingValues > 4) break;
3135  // Unreachable blocks may have zero-operand PHI nodes.
3136  if (NumIncomingValues == 0) break;
3137 
3138  // Take the minimum of all incoming values. This can't infinitely loop
3139  // because of our depth threshold.
3140  Query RecQ = Q;
3141  Tmp = TyBits;
3142  for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
3143  if (Tmp == 1) return Tmp;
3144  RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
3145  Tmp = std::min(
3146  Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ));
3147  }
3148  return Tmp;
3149  }
3150 
3151  case Instruction::Trunc:
3152  // FIXME: it's tricky to do anything useful for this, but it is an
3153  // important case for targets like X86.
3154  break;
3155 
3156  case Instruction::ExtractElement:
3157  // Look through extract element. At the moment we keep this simple and
3158  // skip tracking the specific element. But at least we might find
3159  // information valid for all elements of the vector (for example if vector
3160  // is sign extended, shifted, etc).
3161  return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3162 
3163  case Instruction::ShuffleVector: {
3164  // Collect the minimum number of sign bits that are shared by every vector
3165  // element referenced by the shuffle.
3166  auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
3167  if (!Shuf) {
3168  // FIXME: Add support for shufflevector constant expressions.
3169  return 1;
3170  }
3171  APInt DemandedLHS, DemandedRHS;
3172  // For undef elements, we don't know anything about the common state of
3173  // the shuffle result.
3174  if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3175  return 1;
3177  if (!!DemandedLHS) {
3178  const Value *LHS = Shuf->getOperand(0);
3179  Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q);
3180  }
3181  // If we don't know anything, early out and try computeKnownBits
3182  // fall-back.
3183  if (Tmp == 1)
3184  break;
3185  if (!!DemandedRHS) {
3186  const Value *RHS = Shuf->getOperand(1);
3187  Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q);
3188  Tmp = std::min(Tmp, Tmp2);
3189  }
3190  // If we don't know anything, early out and try computeKnownBits
3191  // fall-back.
3192  if (Tmp == 1)
3193  break;
3194  assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
3195  return Tmp;
3196  }
3197  case Instruction::Call: {
3198  if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
3199  switch (II->getIntrinsicID()) {
3200  default: break;
3201  case Intrinsic::abs:
3202  Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3203  if (Tmp == 1) break;
3204 
3205  // Absolute value reduces number of sign bits by at most 1.
3206  return Tmp - 1;
3207  }
3208  }
3209  }
3210  }
3211  }
3212 
3213  // Finally, if we can prove that the top bits of the result are 0's or 1's,
3214  // use this information.
3215 
3216  // If we can examine all elements of a vector constant successfully, we're
3217  // done (we can't do any better than that). If not, keep trying.
3218  if (unsigned VecSignBits =
3219  computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
3220  return VecSignBits;
3221 
3222  KnownBits Known(TyBits);
3223  computeKnownBits(V, DemandedElts, Known, Depth, Q);
3224 
3225  // If we know that the sign bit is either zero or one, determine the number of
3226  // identical bits in the top of the input value.
3227  return std::max(FirstAnswer, Known.countMinSignBits());
3228 }
3229 
3230 /// This function computes the integer multiple of Base that equals V.
3231 /// If successful, it returns true and returns the multiple in
3232 /// Multiple. If unsuccessful, it returns false. It looks
3233 /// through SExt instructions only if LookThroughSExt is true.
3234 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
3235  bool LookThroughSExt, unsigned Depth) {
3236  assert(V && "No Value?");
3237  assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3238  assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
3239 
3240  Type *T = V->getType();
3241 
3242  ConstantInt *CI = dyn_cast<ConstantInt>(V);
3243 
3244  if (Base == 0)
3245  return false;
3246 
3247  if (Base == 1) {
3248  Multiple = V;
3249  return true;
3250  }
3251 
3252  ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
3253  Constant *BaseVal = ConstantInt::get(T, Base);
3254  if (CO && CO == BaseVal) {
3255  // Multiple is 1.
3256  Multiple = ConstantInt::get(T, 1);
3257  return true;
3258  }
3259 
3260  if (CI && CI->getZExtValue() % Base == 0) {
3261  Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
3262  return true;
3263  }
3264 
3265  if (Depth == MaxAnalysisRecursionDepth) return false;
3266 
3267  Operator *I = dyn_cast<Operator>(V);
3268  if (!I) return false;
3269 
3270  switch (I->getOpcode()) {
3271  default: break;
3272  case Instruction::SExt:
3273  if (!LookThroughSExt) return false;
3274  // otherwise fall through to ZExt
3276  case Instruction::ZExt:
3277  return ComputeMultiple(I->getOperand(0), Base, Multiple,
3278  LookThroughSExt, Depth+1);
3279  case Instruction::Shl:
3280  case Instruction::Mul: {
3281  Value *Op0 = I->getOperand(0);
3282  Value *Op1 = I->getOperand(1);
3283 
3284  if (I->getOpcode() == Instruction::Shl) {
3285  ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
3286  if (!Op1CI) return false;
3287  // Turn Op0 << Op1 into Op0 * 2^Op1
3288  APInt Op1Int = Op1CI->getValue();
3289  uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
3290  APInt API(Op1Int.getBitWidth(), 0);
3291  API.setBit(BitToSet);
3292  Op1 = ConstantInt::get(V->getContext(), API);
3293  }
3294 
3295  Value *Mul0 = nullptr;
3296  if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
3297  if (Constant *Op1C = dyn_cast<Constant>(Op1))
3298  if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
3299  if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3300  MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3301  Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
3302  if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3303  MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3304  MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
3305 
3306  // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
3307  Multiple = ConstantExpr::getMul(MulC, Op1C);
3308  return true;
3309  }
3310 
3311  if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
3312  if (Mul0CI->getValue() == 1) {
3313  // V == Base * Op1, so return Op1
3314  Multiple = Op1;
3315  return true;
3316  }
3317  }
3318 
3319  Value *Mul1 = nullptr;
3320  if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
3321  if (Constant *Op0C = dyn_cast<Constant>(Op0))
3322  if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
3323  if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() <
3324  MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3325  Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
3326  if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() >
3327  MulC->getType()->getPrimitiveSizeInBits().getFixedSize())
3328  MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
3329 
3330  // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
3331  Multiple = ConstantExpr::getMul(MulC, Op0C);
3332  return true;
3333  }
3334 
3335  if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
3336  if (Mul1CI->getValue() == 1) {
3337  // V == Base * Op0, so return Op0
3338  Multiple = Op0;
3339  return true;
3340  }
3341  }
3342  }
3343  }
3344 
3345  // We could not determine if V is a multiple of Base.
3346  return false;
3347 }
3348 
3350  const TargetLibraryInfo *TLI) {
3351  const Function *F = CB.getCalledFunction();
3352  if (!F)
3353  return Intrinsic::not_intrinsic;
3354 
3355  if (F->isIntrinsic())
3356  return F->getIntrinsicID();
3357 
3358  // We are going to infer semantics of a library function based on mapping it
3359  // to an LLVM intrinsic. Check that the library function is available from
3360  // this callbase and in this environment.
3361  LibFunc Func;
3362  if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
3363  !CB.onlyReadsMemory())
3364  return Intrinsic::not_intrinsic;
3365 
3366  switch (Func) {
3367  default:
3368  break;
3369  case LibFunc_sin:
3370  case LibFunc_sinf:
3371  case LibFunc_sinl:
3372  return Intrinsic::sin;
3373  case LibFunc_cos:
3374  case LibFunc_cosf:
3375  case LibFunc_cosl:
3376  return Intrinsic::cos;
3377  case LibFunc_exp:
3378  case LibFunc_expf:
3379  case LibFunc_expl:
3380  return Intrinsic::exp;
3381  case LibFunc_exp2:
3382  case LibFunc_exp2f:
3383  case LibFunc_exp2l:
3384  return Intrinsic::exp2;
3385  case LibFunc_log:
3386  case LibFunc_logf:
3387  case LibFunc_logl:
3388  return Intrinsic::log;
3389  case LibFunc_log10:
3390  case LibFunc_log10f:
3391  case LibFunc_log10l:
3392  return Intrinsic::log10;
3393  case LibFunc_log2:
3394  case LibFunc_log2f:
3395  case LibFunc_log2l:
3396  return Intrinsic::log2;
3397  case LibFunc_fabs:
3398  case LibFunc_fabsf:
3399  case LibFunc_fabsl:
3400  return Intrinsic::fabs;
3401  case LibFunc_fmin:
3402  case LibFunc_fminf:
3403  case LibFunc_fminl:
3404  return Intrinsic::minnum;
3405  case LibFunc_fmax:
3406  case LibFunc_fmaxf:
3407  case LibFunc_fmaxl:
3408  return Intrinsic::maxnum;
3409  case LibFunc_copysign:
3410  case LibFunc_copysignf:
3411  case LibFunc_copysignl:
3412  return Intrinsic::copysign;
3413  case LibFunc_floor:
3414  case LibFunc_floorf:
3415  case LibFunc_floorl:
3416  return Intrinsic::floor;
3417  case LibFunc_ceil:
3418  case LibFunc_ceilf:
3419  case LibFunc_ceill:
3420  return Intrinsic::ceil;
3421  case LibFunc_trunc:
3422  case LibFunc_truncf:
3423  case LibFunc_truncl:
3424  return Intrinsic::trunc;
3425  case LibFunc_rint:
3426  case LibFunc_rintf:
3427  case LibFunc_rintl:
3428  return Intrinsic::rint;
3429  case LibFunc_nearbyint:
3430  case LibFunc_nearbyintf:
3431  case LibFunc_nearbyintl:
3432  return Intrinsic::nearbyint;
3433  case LibFunc_round:
3434  case LibFunc_roundf:
3435  case LibFunc_roundl:
3436  return Intrinsic::round;
3437  case LibFunc_roundeven:
3438  case LibFunc_roundevenf:
3439  case LibFunc_roundevenl:
3440  return Intrinsic::roundeven;
3441  case LibFunc_pow:
3442  case LibFunc_powf:
3443  case LibFunc_powl:
3444  return Intrinsic::pow;
3445  case LibFunc_sqrt:
3446  case LibFunc_sqrtf:
3447  case LibFunc_sqrtl:
3448  return Intrinsic::sqrt;
3449  }
3450 
3451  return Intrinsic::not_intrinsic;
3452 }
3453 
3454 /// Return true if we can prove that the specified FP value is never equal to
3455 /// -0.0.
3456 /// NOTE: Do not check 'nsz' here because that fast-math-flag does not guarantee
3457 /// that a value is not -0.0. It only guarantees that -0.0 may be treated
3458 /// the same as +0.0 in floating-point ops.
3459 ///
3460 /// NOTE: this function will need to be revisited when we support non-default
3461 /// rounding modes!
3463  unsigned Depth) {
3464  if (auto *CFP = dyn_cast<ConstantFP>(V))
3465  return !CFP->getValueAPF().isNegZero();
3466 
3468  return false;
3469 
3470  auto *Op = dyn_cast<Operator>(V);
3471  if (!Op)
3472  return false;
3473 
3474  // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
3475  if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
3476  return true;
3477 
3478  // sitofp and uitofp turn into +0.0 for zero.
3479  if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
3480  return true;
3481 
3482  if (auto *Call = dyn_cast<CallInst>(Op)) {
3483  Intrinsic::ID IID = getIntrinsicForCallSite(*Call, TLI);
3484  switch (IID) {
3485  default:
3486  break;
3487  // sqrt(-0.0) = -0.0, no other negative results are possible.
3488  case Intrinsic::sqrt:
3489  case Intrinsic::canonicalize:
3490  return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
3491  // fabs(x) != -0.0
3492  case Intrinsic::fabs:
3493  return true;
3494  }
3495  }
3496 
3497  return false;
3498 }
3499 
3500 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
3501 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
3502 /// bit despite comparing equal.
3504  const TargetLibraryInfo *TLI,
3505  bool SignBitOnly,
3506  unsigned Depth) {
3507  // TODO: This function does not do the right thing when SignBitOnly is true
3508  // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
3509  // which flips the sign bits of NaNs. See
3510  // https://llvm.org/bugs/show_bug.cgi?id=31702.
3511 
3512  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3513  return !CFP->getValueAPF().isNegative() ||
3514  (!SignBitOnly && CFP->getValueAPF().isZero());
3515  }
3516 
3517  // Handle vector of constants.
3518  if (auto *CV = dyn_cast<Constant>(V)) {
3519  if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
3520  unsigned NumElts = CVFVTy->getNumElements();
3521  for (unsigned i = 0; i != NumElts; ++i) {
3522  auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
3523  if (!CFP)
3524  return false;
3525  if (CFP->getValueAPF().isNegative() &&
3526  (SignBitOnly || !CFP->getValueAPF().isZero()))
3527  return false;
3528  }
3529 
3530  // All non-negative ConstantFPs.
3531  return true;
3532  }
3533  }
3534 
3536  return false;
3537 
3538  const Operator *I = dyn_cast<Operator>(V);
3539  if (!I)
3540  return false;
3541 
3542  switch (I->getOpcode()) {
3543  default:
3544  break;
3545  // Unsigned integers are always nonnegative.
3546  case Instruction::UIToFP:
3547  return true;
3548  case Instruction::FMul:
3549  case Instruction::FDiv:
3550  // X * X is always non-negative or a NaN.
3551  // X / X is always exactly 1.0 or a NaN.
3552  if (I->getOperand(0) == I->getOperand(1) &&
3553  (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3554  return true;
3555 
3557  case Instruction::FAdd:
3558  case Instruction::FRem:
3559  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3560  Depth + 1) &&
3561  cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3562  Depth + 1);
3563  case Instruction::Select:
3564  return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3565  Depth + 1) &&
3566  cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3567  Depth + 1);
3568  case Instruction::FPExt:
3569  case Instruction::FPTrunc:
3570  // Widening/narrowing never change sign.
3571  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3572  Depth + 1);
3573  case Instruction::ExtractElement:
3574  // Look through extract element. At the moment we keep this simple and skip
3575  // tracking the specific element. But at least we might find information
3576  // valid for all elements of the vector.
3577  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3578  Depth + 1);
3579  case Instruction::Call:
3580  const auto *CI = cast<CallInst>(I);
3581  Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI);
3582  switch (IID) {
3583  default:
3584  break;
3585  case Intrinsic::maxnum: {
3586  Value *V0 = I->getOperand(0), *V1 = I->getOperand(1);
3587  auto isPositiveNum = [&](Value *V) {
3588  if (SignBitOnly) {
3589  // With SignBitOnly, this is tricky because the result of
3590  // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is
3591  // a constant strictly greater than 0.0.
3592  const APFloat *C;
3593  return match(V, m_APFloat(C)) &&
3594  *C > APFloat::getZero(C->getSemantics());
3595  }
3596 
3597  // -0.0 compares equal to 0.0, so if this operand is at least -0.0,
3598  // maxnum can't be ordered-less-than-zero.
3599  return isKnownNeverNaN(V, TLI) &&
3600  cannotBeOrderedLessThanZeroImpl(V, TLI, false, Depth + 1);
3601  };
3602 
3603  // TODO: This could be improved. We could also check that neither operand
3604  // has its sign bit set (and at least 1 is not-NAN?).
3605  return isPositiveNum(V0) || isPositiveNum(V1);
3606  }
3607 
3608  case Intrinsic::maximum:
3609  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3610  Depth + 1) ||
3611  cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3612  Depth + 1);
3613  case Intrinsic::minnum:
3614  case Intrinsic::minimum:
3615  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3616  Depth + 1) &&
3617  cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3618  Depth + 1);
3619  case Intrinsic::exp:
3620  case Intrinsic::exp2:
3621  case Intrinsic::fabs:
3622  return true;
3623 
3624  case Intrinsic::sqrt:
3625  // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3626  if (!SignBitOnly)
3627  return true;
3628  return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3629  CannotBeNegativeZero(CI->getOperand(0), TLI));
3630 
3631  case Intrinsic::powi:
3632  if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
3633  // powi(x,n) is non-negative if n is even.
3634  if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
3635  return true;
3636  }
3637  // TODO: This is not correct. Given that exp is an integer, here are the
3638  // ways that pow can return a negative value:
3639  //
3640  // pow(x, exp) --> negative if exp is odd and x is negative.
3641  // pow(-0, exp) --> -inf if exp is negative odd.
3642  // pow(-0, exp) --> -0 if exp is positive odd.
3643  // pow(-inf, exp) --> -0 if exp is negative odd.
3644  // pow(-inf, exp) --> -inf if exp is positive odd.
3645  //
3646  // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3647  // but we must return false if x == -0. Unfortunately we do not currently
3648  // have a way of expressing this constraint. See details in
3649  // https://llvm.org/bugs/show_bug.cgi?id=31702.
3650  return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3651  Depth + 1);
3652 
3653  case Intrinsic::fma:
3654  case Intrinsic::fmuladd:
3655  // x*x+y is non-negative if y is non-negative.
3656  return I->getOperand(0) == I->getOperand(1) &&
3657  (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3658  cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3659  Depth + 1);
3660  }
3661  break;
3662  }
3663  return false;
3664 }
3665 
3667  const TargetLibraryInfo *TLI) {
3668  return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3669 }
3670 
3672  return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3673 }
3674 
3676  unsigned Depth) {
3677  assert(V->getType()->isFPOrFPVectorTy() && "Querying for Inf on non-FP type");
3678 
3679  // If we're told that infinities won't happen, assume they won't.
3680  if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3681  if (FPMathOp->hasNoInfs())
3682  return true;
3683 
3684  // Handle scalar constants.
3685  if (auto *CFP = dyn_cast<ConstantFP>(V))
3686  return !CFP->isInfinity();
3687 
3689  return false;
3690 
3691  if (auto *Inst = dyn_cast<Instruction>(V)) {
3692  switch (Inst->getOpcode()) {
3693  case Instruction::Select: {
3694  return isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1) &&
3695  isKnownNeverInfinity(Inst->getOperand(2), TLI, Depth + 1);
3696  }
3697  case Instruction::SIToFP:
3698  case Instruction::UIToFP: {
3699  // Get width of largest magnitude integer (remove a bit if signed).
3700  // This still works for a signed minimum value because the largest FP
3701  // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
3702  int IntSize = Inst->getOperand(0)->getType()->getScalarSizeInBits();
3703  if (Inst->getOpcode() == Instruction::SIToFP)
3704  --IntSize;
3705 
3706  // If the exponent of the largest finite FP value can hold the largest
3707  // integer, the result of the cast must be finite.
3708  Type *FPTy = Inst->getType()->getScalarType();
3709  return ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize;
3710  }
3711  default:
3712  break;
3713  }
3714  }
3715 
3716  // try to handle fixed width vector constants
3717  auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3718  if (VFVTy && isa<Constant>(V)) {
3719  // For vectors, verify that each element is not infinity.
3720  unsigned NumElts = VFVTy->getNumElements();
3721  for (unsigned i = 0; i != NumElts; ++i) {
3722  Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3723  if (!Elt)
3724  return false;
3725  if (isa<UndefValue>(Elt))
3726  continue;
3727  auto *CElt = dyn_cast<ConstantFP>(Elt);
3728  if (!CElt || CElt->isInfinity())
3729  return false;
3730  }
3731  // All elements were confirmed non-infinity or undefined.
3732  return true;
3733  }
3734 
3735  // was not able to prove that V never contains infinity
3736  return false;
3737 }
3738 
3740  unsigned Depth) {
3741  assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
3742 
3743  // If we're told that NaNs won't happen, assume they won't.
3744  if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3745  if (FPMathOp->hasNoNaNs())
3746  return true;
3747 
3748  // Handle scalar constants.
3749  if (auto *CFP = dyn_cast<ConstantFP>(V))
3750  return !CFP->isNaN();
3751 
3753  return false;
3754 
3755  if (auto *Inst = dyn_cast<Instruction>(V)) {
3756  switch (Inst->getOpcode()) {
3757  case Instruction::FAdd:
3758  case Instruction::FSub:
3759  // Adding positive and negative infinity produces NaN.
3760  return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3761  isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3762  (isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) ||
3763  isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1));
3764 
3765  case Instruction::FMul:
3766  // Zero multiplied with infinity produces NaN.
3767  // FIXME: If neither side can be zero fmul never produces NaN.
3768  return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3769  isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) &&
3770  isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3771  isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1);
3772 
3773  case Instruction::FDiv:
3774  case Instruction::FRem:
3775  // FIXME: Only 0/0, Inf/Inf, Inf REM x and x REM 0 produce NaN.
3776  return false;
3777 
3778  case Instruction::Select: {
3779  return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3780  isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3781  }
3782  case Instruction::SIToFP:
3783  case Instruction::UIToFP:
3784  return true;
3785  case Instruction::FPTrunc:
3786  case Instruction::FPExt:
3787  return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3788  default:
3789  break;
3790  }
3791  }
3792 
3793  if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3794  switch (II->getIntrinsicID()) {
3795  case Intrinsic::canonicalize:
3796  case Intrinsic::fabs:
3797  case Intrinsic::copysign:
3798  case Intrinsic::exp:
3799  case Intrinsic::exp2:
3800  case Intrinsic::floor:
3801  case Intrinsic::ceil:
3802  case Intrinsic::trunc:
3803  case Intrinsic::rint:
3804  case Intrinsic::nearbyint:
3805  case Intrinsic::round:
3806  case Intrinsic::roundeven:
3807  return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3808  case Intrinsic::sqrt:
3809  return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3810  CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3811  case Intrinsic::minnum:
3812  case Intrinsic::maxnum:
3813  // If either operand is not NaN, the result is not NaN.
3814  return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3815  isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
3816  default:
3817  return false;
3818  }
3819  }
3820 
3821  // Try to handle fixed width vector constants
3822  auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3823  if (VFVTy && isa<Constant>(V)) {
3824  // For vectors, verify that each element is not NaN.
3825  unsigned NumElts = VFVTy->getNumElements();
3826  for (unsigned i = 0; i != NumElts; ++i) {
3827  Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3828  if (!Elt)
3829  return false;
3830  if (isa<UndefValue>(Elt))
3831  continue;
3832  auto *CElt = dyn_cast<ConstantFP>(Elt);
3833  if (!CElt || CElt->isNaN())
3834  return false;
3835  }
3836  // All elements were confirmed not-NaN or undefined.
3837  return true;
3838  }
3839 
3840  // Was not able to prove that V never contains NaN
3841  return false;
3842 }
3843 
3845 
3846  // All byte-wide stores are splatable, even of arbitrary variables.
3847  if (V->getType()->isIntegerTy(8))
3848  return V;
3849 
3850  LLVMContext &Ctx = V->getContext();
3851 
3852  // Undef don't care.
3853  auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3854  if (isa<UndefValue>(V))
3855  return UndefInt8;
3856 
3857  // Return Undef for zero-sized type.
3858  if (!DL.getTypeStoreSize(V->getType()).isNonZero())
3859  return UndefInt8;
3860 
3861  Constant *C = dyn_cast<Constant>(V);
3862  if (!C) {
3863  // Conceptually, we could handle things like:
3864  // %a = zext i8 %X to i16
3865  // %b = shl i16 %a, 8
3866  // %c = or i16 %a, %b
3867  // but until there is an example that actually needs this, it doesn't seem
3868  // worth worrying about.
3869  return nullptr;
3870  }
3871 
3872  // Handle 'null' ConstantArrayZero etc.
3873  if (C->isNullValue())
3875 
3876  // Constant floating-point values can be handled as integer values if the
3877  // corresponding integer value is "byteable". An important case is 0.0.
3878  if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3879  Type *Ty = nullptr;
3880  if (CFP->getType()->isHalfTy())
3881  Ty = Type::getInt16Ty(Ctx);
3882  else if (CFP->getType()->isFloatTy())
3883  Ty = Type::getInt32Ty(Ctx);
3884  else if (CFP->getType()->isDoubleTy())
3885  Ty = Type::getInt64Ty(Ctx);
3886  // Don't handle long double formats, which have strange constraints.
3887  return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3888  : nullptr;
3889  }
3890 
3891  // We can handle constant integers that are multiple of 8 bits.
3892  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
3893  if (CI->getBitWidth() % 8 == 0) {
3894  assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
3895  if (!CI->getValue().isSplat(8))
3896  return nullptr;
3897  return ConstantInt::get(Ctx, CI->getValue().trunc(8));
3898  }
3899  }
3900 
3901  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3902  if (CE->getOpcode() == Instruction::IntToPtr) {
3903  if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
3904  unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
3905  return isBytewiseValue(
3906  ConstantExpr::getIntegerCast(CE->getOperand(0),
3907  Type::getIntNTy(Ctx, BitWidth), false),
3908  DL);
3909  }
3910  }
3911  }
3912 
3913  auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3914  if (LHS == RHS)
3915  return LHS;
3916  if (!LHS || !RHS)
3917  return nullptr;
3918  if (LHS == UndefInt8)
3919  return RHS;
3920  if (RHS == UndefInt8)
3921  return LHS;
3922  return nullptr;
3923  };
3924 
3925  if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
3926  Value *Val = UndefInt8;
3927  for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
3928  if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
3929  return nullptr;
3930  return Val;
3931  }
3932 
3933  if (isa<ConstantAggregate>(C)) {
3934  Value *Val = UndefInt8;
3935  for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
3936  if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
3937  return nullptr;
3938  return Val;
3939  }
3940 
3941  // Don't try to handle the handful of other constants.
3942  return nullptr;
3943 }
3944 
3945 // This is the recursive version of BuildSubAggregate. It takes a few different
3946 // arguments. Idxs is the index within the nested struct From that we are
3947 // looking at now (which is of type IndexedType). IdxSkip is the number of
3948 // indices from Idxs that should be left out when inserting into the resulting
3949 // struct. To is the result struct built so far, new insertvalue instructions
3950 // build on that.
3951 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
3953  unsigned IdxSkip,
3954  Instruction *InsertBefore) {
3955  StructType *STy = dyn_cast<StructType>(IndexedType);
3956  if (STy) {
3957  // Save the original To argument so we can modify it
3958  Value *OrigTo = To;
3959  // General case, the type indexed by Idxs is a struct
3960  for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3961  // Process each struct element recursively
3962  Idxs.push_back(i);
3963  Value *PrevTo = To;
3964  To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
3965  InsertBefore);
3966  Idxs.pop_back();
3967  if (!To) {
3968  // Couldn't find any inserted value for this index? Cleanup
3969  while (PrevTo != OrigTo) {
3970  InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
3971  PrevTo = Del->getAggregateOperand();
3972  Del->eraseFromParent();
3973  }
3974  // Stop processing elements
3975  break;
3976  }
3977  }
3978  // If we successfully found a value for each of our subaggregates
3979  if (To)
3980  return To;
3981  }
3982  // Base case, the type indexed by SourceIdxs is not a struct, or not all of
3983  // the struct's elements had a value that was inserted directly. In the latter
3984  // case, perhaps we can't determine each of the subelements individually, but
3985  // we might be able to find the complete struct somewhere.
3986 
3987  // Find the value that is at that particular spot
3988  Value *V = FindInsertedValue(From, Idxs);
3989 
3990  if (!V)
3991  return nullptr;
3992 
3993  // Insert the value in the new (sub) aggregate
3994  return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3995  "tmp", InsertBefore);
3996 }
3997 
3998 // This helper takes a nested struct and extracts a part of it (which is again a
3999 // struct) into a new value. For example, given the struct:
4000 // { a, { b, { c, d }, e } }
4001 // and the indices "1, 1" this returns
4002 // { c, d }.
4003 //
4004 // It does this by inserting an insertvalue for each element in the resulting
4005 // struct, as opposed to just inserting a single struct. This will only work if
4006 // each of the elements of the substruct are known (ie, inserted into From by an
4007 // insertvalue instruction somewhere).
4008 //
4009 // All inserted insertvalue instructions are inserted before InsertBefore
4011  Instruction *InsertBefore) {
4012  assert(InsertBefore && "Must have someplace to insert!");
4013  Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
4014  idx_range);
4015  Value *To = UndefValue::get(IndexedType);
4016  SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
4017  unsigned IdxSkip = Idxs.size();
4018 
4019  return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
4020 }
4021 
4022 /// Given an aggregate and a sequence of indices, see if the scalar value
4023 /// indexed is already around as a register, for example if it was inserted
4024 /// directly into the aggregate.
4025 ///
4026 /// If InsertBefore is not null, this function will duplicate (modified)
4027 /// insertvalues when a part of a nested struct is extracted.
4029  Instruction *InsertBefore) {
4030  // Nothing to index? Just return V then (this is useful at the end of our
4031  // recursion).
4032  if (idx_range.empty())
4033  return V;
4034  // We have indices, so V should have an indexable type.
4035  assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
4036  "Not looking at a struct or array?");
4037  assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
4038  "Invalid indices for type?");
4039 
4040  if (Constant *C = dyn_cast<Constant>(V)) {
4041  C = C->getAggregateElement(idx_range[0]);
4042  if (!C) return nullptr;
4043  return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
4044  }
4045 
4046  if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
4047  // Loop the indices for the insertvalue instruction in parallel with the
4048  // requested indices
4049  const unsigned *req_idx = idx_range.begin();
4050  for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
4051  i != e; ++i, ++req_idx) {
4052  if (req_idx == idx_range.end()) {
4053  // We can't handle this without inserting insertvalues
4054  if (!InsertBefore)
4055  return nullptr;
4056 
4057  // The requested index identifies a part of a nested aggregate. Handle
4058  // this specially. For example,
4059  // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
4060  // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
4061  // %C = extractvalue {i32, { i32, i32 } } %B, 1
4062  // This can be changed into
4063  // %A = insertvalue {i32, i32 } undef, i32 10, 0
4064  // %C = insertvalue {i32, i32 } %A, i32 11, 1
4065  // which allows the unused 0,0 element from the nested struct to be
4066  // removed.
4067  return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
4068  InsertBefore);
4069  }
4070 
4071  // This insert value inserts something else than what we are looking for.
4072  // See if the (aggregate) value inserted into has the value we are
4073  // looking for, then.
4074  if (*req_idx != *i)
4075  return FindInsertedValue(I->getAggregateOperand(), idx_range,
4076  InsertBefore);
4077  }
4078  // If we end up here, the indices of the insertvalue match with those
4079  // requested (though possibly only partially). Now we recursively look at
4080  // the inserted value, passing any remaining indices.
4081  return FindInsertedValue(I->getInsertedValueOperand(),
4082  makeArrayRef(req_idx, idx_range.end()),
4083  InsertBefore);
4084  }
4085 
4086  if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
4087  // If we're extracting a value from an aggregate that was extracted from
4088  // something else, we can extract from that something else directly instead.
4089  // However, we will need to chain I's indices with the requested indices.
4090 
4091  // Calculate the number of indices required
4092  unsigned size = I->getNumIndices() + idx_range.size();
4093  // Allocate some space to put the new indices in
4095  Idxs.reserve(size);
4096  // Add indices from the extract value instruction
4097  Idxs.append(I->idx_begin(), I->idx_end());
4098 
4099  // Add requested indices
4100  Idxs.append(idx_range.begin(), idx_range.end());
4101 
4102  assert(Idxs.size() == size
4103  && "Number of indices added not correct?");
4104 
4105  return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
4106  }
4107  // Otherwise, we don't know (such as, extracting from a function return value
4108  // or load instruction)
4109  return nullptr;
4110 }
4111 
4113  unsigned CharSize) {
4114  // Make sure the GEP has exactly three arguments.
4115  if (GEP->getNumOperands() != 3)
4116  return false;
4117 
4118  // Make sure the index-ee is a pointer to array of \p CharSize integers.
4119  // CharSize.
4120  ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
4121  if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
4122  return false;
4123 
4124  // Check to make sure that the first operand of the GEP is an integer and
4125  // has value 0 so that we are sure we're indexing into the initializer.
4126  const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
4127  if (!FirstIdx || !FirstIdx->isZero())
4128  return false;
4129 
4130  return true;
4131 }
4132 
4134  ConstantDataArraySlice &Slice,
4135  unsigned ElementSize, uint64_t Offset) {
4136  assert(V);
4137 
4138  // Look through bitcast instructions and geps.
4139  V = V->stripPointerCasts();
4140 
4141  // If the value is a GEP instruction or constant expression, treat it as an
4142  // offset.
4143  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
4144  // The GEP operator should be based on a pointer to string constant, and is
4145  // indexing into the string constant.
4146  if (!isGEPBasedOnPointerToString(GEP, ElementSize))
4147  return false;
4148 
4149  // If the second index isn't a ConstantInt, then this is a variable index
4150  // into the array. If this occurs, we can't say anything meaningful about
4151  // the string.
4152  uint64_t StartIdx = 0;
4153  if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
4154  StartIdx = CI->getZExtValue();
4155  else
4156  return false;
4157  return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
4158  StartIdx + Offset);
4159  }
4160 
4161  // The GEP instruction, constant or instruction, must reference a global
4162  // variable that is a constant and is initialized. The referenced constant
4163  // initializer is the array that we'll use for optimization.
4164  const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
4165  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
4166  return false;
4167 
4168  const ConstantDataArray *Array;
4169  ArrayType *ArrayTy;
4170  if (GV->getInitializer()->isNullValue()) {
4171  Type *GVTy = GV->getValueType();
4172  if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
4173  // A zeroinitializer for the array; there is no ConstantDataArray.
4174  Array = nullptr;
4175  } else {
4176  const DataLayout &DL = GV->getParent()->getDataLayout();
4177  uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedSize();
4178  uint64_t Length = SizeInBytes / (ElementSize / 8);
4179  if (Length <= Offset)
4180  return false;
4181 
4182  Slice.Array = nullptr;
4183  Slice.Offset = 0;
4184  Slice.Length = Length - Offset;
4185  return true;
4186  }
4187  } else {
4188  // This must be a ConstantDataArray.
4189  Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
4190  if (!Array)
4191  return false;
4192  ArrayTy = Array->getType();
4193  }
4194  if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
4195  return false;
4196 
4197  uint64_t NumElts = ArrayTy->getArrayNumElements();
4198  if (Offset > NumElts)
4199  return false;
4200 
4201  Slice.Array = Array;
4202  Slice.Offset = Offset;
4203  Slice.Length = NumElts - Offset;
4204  return true;
4205 }
4206 
4207 /// This function computes the length of a null-terminated C string pointed to
4208 /// by V. If successful, it returns true and returns the string in Str.
4209 /// If unsuccessful, it returns false.
4211  uint64_t Offset, bool TrimAtNul) {
4212  ConstantDataArraySlice Slice;
4213  if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
4214  return false;
4215 
4216  if (Slice.Array == nullptr) {
4217  if (TrimAtNul) {
4218  Str = StringRef();
4219  return true;
4220  }
4221  if (Slice.Length == 1) {
4222  Str = StringRef("", 1);
4223  return true;
4224  }
4225  // We cannot instantiate a StringRef as we do not have an appropriate string
4226  // of 0s at hand.
4227  return false;
4228  }
4229 
4230  // Start out with the entire array in the StringRef.
4231  Str = Slice.Array->getAsString();
4232  // Skip over 'offset' bytes.
4233  Str = Str.substr(Slice.Offset);
4234 
4235  if (TrimAtNul) {
4236  // Trim off the \0 and anything after it. If the array is not nul
4237  // terminated, we just return the whole end of string. The client may know
4238  // some other way that the string is length-bound.
4239  Str = Str.substr(0, Str.find('\0'));
4240  }
4241  return true;
4242 }
4243 
4244 // These next two are very similar to the above, but also look through PHI
4245 // nodes.
4246 // TODO: See if we can integrate these two together.
4247 
4248 /// If we can compute the length of the string pointed to by
4249 /// the specified pointer, return 'len+1'. If we can't, return 0.
4252  unsigned CharSize) {
4253  // Look through noop bitcast instructions.
4254  V = V->stripPointerCasts();
4255 
4256  // If this is a PHI node, there are two cases: either we have already seen it
4257  // or we haven't.
4258  if (const PHINode *PN = dyn_cast<PHINode>(V)) {
4259  if (!PHIs.insert(PN).second)
4260  return ~0ULL; // already in the set.
4261 
4262  // If it was new, see if all the input strings are the same length.
4263  uint64_t LenSoFar = ~0ULL;
4264  for (Value *IncValue : PN->incoming_values()) {
4265  uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
4266  if (Len == 0) return 0; // Unknown length -> unknown.
4267 
4268  if (Len == ~0ULL) continue;
4269 
4270  if (Len != LenSoFar && LenSoFar != ~0ULL)
4271  return 0; // Disagree -> unknown.
4272  LenSoFar = Len;
4273  }
4274 
4275  // Success, all agree.
4276  return LenSoFar;
4277  }
4278 
4279  // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
4280  if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
4281  uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
4282  if (Len1 == 0) return 0;
4283  uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
4284  if (Len2 == 0) return 0;
4285  if (Len1 == ~0ULL) return Len2;
4286  if (Len2 == ~0ULL) return Len1;
4287  if (Len1 != Len2) return 0;
4288  return Len1;
4289  }
4290 
4291  // Otherwise, see if we can read the string.
4292  ConstantDataArraySlice Slice;
4293  if (!getConstantDataArrayInfo(V, Slice, CharSize))
4294  return 0;
4295 
4296  if (Slice.Array == nullptr)
4297  return 1;
4298 
4299  // Search for nul characters
4300  unsigned NullIndex = 0;
4301  for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
4302  if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
4303  break;
4304  }
4305 
4306  return NullIndex + 1;
4307 }
4308 
4309 /// If we can compute the length of the string pointed to by
4310 /// the specified pointer, return 'len+1'. If we can't, return 0.
4311 uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
4312  if (!V->getType()->isPointerTy())
4313  return 0;
4314 
4316  uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
4317  // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
4318  // an empty string as a length.
4319  return Len == ~0ULL ? 1 : Len;
4320 }
4321 
4322 const Value *
4324  bool MustPreserveNullness) {
4325  assert(Call &&
4326  "getArgumentAliasingToReturnedPointer only works on nonnull calls");
4327  if (const Value *RV = Call->getReturnedArgOperand())
4328  return RV;
4329  // This can be used only as a aliasing property.
4331  Call, MustPreserveNullness))
4332  return Call->getArgOperand(0);
4333  return nullptr;
4334 }
4335 
4337  const CallBase *Call, bool MustPreserveNullness) {
4338  switch (Call->getIntrinsicID()) {
4339  case Intrinsic::launder_invariant_group:
4340  case Intrinsic::strip_invariant_group:
4341  case Intrinsic::aarch64_irg:
4342  case Intrinsic::aarch64_tagp:
4343  return true;
4344  case Intrinsic::ptrmask:
4345  return !MustPreserveNullness;
4346  default:
4347  return false;
4348  }
4349 }
4350 
4351 /// \p PN defines a loop-variant pointer to an object. Check if the
4352 /// previous iteration of the loop was referring to the same object as \p PN.
4354  const LoopInfo *LI) {
4355  // Find the loop-defined value.
4356  Loop *L = LI->getLoopFor(PN->getParent());
4357  if (PN->getNumIncomingValues() != 2)
4358  return true;
4359 
4360  // Find the value from previous iteration.
4361  auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
4362  if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4363  PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
4364  if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4365  return true;
4366 
4367  // If a new pointer is loaded in the loop, the pointer references a different
4368  // object in every iteration. E.g.:
4369  // for (i)
4370  // int *p = a[i];
4371  // ...
4372  if (auto *Load = dyn_cast<LoadInst>(PrevValue))
4373  if (!L->isLoopInvariant(Load->getPointerOperand()))
4374  return false;
4375  return true;
4376 }
4377 
4378 const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
4379  if (!V->getType()->isPointerTy())
4380  return V;
4381  for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
4382  if (auto *GEP = dyn_cast<GEPOperator>(V)) {
4383  V = GEP->getPointerOperand();
4384  } else if (Operator::getOpcode(V) == Instruction::BitCast ||
4385  Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
4386  V = cast<Operator>(V)->getOperand(0);
4387  if (!V->getType()->isPointerTy())
4388  return V;
4389  } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
4390  if (GA->isInterposable())
4391  return V;
4392  V = GA->getAliasee();
4393  } else {
4394  if (auto *PHI = dyn_cast<PHINode>(V)) {
4395  // Look through single-arg phi nodes created by LCSSA.
4396  if (PHI->getNumIncomingValues() == 1) {
4397  V = PHI->getIncomingValue(0);
4398  continue;
4399  }
4400  } else if (auto *Call = dyn_cast<CallBase>(V)) {
4401  // CaptureTracking can know about special capturing properties of some
4402  // intrinsics like launder.invariant.group, that can't be expressed with
4403  // the attributes, but have properties like returning aliasing pointer.
4404  // Because some analysis may assume that nocaptured pointer is not
4405  // returned from some special intrinsic (because function would have to
4406  // be marked with returns attribute), it is crucial to use this function
4407  // because it should be in sync with CaptureTracking. Not using it may
4408  // cause weird miscompilations where 2 aliasing pointers are assumed to
4409  // noalias.
4410  if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
4411  V = RP;
4412  continue;
4413  }
4414  }
4415 
4416  return V;
4417  }
4418  assert(V->getType()->isPointerTy() && "Unexpected operand type!");
4419  }
4420  return V;
4421 }
4422 
4425  LoopInfo *LI, unsigned MaxLookup) {
4428  Worklist.push_back(V);
4429  do {
4430  const Value *P = Worklist.pop_back_val();
4431  P = getUnderlyingObject(P, MaxLookup);
4432 
4433  if (!Visited.insert(P).second)
4434  continue;
4435 
4436  if (auto *SI = dyn_cast<SelectInst>(P)) {
4437  Worklist.push_back(SI->getTrueValue());
4438  Worklist.push_back(SI->getFalseValue());
4439  continue;
4440  }
4441 
4442  if (auto *PN = dyn_cast<PHINode>(P)) {
4443  // If this PHI changes the underlying object in every iteration of the
4444  // loop, don't look through it. Consider:
4445  // int **A;
4446  // for (i) {
4447  // Prev = Curr; // Prev = PHI (Prev_0, Curr)
4448  // Curr = A[i];
4449  // *Prev, *Curr;
4450  //
4451  // Prev is tracking Curr one iteration behind so they refer to different
4452  // underlying objects.
4453  if (!LI || !LI->isLoopHeader(PN->getParent()) ||
4455  append_range(Worklist, PN->incoming_values());
4456  continue;
4457  }
4458 
4459  Objects.push_back(P);
4460  } while (!Worklist.empty());
4461 }
4462 
4463 /// This is the function that does the work of looking through basic
4464 /// ptrtoint+arithmetic+inttoptr sequences.
4465 static const Value *getUnderlyingObjectFromInt(const Value *V) {
4466  do {
4467  if (const Operator *U = dyn_cast<Operator>(V)) {
4468  // If we find a ptrtoint, we can transfer control back to the
4469  // regular getUnderlyingObjectFromInt.
4470  if (U->getOpcode() == Instruction::PtrToInt)
4471  return U->getOperand(0);
4472  // If we find an add of a constant, a multiplied value, or a phi, it's
4473  // likely that the other operand will lead us to the base
4474  // object. We don't have to worry about the case where the
4475  // object address is somehow being computed by the multiply,
4476  // because our callers only care when the result is an
4477  // identifiable object.
4478  if (U->getOpcode() != Instruction::Add ||
4479  (!isa<ConstantInt>(U->getOperand(1)) &&
4480  Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
4481  !isa<PHINode>(U->getOperand(1))))
4482  return V;
4483  V = U->getOperand(0);
4484  } else {
4485  return V;
4486  }
4487  assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
4488  } while (true);
4489 }
4490 
4491 /// This is a wrapper around getUnderlyingObjects and adds support for basic
4492 /// ptrtoint+arithmetic+inttoptr sequences.
4493 /// It returns false if unidentified object is found in getUnderlyingObjects.
4495  SmallVectorImpl<Value *> &Objects) {
4497  SmallVector<const Value *, 4> Working(1, V);
4498  do {
4499  V = Working.pop_back_val();
4500 
4502  getUnderlyingObjects(V, Objs);
4503 
4504  for (const Value *V : Objs) {
4505  if (!Visited.insert(V).second)
4506  continue;
4507  if (Operator::getOpcode(V) == Instruction::IntToPtr) {
4508  const Value *O =
4509  getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
4510  if (O->getType()->isPointerTy()) {
4511  Working.push_back(O);
4512  continue;
4513  }
4514  }
4515  // If getUnderlyingObjects fails to find an identifiable object,
4516  // getUnderlyingObjectsForCodeGen also fails for safety.
4517  if (!isIdentifiedObject(V)) {
4518  Objects.clear();
4519  return false;
4520  }
4521  Objects.push_back(const_cast<Value *>(V));
4522  }
4523  } while (!Working.empty());
4524  return true;
4525 }
4526 
4528  AllocaInst *Result = nullptr;
4529  SmallPtrSet<Value *, 4> Visited;
4530  SmallVector<Value *, 4> Worklist;
4531 
4532  auto AddWork = [&](Value *V) {
4533  if (Visited.insert(V).second)
4534  Worklist.push_back(V);
4535  };
4536 
4537  AddWork(V);
4538  do {
4539  V = Worklist.pop_back_val();
4540  assert(Visited.count(V));
4541 
4542  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
4543  if (Result && Result != AI)
4544  return nullptr;
4545  Result = AI;
4546  } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
4547  AddWork(CI->getOperand(0));
4548  } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
4549  for (Value *IncValue : PN->incoming_values())
4550  AddWork(IncValue);
4551  } else if (auto *SI = dyn_cast<SelectInst>(V)) {
4552  AddWork(SI->getTrueValue());
4553  AddWork(SI->getFalseValue());
4554  } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
4555  if (OffsetZero && !GEP->hasAllZeroIndices())
4556  return nullptr;
4557  AddWork(GEP->getPointerOperand());
4558  } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
4559  Value *Returned = CB->getReturnedArgOperand();
4560  if (Returned)
4561  AddWork(Returned);
4562  else
4563  return nullptr;
4564  } else {
4565  return nullptr;
4566  }
4567  } while (!Worklist.empty());
4568 
4569  return Result;
4570 }
4571 
4573  const Value *V, bool AllowLifetime, bool AllowDroppable) {
4574  for (const User *U : V->users()) {
4575  const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4576  if (!II)
4577  return false;
4578 
4579  if (AllowLifetime && II->isLifetimeStartOrEnd())
4580  continue;
4581 
4582  if (AllowDroppable && II->isDroppable())
4583  continue;
4584 
4585  return false;
4586  }
4587  return true;
4588 }
4589 
4592  V, /* AllowLifetime */ true, /* AllowDroppable */ false);
4593 }
4596  V, /* AllowLifetime */ true, /* AllowDroppable */ true);
4597 }
4598 
4600  if (!LI.isUnordered())
4601  return true;
4602  const Function &F = *LI.getFunction();
4603  // Speculative load may create a race that did not exist in the source.
4604  return F.hasFnAttribute(Attribute::SanitizeThread) ||
4605  // Speculative load may load data from dirty regions.
4606  F.hasFnAttribute(Attribute::SanitizeAddress) ||
4607  F.hasFnAttribute(Attribute::SanitizeHWAddress);
4608 }
4609 
4610 
4612  const Instruction *CtxI,
4613  const DominatorTree *DT,
4614  const TargetLibraryInfo *TLI) {
4615  const Operator *Inst = dyn_cast<Operator>(V);
4616  if (!Inst)
4617  return false;
4618 
4619  for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
4620  if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
4621  if (C->canTrap())
4622  return false;
4623 
4624  switch (Inst->getOpcode()) {
4625  default:
4626  return true;
4627  case Instruction::UDiv:
4628  case Instruction::URem: {
4629  // x / y is undefined if y == 0.
4630  const APInt *V;
4631  if (match(Inst->getOperand(1), m_APInt(V)))
4632  return *V != 0;
4633  return false;
4634  }
4635  case Instruction::SDiv:
4636  case Instruction::SRem: {
4637  // x / y is undefined if y == 0 or x == INT_MIN and y == -1
4638  const APInt *Numerator, *Denominator;
4639  if (!match(Inst->getOperand(1), m_APInt(Denominator)))
4640  return false;
4641  // We cannot hoist this division if the denominator is 0.
4642  if (*Denominator == 0)
4643  return false;
4644  // It's safe to hoist if the denominator is not 0 or -1.
4645  if (!Denominator->isAllOnes())
4646  return true;
4647  // At this point we know that the denominator is -1. It is safe to hoist as
4648  // long we know that the numerator is not INT_MIN.
4649  if (match(Inst->getOperand(0), m_APInt(Numerator)))
4650  return !Numerator->isMinSignedValue();
4651  // The numerator *might* be MinSignedValue.
4652  return false;
4653  }
4654  case Instruction::Load: {
4655  const LoadInst *LI = cast<LoadInst>(Inst);
4656  if (mustSuppressSpeculation(*LI))
4657  return false;
4658  const DataLayout &DL = LI->getModule()->getDataLayout();
4660  LI->getPointerOperand(), LI->getType(), MaybeAlign(LI->getAlignment()),
4661  DL, CtxI, DT, TLI);
4662  }
4663  case Instruction::Call: {
4664  auto *CI = cast<const CallInst>(Inst);
4665  const Function *Callee = CI->getCalledFunction();
4666 
4667  // The called function could have undefined behavior or side-effects, even
4668  // if marked readnone nounwind.
4669  return Callee && Callee->isSpeculatable();
4670  }
4671  case Instruction::VAArg:
4672  case Instruction::Alloca:
4673  case Instruction::Invoke:
4674  case Instruction::CallBr:
4675  case Instruction::PHI:
4676  case Instruction::Store:
4677  case Instruction::Ret:
4678  case Instruction::Br:
4679  case Instruction::IndirectBr:
4680  case Instruction::Switch:
4681  case Instruction::Unreachable:
4682  case Instruction::Fence:
4683  case Instruction::AtomicRMW:
4684  case Instruction::AtomicCmpXchg:
4685  case Instruction::LandingPad:
4686  case Instruction::Resume:
4687  case Instruction::CatchSwitch:
4688  case Instruction::CatchPad:
4689  case Instruction::CatchRet:
4690  case Instruction::CleanupPad:
4691  case Instruction::CleanupRet:
4692  return false; // Misc instructions which have effects
4693  }
4694 }
4695 
4697  return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
4698 }
4699 
4700 /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
4702  switch (OR) {
4711  }
4712  llvm_unreachable("Unknown OverflowResult");
4713 }
4714 
4715 /// Combine constant ranges from computeConstantRange() and computeKnownBits().
4717  const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4718  AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4719  OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4720  KnownBits Known = computeKnownBits(
4721  V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4722  ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4723  ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4726  return CR1.intersectWith(CR2, RangeType);
4727 }
4728 
4730  const Value *LHS, const Value *RHS, const DataLayout &DL,
4731  AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4732  bool UseInstrInfo) {
4733  KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4734  nullptr, UseInstrInfo);
4735  KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4736  nullptr, UseInstrInfo);
4737  ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4738  ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4739  return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
4740 }
4741 
4744  const DataLayout &DL, AssumptionCache *AC,
4745  const Instruction *CxtI,
4746  const DominatorTree *DT, bool UseInstrInfo) {
4747  // Multiplying n * m significant bits yields a result of n + m significant
4748  // bits. If the total number of significant bits does not exceed the
4749  // result bit width (minus 1), there is no overflow.
4750  // This means if we have enough leading sign bits in the operands
4751  // we can guarantee that the result does not overflow.
4752  // Ref: "Hacker's Delight" by Henry Warren
4753  unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4754 
4755  // Note that underestimating the number of sign bits gives a more
4756  // conservative answer.
4757  unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4758  ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4759 
4760  // First handle the easy case: if we have enough sign bits there's
4761  // definitely no overflow.
4762  if (SignBits > BitWidth + 1)
4764 
4765  // There are two ambiguous cases where there can be no overflow:
4766  // SignBits == BitWidth + 1 and
4767  // SignBits == BitWidth
4768  // The second case is difficult to check, therefore we only handle the
4769  // first case.
4770  if (SignBits == BitWidth + 1) {
4771  // It overflows only when both arguments are negative and the true
4772  // product is exactly the minimum negative number.
4773  // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4774  // For simplicity we just check if at least one side is not negative.
4775  KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4776  nullptr, UseInstrInfo);
4777  KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4778  nullptr, UseInstrInfo);
4779  if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4781  }
4783 }
4784 
4786  const Value *LHS, const Value *RHS, const DataLayout &DL,
4787  AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4788  bool UseInstrInfo) {
4790  LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4791  nullptr, UseInstrInfo);
4793  RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4794  nullptr, UseInstrInfo);
4795  return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
4796 }
4797 
4799  const Value *RHS,
4800  const AddOperator *Add,
4801  const DataLayout &DL,
4802  AssumptionCache *AC,
4803  const Instruction *CxtI,
4804  const DominatorTree *DT) {
4805  if (Add && Add->hasNoSignedWrap()) {
4807  }
4808 
4809  // If LHS and RHS each have at least two sign bits, the addition will look
4810  // like
4811  //
4812  // XX..... +
4813  // YY.....
4814  //
4815  // If the carry into the most significant position is 0, X and Y can't both
4816  // be 1 and therefore the carry out of the addition is also 0.
4817  //
4818  // If the carry into the most significant position is 1, X and Y can't both
4819  // be 0 and therefore the carry out of the addition is also 1.
4820  //
4821  // Since the carry into the most significant position is always equal to
4822  // the carry out of the addition, there is no signed overflow.
4823  if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4824  ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4826 
4828  LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4830  RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4831  OverflowResult OR =
4832  mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4834  return OR;
4835 
4836  // The remaining code needs Add to be available. Early returns if not so.
4837  if (!Add)
4839 
4840  // If the sign of Add is the same as at least one of the operands, this add
4841  // CANNOT overflow. If this can be determined from the known bits of the
4842  // operands the above signedAddMayOverflow() check will have already done so.
4843  // The only other way to improve on the known bits is from an assumption, so
4844  // call computeKnownBitsFromAssume() directly.
4845  bool LHSOrRHSKnownNonNegative =
4846  (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
4847  bool LHSOrRHSKnownNegative =
4848  (LHSRange.isAllNegative() || RHSRange.isAllNegative());
4849  if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4850  KnownBits AddKnown(LHSRange.getBitWidth());
4852  Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
4853  if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4854  (AddKnown.isNegative() && LHSOrRHSKnownNegative))
4856  }
4857 
4859 }
4860 
4862  const Value *RHS,
4863  const DataLayout &DL,
4864  AssumptionCache *AC,
4865  const Instruction *CxtI,
4866  const DominatorTree *DT) {
4867  // Checking for conditions implied by dominating conditions may be expensive.
4868  // Limit it to usub_with_overflow calls for now.
4869  if (match(CxtI,
4870  m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value())))
4871  if (auto C =
4872  isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) {
4873  if (*C)
4876  }
4878  LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4880  RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4881  return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
4882 }
4883 
4885  const Value *RHS,
4886  const DataLayout &DL,
4887  AssumptionCache *AC,
4888  const Instruction *CxtI,
4889  const DominatorTree *DT) {
4890  // If LHS and RHS each have at least two sign bits, the subtraction
4891  // cannot overflow.
4892  if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4893  ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4895 
4897  LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4899  RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4900  return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
4901 }
4902 
4904  const DominatorTree &DT) {
4905  SmallVector<const BranchInst *, 2> GuardingBranches;
4907 
4908  for (const User *U : WO->users()) {
4909  if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4910  assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4911 
4912  if (EVI->getIndices()[0] == 0)
4913  Results.push_back(EVI);
4914  else {
4915  assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4916 
4917  for (const auto *U : EVI->users())
4918  if (const auto *B = dyn_cast<BranchInst>(U)) {
4919  assert(B->isConditional() && "How else is it using an i1?");
4920  GuardingBranches.push_back(B);
4921  }
4922  }
4923  } else {
4924  // We are using the aggregate directly in a way we don't want to analyze
4925  // here (storing it to a global, say).
4926  return false;
4927  }
4928  }
4929 
4930  auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
4931  BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4932  if (!NoWrapEdge.isSingleEdge())
4933  return false;
4934 
4935  // Check if all users of the add are provably no-wrap.
4936  for (const auto *Result : Results) {
4937  // If the extractvalue itself is not executed on overflow, the we don't
4938  // need to check each use separately, since domination is transitive.<