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