LLVM 24.0.0git
ConstraintElimination.cpp
Go to the documentation of this file.
1//===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
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// Eliminate conditions based on constraints collected from dominating
10// conditions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DebugInfo.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Module.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Pass.h"
41#include "llvm/Support/Debug.h"
46
47#include <optional>
48#include <string>
49
50using namespace llvm;
51using namespace PatternMatch;
52using namespace SCEVPatternMatch;
53
54#define DEBUG_TYPE "constraint-elimination"
55
56STATISTIC(NumCondsRemoved, "Number of instructions removed");
57DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
58 "Controls which conditions are eliminated");
59
61 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
62 cl::desc("Maximum number of rows to keep in constraint system"));
63
65 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
66 cl::desc("Dump IR to reproduce successful transformations."));
67
68static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
69static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
70
72 Instruction *UserI = cast<Instruction>(U.getUser());
73 if (auto *Phi = dyn_cast<PHINode>(UserI))
74 UserI = Phi->getIncomingBlock(U)->getTerminator();
75 return UserI;
76}
77
78/// Returns the closest program point dominating all uses of \p I.
80 DominatorTree &DT) {
81 Instruction *CommonDom = nullptr;
82 unsigned NumUses = 0;
83 for (Use &U : I.uses()) {
84 // Conservatively use original instruction, if there are too many uses.
85 if (++NumUses == 16)
86 return &I;
88 CommonDom =
89 CommonDom ? DT.findNearestCommonDominator(CommonDom, UserI) : UserI;
90 }
91 if (!CommonDom)
92 return &I;
93 // Uses in unreachable blocks are not in the dominator tree.
94 return DT.getNode(CommonDom->getParent()) ? CommonDom : &I;
95}
96
97namespace {
98using Entry = ConstraintSystem::Entry;
99using RowTy = ConstraintSystem::RowTy;
100
101/// Struct to express a condition of the form %Op0 Pred %Op1.
102struct ConditionTy {
103 CmpPredicate Pred;
104 Value *Op0 = nullptr;
105 Value *Op1 = nullptr;
106
107 ConditionTy() = default;
108 ConditionTy(CmpPredicate Pred, Value *Op0, Value *Op1)
109 : Pred(Pred), Op0(Op0), Op1(Op1) {}
110};
111
112/// Represents either
113/// * a condition that holds on entry to a block (=condition fact)
114/// * an assume (=assume fact)
115/// * a use of a compare instruction to simplify.
116/// It also tracks the Dominator DFS in and out numbers for each entry.
117struct FactOrCheck {
118 enum class EntryTy {
119 ConditionFact, /// A condition that holds on entry to a block.
120 InstFact, /// A fact that holds after Inst executed (e.g. an assume or
121 /// min/mix intrinsic.
122 InstCheck, /// An instruction to simplify (e.g. an overflow math
123 /// intrinsics) or whose flags may be strengthened.
124 UseCheck /// An use of a compare instruction to simplify.
125 };
126
127 union {
128 Instruction *Inst;
129 Use *U;
131 };
132
133 union {
134 /// A pre-condition that must hold for the current fact to be added to the
135 /// system. Only used by condition facts.
136 ConditionTy DoesHold;
137
138 /// Context instruction for the point where conditions are checked for
139 /// InstCheck simplifications.
140 Instruction *ContextInst;
141 };
142
143 unsigned NumIn;
144 unsigned NumOut;
145 EntryTy Ty;
146
147 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst,
148 Instruction *ContextInst = nullptr)
149 : Inst(Inst), ContextInst(ContextInst ? ContextInst : Inst),
150 NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), Ty(Ty) {}
151
152 FactOrCheck(DomTreeNode *DTN, Use *U)
153 : U(U), ContextInst(nullptr), NumIn(DTN->getDFSNumIn()),
154 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::UseCheck) {}
155
156 FactOrCheck(DomTreeNode *DTN, CmpPredicate Pred, Value *Op0, Value *Op1,
157 ConditionTy Precond = {})
158 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
159 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
160
161 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpPredicate Pred,
162 Value *Op0, Value *Op1,
163 ConditionTy Precond = {}) {
164 return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
165 }
166
167 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
168 return FactOrCheck(EntryTy::InstFact, DTN, Inst);
169 }
170
171 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
172 return FactOrCheck(DTN, U);
173 }
174
175 static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *I,
176 Instruction *ContextInst = nullptr) {
177 assert((ContextInst ? ContextInst : I)->getParent() == DTN->getBlock() &&
178 "anchoring instruction must be in DTN's block");
179 return FactOrCheck(EntryTy::InstCheck, DTN, I, ContextInst);
180 }
181
182 bool isCheck() const {
183 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
184 }
185
186 Instruction *getContextInst() const {
187 assert(!isConditionFact());
188 if (Ty == EntryTy::UseCheck)
189 return getContextInstForUse(*U);
190 return ContextInst;
191 }
192
193 Instruction *getInstructionToSimplify() const {
194 assert(isCheck());
195 if (Ty == EntryTy::InstCheck)
196 return Inst;
197 // The use may have been simplified to a constant already.
198 return dyn_cast<Instruction>(*U);
199 }
200
201 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
202};
203
204/// The senses in which an induction phi is monotonic, together with the
205/// direction it moves in.
206struct MonotonicInfo {
207 /// True if the phi steps by a negative constant.
208 bool Decreasing = false;
209 /// True if the phi is monotonic in the unsigned sense.
210 bool Unsigned = false;
211 /// True if the phi is monotonic in the signed sense.
212 bool Signed = false;
213};
214
215/// Keep state required to build worklist.
216struct State {
217 DominatorTree &DT;
218 LoopInfo &LI;
219 ScalarEvolution &SE;
220 TargetLibraryInfo &TLI;
222
223 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE,
224 TargetLibraryInfo &TLI)
225 : DT(DT), LI(LI), SE(SE), TLI(TLI) {}
226
227 /// Process block \p BB and add known facts to work-list.
228 void addInfoFor(BasicBlock &BB);
229
230 /// If \p BB is a loop header, bound each induction phi in it by its start
231 /// value.
232 void addBoundsForHeaderInductions(BasicBlock &BB);
233
234 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
235 /// controlling the loop header.
236 void addInfoForInductions(BasicBlock &BB);
237
238 /// Returns the direction the induction phi \p PN with backedge value \p Step
239 /// moves in, and the senses in which it is monotonic in that direction.
240 MonotonicInfo getMonotonicityInfo(PHINode &PN, Value *Step);
241
242 /// Returns true if we can add a known condition from BB to its successor
243 /// block Succ.
244 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
245 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
246 }
247};
248
249class ConstraintInfo;
250
251struct StackEntry {
252 unsigned NumIn;
253 unsigned NumOut;
254 bool IsSigned = false;
255 /// Variables that can be removed from the system once the stack entry gets
256 /// removed.
257 SmallVector<Value *, 2> ValuesToRelease;
258
259 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
260 SmallVector<Value *, 2> ValuesToRelease)
261 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
262 ValuesToRelease(std::move(ValuesToRelease)) {}
263};
264
265struct ConstraintTy {
266 RowTy Coefficients;
267
268 /// Number of variables the constraint is defined over.
269 unsigned NumVars = 0;
270
271 bool IsSigned = false;
272
273 ConstraintTy() = default;
274
275 ConstraintTy(RowTy Coefficients, unsigned NumVars, bool IsSigned, bool IsEq,
276 bool IsNe)
277 : Coefficients(std::move(Coefficients)), NumVars(NumVars),
278 IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {}
279
280 bool empty() const { return Coefficients.empty(); }
281
282 /// Returns true if the constraint does not reference any variable, i.e. it is
283 /// of the form 'c >= 0'.
284 bool isConstantOnly() const { return Coefficients.size() < 2; }
285
286 bool isEq() const { return IsEq; }
287
288 bool isNe() const { return IsNe; }
289
290 /// Check if the current constraint is implied by the given ConstraintSystem.
291 ///
292 /// \return true or false if the constraint is proven to be respectively true,
293 /// or false. When the constraint cannot be proven to be either true or false,
294 /// std::nullopt is returned.
295 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
296
297private:
298 bool IsEq = false;
299 bool IsNe = false;
300};
301
302/// Wrapper encapsulating separate constraint systems and corresponding value
303/// mappings for both unsigned and signed information. Facts are added to and
304/// conditions are checked against the corresponding system depending on the
305/// signed-ness of their predicates. While the information is kept separate
306/// based on signed-ness, certain conditions can be transferred between the two
307/// systems.
308class ConstraintInfo {
309
310 ConstraintSystem UnsignedCS;
311 ConstraintSystem SignedCS;
312
313 const DataLayout &DL;
314
315public:
316 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
317 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
318 auto &Value2Index = getValue2Index(false);
319 // Add Arg > -1 constraints to unsigned system for all function arguments.
320 for (Value *Arg : FunctionArgs)
321 UnsignedCS.addRow({Entry(0, 0), Entry(-1, Value2Index.at(Arg))},
322 Value2Index.size());
323 }
324
325 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
326 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
327 }
328 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
329 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
330 }
331
332 ConstraintSystem &getCS(bool Signed) {
333 return Signed ? SignedCS : UnsignedCS;
334 }
335 const ConstraintSystem &getCS(bool Signed) const {
336 return Signed ? SignedCS : UnsignedCS;
337 }
338
339 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
340 void popLastNVariables(bool Signed, unsigned N) {
341 getCS(Signed).popLastNVariables(N);
342 }
343
344 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
345
346 /// Returns true if \p V is known to be non-negative, either because the
347 /// signed system implies it or because ValueTracking can prove it.
348 bool isKnownNonNegative(Value *V) const;
349
350 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
351 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
352
353 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
354 /// constraints, using indices from the corresponding constraint system.
355 /// New variables that need to be added to the system are collected in
356 /// \p NewVariables.
357 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
358 SmallVectorImpl<Value *> &NewVariables,
359 bool ForceSignedSystem = false) const;
360
361 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
362 /// constraints using getConstraint. Returns an empty constraint if the result
363 /// cannot be used to query the existing constraint system, e.g. because it
364 /// would require adding new variables. Also tries to convert signed
365 /// predicates to unsigned ones if possible to allow using the unsigned system
366 /// which increases the effectiveness of the signed <-> unsigned transfer
367 /// logic.
368 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
369 Value *Op1) const;
370
371 /// Try to add information from \p A \p Pred \p B to the unsigned/signed
372 /// system if \p Pred is signed/unsigned.
373 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
374 unsigned NumIn, unsigned NumOut,
375 SmallVectorImpl<StackEntry> &DFSInStack);
376
377private:
378 /// Adds facts into constraint system. \p ForceSignedSystem can be set when
379 /// the \p Pred is eq/ne, and signed constraint system is used when it's
380 /// specified.
381 void addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
382 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack,
383 bool ForceSignedSystem);
384
385 /// Try to use the inequality \p A != \p B to tighten a non-strict bound the
386 /// system already implies to the corresponding strict bound.
387 void tightenBoundUsingNe(Value *A, Value *B, unsigned NumIn, unsigned NumOut,
388 SmallVectorImpl<StackEntry> &DFSInStack);
389};
390
391/// Represents a (Coefficient * Variable) entry after IR decomposition.
392struct DecompEntry {
393 int64_t Coefficient;
394 Value *Variable;
395
396 DecompEntry(int64_t Coefficient, Value *Variable)
397 : Coefficient(Coefficient), Variable(Variable) {}
398};
399
400/// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
401struct Decomposition {
402 int64_t Offset = 0;
404
405 Decomposition(int64_t Offset) : Offset(Offset) {}
406 Decomposition(Value *V) { Vars.emplace_back(1, V); }
407 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
408 : Offset(Offset), Vars(Vars) {}
409
410 /// Add \p OtherOffset and return true if the operation overflows, i.e. the
411 /// new decomposition is invalid.
412 [[nodiscard]] bool add(int64_t OtherOffset) {
413 return AddOverflow(Offset, OtherOffset, Offset);
414 }
415
416 /// Add \p Other and return true if the operation overflows, i.e. the new
417 /// decomposition is invalid.
418 [[nodiscard]] bool add(const Decomposition &Other) {
419 if (add(Other.Offset))
420 return true;
421 append_range(Vars, Other.Vars);
422 return false;
423 }
424
425 /// Subtract \p Other and return true if the operation overflows, i.e. the new
426 /// decomposition is invalid.
427 [[nodiscard]] bool sub(const Decomposition &Other) {
428 Decomposition Tmp = Other;
429 if (Tmp.mul(-1))
430 return true;
431 if (add(Tmp.Offset))
432 return true;
433 append_range(Vars, Tmp.Vars);
434 return false;
435 }
436
437 /// Multiply all coefficients by \p Factor and return true if the operation
438 /// overflows, i.e. the new decomposition is invalid.
439 [[nodiscard]] bool mul(int64_t Factor) {
440 if (MulOverflow(Offset, Factor, Offset))
441 return true;
442 for (auto &Var : Vars)
443 if (MulOverflow(Var.Coefficient, Factor, Var.Coefficient))
444 return true;
445 return false;
446 }
447};
448
449// Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
450struct OffsetResult {
451 Value *BasePtr;
452 APInt ConstantOffset;
453 SmallMapVector<Value *, APInt, 4> VariableOffsets;
454 GEPNoWrapFlags NW;
455
456 OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
457
458 OffsetResult(GEPOperator &GEP, const DataLayout &DL)
459 : BasePtr(GEP.getPointerOperand()), NW(GEP.getNoWrapFlags()) {
460 ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
461 }
462};
463} // namespace
464
465// Try to collect variable and constant offsets for \p GEP, partly traversing
466// nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
467// the offset fails.
469 OffsetResult Result(GEP, DL);
470 unsigned BitWidth = Result.ConstantOffset.getBitWidth();
471 if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
472 Result.ConstantOffset))
473 return {};
474
475 // If we have a nested GEP, check if we can combine the constant offset of the
476 // inner GEP with the outer GEP.
477 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
478 SmallMapVector<Value *, APInt, 4> VariableOffsets2;
479 APInt ConstantOffset2(BitWidth, 0);
480 bool CanCollectInner = InnerGEP->collectOffset(
481 DL, BitWidth, VariableOffsets2, ConstantOffset2);
482 // TODO: Support cases with more than 1 variable offset.
483 if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
484 VariableOffsets2.size() > 1 ||
485 (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
486 // More than 1 variable index, use outer result.
487 return Result;
488 }
489 Result.BasePtr = InnerGEP->getPointerOperand();
490 Result.ConstantOffset += ConstantOffset2;
491 if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
492 Result.VariableOffsets = std::move(VariableOffsets2);
493 Result.NW &= InnerGEP->getNoWrapFlags();
494 }
495 return Result;
496}
497
498static Decomposition decompose(Value *V, const ConstraintInfo &Info,
499 bool IsSigned, const DataLayout &DL);
500
501static bool canUseSExt(ConstantInt *CI) {
502 const APInt &Val = CI->getValue();
504}
505
506/// Returns true if the pre-condition \p Op \p Pred \p RHS, required to look
507/// through an expression while decomposing it, is known to hold given \p Info.
508static bool preconditionHolds(const ConstraintInfo &Info,
509 CmpInst::Predicate Pred, Value *Op, int64_t RHS) {
510 return Info.doesHold(Pred, Op, ConstantInt::get(Op->getType(), RHS));
511}
512
513static Decomposition decomposeGEP(GEPOperator &GEP, const ConstraintInfo &Info,
514 bool IsSigned, const DataLayout &DL) {
515 // Do not reason about pointers where the index size is larger than 64 bits,
516 // as the coefficients used to encode constraints are 64 bit integers.
517 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
518 return &GEP;
519
520 assert(!IsSigned && "The logic below only supports decomposition for "
521 "unsigned predicates at the moment.");
522 const auto &[BasePtr, ConstantOffset, VariableOffsets, NW] =
524 // We support either plain gep nuw, or gep nusw with non-negative offset,
525 // which implies gep nuw.
526 if (!BasePtr || NW == GEPNoWrapFlags::none())
527 return &GEP;
528
529 // For a nuw-only GEP (nuw without nusw/inbounds), the offset must be
530 // interpreted as unsigned.
531 if (!NW.hasNoUnsignedSignedWrap() && ConstantOffset.isNegative())
532 return &GEP;
533
534 Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
535 for (auto [Index, Scale] : VariableOffsets) {
536 if (!NW.hasNoUnsignedWrap()) {
537 // Try to prove nuw from nusw and nneg. If the index cannot be proven
538 // non-negative, keep the GEP as-is instead of decomposing it.
539 assert(NW.hasNoUnsignedSignedWrap() && "Must have nusw flag");
540 if (!isKnownNonNegative(Index, DL) &&
541 !preconditionHolds(Info, CmpInst::ICMP_SGE, Index, 0))
542 return &GEP;
543 }
544
545 auto IdxResult = decompose(Index, Info, IsSigned, DL);
546 if (IdxResult.mul(Scale.getSExtValue()))
547 return &GEP;
548 if (Result.add(IdxResult))
549 return &GEP;
550 }
551 return Result;
552}
553
554// Decomposes \p V into a constant offset + list of pairs { Coefficient,
555// Variable } where Coefficient * Variable. The sum of the constant offset and
556// pairs equals \p V.
557//
558// Looking through certain expressions is only valid if a pre-condition holds.
559// Pre-conditions are checked against \p Info as needed.
560static Decomposition decompose(Value *V, const ConstraintInfo &Info,
561 bool IsSigned, const DataLayout &DL) {
562 auto MergeResults = [&Info, IsSigned,
563 &DL](Value *A, Value *B,
564 bool IsSignedB) -> std::optional<Decomposition> {
565 auto ResA = decompose(A, Info, IsSigned, DL);
566 auto ResB = decompose(B, Info, IsSignedB, DL);
567 if (ResA.add(ResB))
568 return std::nullopt;
569 return ResA;
570 };
571
572 Type *Ty = V->getType()->getScalarType();
573 if (Ty->isPointerTy() && !IsSigned) {
574 if (auto *GEP = dyn_cast<GEPOperator>(V))
575 return decomposeGEP(*GEP, Info, IsSigned, DL);
577 return int64_t(0);
578
579 return V;
580 }
581
582 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
583 // coefficient add/mul may wrap, while the operation in the full bit width
584 // would not.
585 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
586 return V;
587
588 // Decompose \p V used with a signed predicate.
589 if (IsSigned) {
590 if (auto *CI = dyn_cast<ConstantInt>(V)) {
591 if (canUseSExt(CI))
592 return CI->getSExtValue();
593 }
594 Value *Op0;
595 Value *Op1;
596
597 if (match(V, m_SExt(m_Value(Op0))))
598 V = Op0;
599 else if (match(V, m_NNegZExt(m_Value(Op0)))) {
600 V = Op0;
601 } else if (match(V, m_NSWTrunc(m_Value(Op0)))) {
602 if (Op0->getType()->getScalarSizeInBits() <= 64)
603 V = Op0;
604 }
605
606 if (match(V, m_NSWAddLike(m_Value(Op0), m_Value(Op1)))) {
607 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
608 return *Decomp;
609 return V;
610 }
611
612 // `xor %x, -1` is equivalent to `sub nsw -1, %x`.
613 if (match(V, m_Not(m_Value(Op0)))) {
614 Decomposition Result(-1);
615 if (!Result.sub(decompose(Op0, Info, IsSigned, DL)))
616 return Result;
617 return V;
618 }
619
620 if (match(V, m_NSWSub(m_Value(Op0), m_Value(Op1)))) {
621 auto ResA = decompose(Op0, Info, IsSigned, DL);
622 auto ResB = decompose(Op1, Info, IsSigned, DL);
623 if (!ResA.sub(ResB))
624 return ResA;
625 return V;
626 }
627
628 ConstantInt *CI;
629 if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
630 auto Result = decompose(Op0, Info, IsSigned, DL);
631 if (!Result.mul(CI->getSExtValue()))
632 return Result;
633 return V;
634 }
635
636 // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
637 // shift == bw-1.
638 if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) {
639 uint64_t Shift = CI->getValue().getLimitedValue();
640 if (Shift < Ty->getIntegerBitWidth() - 1) {
641 assert(Shift < 64 && "Would overflow");
642 auto Result = decompose(Op0, Info, IsSigned, DL);
643 if (!Result.mul(int64_t(1) << Shift))
644 return Result;
645 return V;
646 }
647 }
648
649 return V;
650 }
651
652 if (auto *CI = dyn_cast<ConstantInt>(V)) {
653 if (CI->uge(MaxConstraintValue))
654 return V;
655 return int64_t(CI->getZExtValue());
656 }
657
658 Value *Op0;
659 if (match(V, m_ZExt(m_Value(Op0)))) {
660 V = Op0;
661 } else if (match(V, m_SExt(m_Value(Op0)))) {
662 // Looking through the sext is only valid if the operand is non-negative.
663 if (!preconditionHolds(Info, CmpInst::ICMP_SGE, Op0, 0))
664 return V;
665 V = Op0;
666 } else if (auto *Trunc = dyn_cast<TruncInst>(V)) {
667 if (Trunc->getSrcTy()->getScalarSizeInBits() <= 64 &&
668 (Trunc->hasNoUnsignedWrap() || Trunc->hasNoSignedWrap())) {
669 Value *Src = Trunc->getOperand(0);
670 // A trunc nsw only truncates without unsigned wrap if its operand is
671 // non-negative.
672 if (!Trunc->hasNoUnsignedWrap() &&
673 !preconditionHolds(Info, CmpInst::ICMP_SGE, Src, 0))
674 return V;
675 V = Src;
676 }
677 }
678
679 Value *Op1;
680 ConstantInt *CI;
681 if (match(V, m_NUWAddLike(m_Value(Op0), m_Value(Op1)))) {
682 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
683 return *Decomp;
684 return V;
685 }
686
687 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
688 canUseSExt(CI)) {
689 // Adding a negative constant only wraps if Op0 is smaller than it.
690 if (!preconditionHolds(Info, CmpInst::ICMP_UGE, Op0,
691 CI->getSExtValue() * -1))
692 return V;
693 if (auto Decomp = MergeResults(Op0, CI, true))
694 return *Decomp;
695 return V;
696 }
697
698 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
699 // An add nsw only adds without unsigned wrap if both operands are
700 // non-negative.
701 if ((!isKnownNonNegative(Op0, DL) &&
702 !preconditionHolds(Info, CmpInst::ICMP_SGE, Op0, 0)) ||
703 (!isKnownNonNegative(Op1, DL) &&
704 !preconditionHolds(Info, CmpInst::ICMP_SGE, Op1, 0)))
705 return V;
706
707 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
708 return *Decomp;
709 return V;
710 }
711
712 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
713 // The scale 1 << shift must fit in the signed coefficient, so reject a
714 // shift of 63, for which int64_t{1} << 63 is INT64_MIN.
715 if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 63)
716 return V;
717 auto Result = decompose(Op1, Info, IsSigned, DL);
718 if (!Result.mul(int64_t{1} << CI->getSExtValue()))
719 return Result;
720 return V;
721 }
722
723 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
724 (!CI->isNegative())) {
725 auto Result = decompose(Op1, Info, IsSigned, DL);
726 if (!Result.mul(CI->getSExtValue()))
727 return Result;
728 return V;
729 }
730
731 if (match(V, m_Sub(m_Value(Op0), m_Value(Op1)))) {
732 // a - b can be decomposed when there is no unsigned wrap (either known via
733 // flag or proven as precondition).
735 !Info.doesHold(CmpInst::ICMP_ULE, Op1, Op0))
736 return V;
737 auto ResA = decompose(Op0, Info, IsSigned, DL);
738 auto ResB = decompose(Op1, Info, IsSigned, DL);
739 if (!ResA.sub(ResB))
740 return ResA;
741 return V;
742 }
743
744 return V;
745}
746
747ConstraintTy
748ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
749 SmallVectorImpl<Value *> &NewVariables,
750 bool ForceSignedSystem) const {
751 assert(NewVariables.empty() && "NewVariables must be empty when passed in");
752 assert((!ForceSignedSystem || CmpInst::isEquality(Pred)) &&
753 "signed system can only be forced on eq/ne");
754
755 bool IsEq = false;
756 bool IsNe = false;
757
758 // Try to convert Pred to one of ULE/ULT/SLE/SLT.
759 switch (Pred) {
763 case CmpInst::ICMP_SGE: {
764 Pred = CmpInst::getSwappedPredicate(Pred);
765 std::swap(Op0, Op1);
766 break;
767 }
768 case CmpInst::ICMP_EQ:
769 if (!ForceSignedSystem && match(Op1, m_Zero())) {
770 Pred = CmpInst::ICMP_ULE;
771 } else {
772 IsEq = true;
773 Pred = CmpInst::ICMP_ULE;
774 }
775 break;
776 case CmpInst::ICMP_NE:
777 if (!ForceSignedSystem && match(Op1, m_Zero())) {
779 std::swap(Op0, Op1);
780 } else {
781 IsNe = true;
782 Pred = CmpInst::ICMP_ULE;
783 }
784 break;
785 default:
786 break;
787 }
788
789 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
790 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
791 return {};
792
793 bool IsSigned = ForceSignedSystem || CmpInst::isSigned(Pred);
794 auto &Value2Index = getValue2Index(IsSigned);
795 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), *this,
796 IsSigned, DL);
797 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), *this,
798 IsSigned, DL);
799 int64_t Offset1 = ADec.Offset;
800 int64_t Offset2 = BDec.Offset;
801 if (MulOverflow(Offset1, int64_t(-1), Offset1))
802 return {};
803
804 auto &VariablesA = ADec.Vars;
805 auto &VariablesB = BDec.Vars;
806
807 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
808 // new entry to NewVariables.
809 auto GetOrAddIndex = [&Value2Index, &NewVariables](Value *V) -> unsigned {
810 auto V2I = Value2Index.find(V);
811 if (V2I != Value2Index.end())
812 return V2I->second;
813 unsigned Idx = find(NewVariables, V) - NewVariables.begin();
814 if (Idx == NewVariables.size())
815 NewVariables.push_back(V);
816 return Value2Index.size() + Idx + 1;
817 };
818
819 // Build result constraint, by first adding all coefficients from A and then
820 // subtracting all coefficients from B.
821 RowTy R(1, Entry(0, 0));
822 auto GetCoefficient = [&R](unsigned Idx) -> int64_t & {
823 // The entry for Idx, or the place to insert it at, is the first entry with
824 // an index >= Idx.
825 Entry *I =
826 find_if(drop_begin(R), [Idx](const Entry &E) { return E.Id >= Idx; });
827 if (I == R.end() || I->Id != Idx)
828 I = R.insert(I, Entry(0, Idx));
829 return I->Coefficient;
830 };
831 for (const auto &KV : VariablesA)
832 GetCoefficient(GetOrAddIndex(KV.Variable)) += KV.Coefficient;
833
834 for (const auto &KV : VariablesB) {
835 auto &Coeff = GetCoefficient(GetOrAddIndex(KV.Variable));
836 if (SubOverflow(Coeff, KV.Coefficient, Coeff))
837 return {};
838 }
839
840 int64_t OffsetSum;
841 if (AddOverflow(Offset1, Offset2, OffsetSum))
842 return {};
843 if (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT)
844 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
845 return {};
846 R[0].Coefficient = OffsetSum;
847
848 // Drop coefficients that cancelled out.
849 erase_if(R, [](const Entry &E) { return E.Id != 0 && E.Coefficient == 0; });
850
851 // Remove any new variable without a coefficient in the row.
852 unsigned NumV2I = Value2Index.size();
853 NewVariables.truncate(R.back().Id > NumV2I ? R.back().Id - NumV2I : 0);
854
855 return ConstraintTy(std::move(R), Value2Index.size() + NewVariables.size(),
856 IsSigned, IsEq, IsNe);
857}
858
859ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
860 Value *Op0,
861 Value *Op1) const {
862 Constant *NullC = Constant::getNullValue(Op0->getType());
863 // Handle trivially true compares directly to avoid adding V UGE 0 constraints
864 // for all variables in the unsigned system.
865 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
866 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
867 // Return constraint that's trivially true.
868 return ConstraintTy(RowTy(1, Entry(0, 0)), /*NumVars=*/0,
869 /*IsSigned=*/false, /*IsEq=*/false, /*IsNe=*/false);
870 }
871
872 // If both operands are known to be non-negative, change signed predicates to
873 // unsigned ones. This increases the reasoning effectiveness in combination
874 // with the signed <-> unsigned transfer logic.
875 if (CmpInst::isSigned(Pred) &&
879
880 SmallVector<Value *> NewVariables;
881 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
882 if (!NewVariables.empty())
883 return {};
884 return R;
885}
886
887std::optional<bool>
888ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
889 const auto &[SubCS, NewCoefficients] = CS.getSubSystem(Coefficients);
890 bool IsConditionImplied = SubCS.isConditionImplied(NewCoefficients);
891
892 if (IsEq || IsNe) {
893 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(NewCoefficients);
894 bool IsNegatedOrEqualImplied =
895 !NegatedOrEqual.empty() && SubCS.isConditionImplied(NegatedOrEqual);
896
897 // In order to check that `%a == %b` is true (equality), both conditions `%a
898 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
899 // is true), we return true if they both hold, false in the other cases.
900 if (IsConditionImplied && IsNegatedOrEqualImplied)
901 return IsEq;
902
903 auto Negated = ConstraintSystem::negate(NewCoefficients);
904 bool IsNegatedImplied =
905 !Negated.empty() && SubCS.isConditionImplied(Negated);
906
907 auto StrictLessThan = ConstraintSystem::toStrictLessThan(NewCoefficients);
908 bool IsStrictLessThanImplied =
909 !StrictLessThan.empty() && SubCS.isConditionImplied(StrictLessThan);
910
911 // In order to check that `%a != %b` is true (non-equality), either
912 // condition `%a > %b` or `%a < %b` must hold true. When checking for
913 // non-equality (`IsNe` is true), we return true if one of the two holds,
914 // false in the other cases.
915 if (IsNegatedImplied || IsStrictLessThanImplied)
916 return IsNe;
917
918 return std::nullopt;
919 }
920
921 if (IsConditionImplied)
922 return true;
923
924 auto Negated = ConstraintSystem::negate(NewCoefficients);
925 auto IsNegatedImplied = !Negated.empty() && SubCS.isConditionImplied(Negated);
926 if (IsNegatedImplied)
927 return false;
928
929 // Neither the condition nor its negated holds, did not prove anything.
930 return std::nullopt;
931}
932
933bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
934 Value *B) const {
935 auto R = getConstraintForSolving(Pred, A, B);
936 return !R.empty() &&
937 getCS(R.IsSigned).isConditionImpliedInSubSystem(R.Coefficients);
938}
939
940bool ConstraintInfo::isKnownNonNegative(Value *V) const {
941 return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
943}
944
945void ConstraintInfo::transferToOtherSystem(
946 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
947 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
948 // Check if we can combine facts from the signed and unsigned systems to
949 // derive additional facts.
950 if (!A->getType()->isIntegerTy())
951 return;
952 // FIXME: This currently depends on the order we add facts. Ideally we
953 // would first add all known facts and only then try to add additional
954 // facts.
955 switch (Pred) {
956 default:
957 break;
960 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
961 if (isKnownNonNegative(B)) {
962 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
963 NumOut, DFSInStack);
964 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
965 DFSInStack);
966 }
967 break;
970 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
971 if (isKnownNonNegative(A)) {
972 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
973 NumOut, DFSInStack);
974 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
975 DFSInStack);
976 }
977 break;
981 addFact(ICmpInst::getUnsignedPredicate(Pred), A, B, NumIn, NumOut,
982 DFSInStack);
983 break;
984 case CmpInst::ICMP_SGT: {
985 if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
986 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
987 NumOut, DFSInStack);
989 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
990
991 break;
992 }
995 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
996 break;
997 }
998}
999
1000#ifndef NDEBUG
1001
1003 const DenseMap<Value *, unsigned> &Value2Index) {
1004 ConstraintSystem CS(Value2Index);
1005 CS.addRow(C, Value2Index.size());
1006 CS.dump();
1007}
1008#endif
1009
1010/// Splits the induction phi \p PN into the start value, coming from the loop
1011/// predecessor \p LoopPred, and the backedge value, coming from inside the
1012/// loop. Returns {nullptr, nullptr} if \p PN has other incoming values.
1013static std::pair<Value *, Value *>
1014getStartAndBackedgeValue(const PHINode &PN, const BasicBlock *LoopPred) {
1015 assert(PN.getBasicBlockIndex(LoopPred) >= 0 &&
1016 "LoopPred must be a predecessor of the phi's block");
1017 if (PN.getNumIncomingValues() != 2)
1018 return {nullptr, nullptr};
1019 unsigned StartIdx = PN.getIncomingBlock(0) == LoopPred ? 0 : 1;
1020 return {PN.getIncomingValue(StartIdx), PN.getIncomingValue(1 - StartIdx)};
1021}
1022
1023/// Matches an increment of \p PhiM by a constant offset, captured in \p Off.
1024/// The increment must be a plain IR add or [u|s]add.with.overflow.
1025template <typename PhiMatchTy>
1026static auto m_IncrementOf(const PhiMatchTy &PhiM, const APInt *&Off) {
1027 return m_CombineOr(
1028 m_c_Add(PhiM, m_APInt(Off)),
1032}
1033
1034MonotonicInfo State::getMonotonicityInfo(PHINode &PN, Value *Step) {
1035 MonotonicInfo Info;
1036 const APInt *StepOffset = nullptr;
1037 if (match(Step, m_IncrementOf(m_Specific(&PN), StepOffset))) {
1038 Info.Decreasing = StepOffset->isNegative();
1039 if (const auto *Add = dyn_cast<OverflowingBinaryOperator>(Step)) {
1040 Info.Unsigned = !Info.Decreasing && Add->hasNoUnsignedWrap();
1041 Info.Signed = Add->hasNoSignedWrap();
1042 }
1043 } else if (const auto *GEP = dyn_cast<GEPOperator>(Step)) {
1044 // TODO: Handle the non-increasing direction, which needs a nusw GEP with a
1045 // negative constant offset.
1046 const DataLayout &DL = PN.getDataLayout();
1047 APInt GEPOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1048 Info.Unsigned = GEP->getPointerOperand() == &PN &&
1049 (GEP->hasNoUnsignedWrap() ||
1050 ((GEP->hasNoUnsignedSignedWrap() &&
1051 GEP->accumulateConstantOffset(DL, GEPOffset) &&
1052 !GEPOffset.isNegative())));
1053 }
1054
1055 // Forming the SCEV of a phi is expensive, so only consult it for a PN + C
1056 // step whose no-wrap flags prove nothing.
1057 if (Info.Unsigned || Info.Signed || !StepOffset)
1058 return Info;
1059
1060 const auto *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1061 if (!AR)
1062 return Info;
1066 auto IsMonotonic = [&](CmpInst::Predicate Pred) {
1067 return SE.getMonotonicPredicateType(AR, Pred) == Expected;
1068 };
1069 Info.Signed = IsMonotonic(CmpInst::ICMP_SGT);
1070 Info.Unsigned = !Info.Decreasing && IsMonotonic(CmpInst::ICMP_UGT);
1071 return Info;
1072}
1073
1074void State::addBoundsForHeaderInductions(BasicBlock &BB) {
1075 Loop *L = LI.getLoopFor(&BB);
1076 if (!L || L->getHeader() != &BB)
1077 return;
1078 BasicBlock *LoopPred = L->getLoopPredecessor();
1079 if (!LoopPred)
1080 return;
1081
1082 DomTreeNode *DTN = DT.getNode(&BB);
1083 for (PHINode &PN : BB.phis()) {
1084 if (!PN.getType()->isIntegerTy() && !PN.getType()->isPointerTy())
1085 continue;
1086
1087 auto [Start, Step] = getStartAndBackedgeValue(PN, LoopPred);
1088 if (!Start)
1089 continue;
1090
1091 MonotonicInfo Info = getMonotonicityInfo(PN, Step);
1092 // Every variable in the unsigned system already has a `V >= 0` row, so a
1093 // zero start value would just duplicate it.
1094 if (match(Start, m_Zero()))
1095 Info.Unsigned = false;
1096 if (!Info.Unsigned && !Info.Signed)
1097 continue;
1098
1099 // A non-decreasing induction cannot step below its start value, and a
1100 // non-increasing one cannot step above it.
1101 Value *LHS = &PN, *RHS = Start;
1102 if (Info.Decreasing)
1103 std::swap(LHS, RHS);
1104 CmpPredicate Pred(Info.Unsigned ? CmpInst::ICMP_UGE : CmpInst::ICMP_SGE,
1105 /*HasSameSign=*/Info.Unsigned && Info.Signed);
1106 WorkList.push_back(FactOrCheck::getConditionFact(DTN, Pred, LHS, RHS));
1107 }
1108}
1109
1110void State::addInfoForInductions(BasicBlock &BB) {
1111 auto *L = LI.getLoopFor(&BB);
1112 if (!L)
1113 return;
1114
1115 BasicBlock *Header = L->getHeader();
1116 BasicBlock *Latch = L->getLoopLatch();
1117 if (Header != &BB && Latch != &BB)
1118 return;
1119
1120 // A is either a phi or a post-increment PN + C with constant step. For the
1121 // latter, extract the constant IncStep.
1122 Value *A;
1123 Value *B;
1124 PHINode *PN = nullptr;
1125 const APInt *IncStep = nullptr;
1126 CmpPredicate Pred;
1127 auto IndValue =
1128 m_Value(A, m_CombineOr(m_Phi(PN), m_IncrementOf(m_Phi(PN), IncStep)));
1129
1130 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1131 if (!Br)
1132 return;
1133
1134 auto CountingCmp = m_c_ICmp(Pred, IndValue, m_Value(B));
1135 std::optional<bool> PeeledOnEdge;
1136 if (!match(Br->getCondition(), CountingCmp)) {
1137 // Look through AND/OR, and remember which edge requires all operands to be
1138 // true.
1139 if (match(Br->getCondition(), m_c_LogicalAnd(CountingCmp, m_Value())))
1140 PeeledOnEdge = true;
1141 else if (match(Br->getCondition(), m_c_LogicalOr(CountingCmp, m_Value())))
1142 PeeledOnEdge = false;
1143 else
1144 return;
1145 }
1146
1147 if (PN->getParent() != Header || PN->getNumIncomingValues() != 2 ||
1148 !SE.isSCEVable(PN->getType()))
1149 return;
1150
1151 // For latch conditions, we need to inject the condition that holds for the
1152 // next iteration into the header. We limit to post-inc conditions, for which
1153 // an original PN + Step != B condition results in a PN < B constraint in the
1154 // header, which also holds for the next loop iteration. This would no longer
1155 // be correct if the post-inc handling would inject a more precise PN + Step <
1156 // B constraint instead.
1157 if (&BB == Latch && !IncStep)
1158 return;
1159
1160 bool ContinueOnTrue =
1161 Pred == CmpInst::ICMP_NE || ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred);
1162 CmpInst::Predicate ContinuePred =
1163 ContinueOnTrue ? Pred.dropSameSign() : CmpInst::getInversePredicate(Pred);
1164 BasicBlock *InLoopSucc = Br->getSuccessor(ContinueOnTrue ? 0 : 1);
1165
1166 // The peeled condition only implies the compare on the edge where the
1167 // combined condition forces its operands, which must be the in-loop edge.
1168 if (PeeledOnEdge && *PeeledOnEdge != ContinueOnTrue)
1169 return;
1170
1171 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB))
1172 return;
1173
1174 BasicBlock *LoopPred = L->getLoopPredecessor();
1175 if (!LoopPred || !L->isLoopInvariant(B))
1176 return;
1177
1178 auto [StartValue, Backedge] = getStartAndBackedgeValue(*PN, LoopPred);
1179 DomTreeNode *DTN = DT.getNode(InLoopSucc);
1180
1181 if (ICmpInst::isRelational(ContinuePred)) {
1182 if (A != Backedge)
1183 return;
1184
1185 // The latch condition ensures ContinuePred holds in the header on each
1186 // iteration other than the first. Together with a precondition on the start
1187 // value (StartValue ContinuePred B), we can add B as bound of PN.
1188 WorkList.push_back(FactOrCheck::getConditionFact(
1189 DTN, ContinuePred, PN, B, ConditionTy(ContinuePred, StartValue, B)));
1190
1191 // A relational latch steps past B rather than landing on it, so none of the
1192 // reasoning below applies.
1193 return;
1194 }
1195
1196 const APInt *StepOffset = nullptr;
1197 const SCEV *StartSCEV = nullptr;
1198 if (match(Backedge, m_c_Add(m_Specific(PN), m_APInt(StepOffset)))) {
1199 if (StepOffset->isZero())
1200 return;
1201 } else {
1202 const SCEV *Expr = SE.getSCEV(PN);
1203 if (!match(Expr,
1204 m_scev_AffineAddRec(m_SCEV(StartSCEV), m_scev_APInt(StepOffset),
1205 m_SpecificLoop(L))))
1206 return;
1207 }
1208
1209 // If we looked through `PN + C`, only derive facts when that add is
1210 // really the induction's post-increment or post-decrement.
1211 if (IncStep && *IncStep != *StepOffset)
1212 return;
1213
1214 MonotonicInfo Info = getMonotonicityInfo(*PN, Backedge);
1215
1216 // Handle negative steps.
1217 if (StepOffset->isNegative()) {
1218 // TODO: Extend to allow steps > -1.
1219 if (!(-*StepOffset).isOne())
1220 return;
1221
1222 // AR may wrap.
1223 // The loop exits once the compared value reaches B, that is at PN == B when
1224 // comparing the phi, and at PN == B + 1 for a post-decrement. Use
1225 // non-strict predicate for the former, and a strict one for the latter to
1226 // ensure the loop exits before wrapping.
1227 CmpInst::Predicate UPrecond =
1229 ConditionTy BBeforeStartUnsigned = {UPrecond, B, StartValue};
1230 ConditionTy BBeforeStartSigned = {ICmpInst::getSignedPredicate(UPrecond), B,
1231 StartValue};
1232
1233 // AR may wrap, so both facts are conditional on B being below StartValue.
1234 // Add StartValue >= PN, which holds as the loop exits before wrapping.
1235 WorkList.push_back(FactOrCheck::getConditionFact(
1236 DTN, CmpInst::ICMP_UGE, StartValue, PN, BBeforeStartUnsigned));
1237 if (!(Info.Decreasing && Info.Signed))
1238 WorkList.push_back(FactOrCheck::getConditionFact(
1239 DTN, CmpInst::ICMP_SGE, StartValue, PN, BBeforeStartSigned));
1240 // Add PN > B, which holds as the loop exits when reaching B.
1241 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGT, PN,
1242 B, BBeforeStartUnsigned));
1243 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGT, PN,
1244 B, BBeforeStartSigned));
1245 return;
1246 }
1247
1248 // Make sure AR either steps by 1 or that the value we compare against is a
1249 // GEP based on the same start value and all offsets are a multiple of the
1250 // step size, to guarantee that the induction will reach the value.
1251 if (StepOffset->isZero() || StepOffset->isNegative())
1252 return;
1253
1254 if (!StepOffset->isOne()) {
1255 // Check whether B-Start is known to be a multiple of StepOffset.
1256 if (!StartSCEV)
1257 StartSCEV = SE.getSCEV(StartValue);
1258 const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV);
1259 if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1260 !SE.getConstantMultiple(BMinusStart).urem(*StepOffset).isZero())
1261 return;
1262 }
1263
1264 // We already established that B - Start is a multiple of Step above. The loop
1265 // exits once the compared value reaches B, that is at PN == B when comparing
1266 // the phi, and at PN + Step == B for a post-increment. Together with the
1267 // added precondition StartValue <= B for the former and the strict
1268 // StartValue < B for the latter (which implies StartValue + Step <= B),
1269 // neither PN nor the increment can wrap.
1271 ConditionTy StartBeforeBoundUnsigned = {UPrecond, StartValue, B};
1272 ConditionTy StartBeforeBoundSigned = {ICmpInst::getSignedPredicate(UPrecond),
1273 StartValue, B};
1274
1275 // Add PN >= StartValue, as the loop exits before wrapping.
1276 if (!Info.Unsigned)
1277 WorkList.push_back(FactOrCheck::getConditionFact(
1278 DTN, CmpInst::ICMP_UGE, PN, StartValue, StartBeforeBoundUnsigned));
1279 if (!Info.Signed)
1280 WorkList.push_back(FactOrCheck::getConditionFact(
1281 DTN, CmpInst::ICMP_SGE, PN, StartValue, StartBeforeBoundSigned));
1282 // Add PN < B, as the loop exits once the compared value reaches B.
1283 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SLT, PN,
1284 B, StartBeforeBoundSigned));
1285 WorkList.push_back(FactOrCheck::getConditionFact(
1286 DTN, CmpInst::ICMP_ULT, PN, B, StartBeforeBoundUnsigned));
1287
1288 // Try to add condition from the header or latch to the dedicated exit
1289 // blocks. When exiting either with EQ or NE, we know that the induction value
1290 // must be u<= B, as other exits may only exit earlier.
1291 assert(!StepOffset->isNegative() && "induction must be increasing");
1292 assert(ContinuePred == CmpInst::ICMP_NE && "unsupported predicate");
1294 L->getExitBlocks(ExitBBs);
1295 for (BasicBlock *EB : ExitBBs) {
1296 // Bail out on non-dedicated exits.
1297 if (DT.dominates(&BB, EB)) {
1298 WorkList.emplace_back(FactOrCheck::getConditionFact(
1299 DT.getNode(EB), CmpInst::ICMP_ULE, A, B, StartBeforeBoundUnsigned));
1300 }
1301 }
1302}
1303
1305 uint64_t AccessSize,
1306 CmpPredicate &Pred, Value *&A,
1307 Value *&B, const DataLayout &DL,
1308 const TargetLibraryInfo &TLI) {
1310 if (!Offset.NW.hasNoUnsignedWrap())
1311 return false;
1312
1313 if (Offset.VariableOffsets.size() != 1)
1314 return false;
1315
1316 uint64_t BitWidth = Offset.ConstantOffset.getBitWidth();
1317 auto &[Index, Scale] = Offset.VariableOffsets.front();
1318 // Bail out on non-canonical GEPs.
1319 if (Index->getType()->getScalarSizeInBits() != BitWidth)
1320 return false;
1321
1322 ObjectSizeOpts Opts;
1323 // Workaround for gep inbounds, ptr null, idx.
1324 Opts.NullIsUnknownSize = true;
1325 // Be conservative since we are not clear on whether an out of bounds access
1326 // to the padding is UB or not.
1327 Opts.RoundToAlign = true;
1328 std::optional<TypeSize> Size =
1329 getBaseObjectSize(Offset.BasePtr, DL, &TLI, Opts);
1330 if (!Size || Size->isScalable())
1331 return false;
1332
1333 // Index * Scale + ConstOffset + AccessSize <= AllocSize
1334 // With nuw flag, we know that the index addition doesn't have unsigned wrap.
1335 // If (AllocSize - (ConstOffset + AccessSize)) wraps around, there is no valid
1336 // value for Index.
1337 APInt MaxIndex = (APInt(BitWidth, Size->getFixedValue() - AccessSize,
1338 /*isSigned=*/false, /*implicitTrunc=*/true) -
1339 Offset.ConstantOffset)
1340 .udiv(Scale);
1341 Pred = ICmpInst::ICMP_ULE;
1342 A = Index;
1343 B = ConstantInt::get(Index->getType(), MaxIndex);
1344 return true;
1345}
1346
1347/// Returns true if \p I is a candidate whose poison-generating flags may be
1348/// strengthened using the constraint systems.
1350 auto *BO = dyn_cast<BinaryOperator>(I);
1351 if (!BO || !BO->getType()->isIntegerTy())
1352 return false;
1353
1354 switch (BO->getOpcode()) {
1355 case Instruction::Sub:
1356 // A - B does not wrap unsigned, if A >=u B. Subs with constant operands get
1357 // canonicalized to Add.
1358 return !BO->hasNoUnsignedWrap() && !isa<Constant>(BO->getOperand(1));
1359 case Instruction::Add:
1360 // NSW/NUW can be refined using constant ranges.
1361 return (!BO->hasNoUnsignedWrap() || !BO->hasNoSignedWrap()) &&
1362 isa<Constant>(BO->getOperand(1));
1363 case Instruction::Mul:
1364 case Instruction::Shl:
1365 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
1366 return false;
1367 // With a constant second operand, we can use bounds on the first operand to
1368 // refine no-wrap flags. Independently, nuw can be added for nsw if the
1369 // operands are non-negative.
1370 return isa<ConstantInt>(BO->getOperand(1)) || BO->hasNoSignedWrap();
1371 default:
1372 return false;
1373 }
1374}
1375
1376/// Returns true if \p Info implies that \p Op is in \p R, interpreting \p R as
1377/// a signed range if \p Signed is set and as an unsigned range otherwise.
1378static bool doesHoldInRange(const ConstraintInfo &Info, Value *Op,
1379 const ConstantRange &R, bool Signed) {
1380 if (R.isEmptySet() || (Signed ? R.isSignWrappedSet() : R.isWrappedSet()))
1381 return false;
1382
1383 if (R.isFullSet())
1384 return true;
1385
1386 unsigned BitWidth = R.getBitWidth();
1387 APInt Min = Signed ? R.getSignedMin() : R.getUnsignedMin();
1388 APInt Max = Signed ? R.getSignedMax() : R.getUnsignedMax();
1393 // Replace bound too large to be decomposed by the largest usable one.
1394 if (!Signed && Max.uge(MaxConstraintValue))
1395 Max = APInt(BitWidth, MaxConstraintValue - 1);
1396
1397 Type *Ty = Op->getType();
1398 if (Min != MinVal &&
1399 !Info.doesHold(Signed ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE, Op,
1400 ConstantInt::get(Ty, Min)))
1401 return false;
1402 if (Max != MaxVal &&
1403 !Info.doesHold(Signed ? CmpInst::ICMP_SLE : CmpInst::ICMP_ULE, Op,
1404 ConstantInt::get(Ty, Max)))
1405 return false;
1406 return true;
1407}
1408
1410 ConstraintInfo &Info) {
1411 auto *C = dyn_cast<ConstantInt>(Op1);
1412 if (!C)
1413 return false;
1414
1415 // For a constant Op1, the ranges of Op0 for which the operation does not
1416 // wrap are known exactly; check if the systems imply one of them.
1417 bool Changed = false;
1418 auto Opcode = static_cast<Instruction::BinaryOps>(I->getOpcode());
1419 using OBO = OverflowingBinaryOperator;
1420 ConstantRange Other(C->getValue());
1421 if (!I->hasNoUnsignedWrap() &&
1422 doesHoldInRange(Info, Op0,
1424 Opcode, Other, OBO::NoUnsignedWrap),
1425 /*Signed=*/false)) {
1426 LLVM_DEBUG(dbgs() << "Adding nuw to " << *I << "\n");
1427 I->setHasNoUnsignedWrap();
1428 Changed = true;
1429 }
1430 if (!I->hasNoSignedWrap() &&
1431 doesHoldInRange(Info, Op0,
1433 Opcode, Other, OBO::NoSignedWrap),
1434 /*Signed=*/true)) {
1435 LLVM_DEBUG(dbgs() << "Adding nsw to " << *I << "\n");
1436 I->setHasNoSignedWrap();
1437 Changed = true;
1438 }
1439 return Changed;
1440}
1441
1442/// Try to strengthen \p I's poison generating flags using \p Info. Returns
1443/// true if \p I was modified.
1444static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info,
1446 assert(canStrengthenFlags(I) && "not a candidate for flag strengthening");
1447
1448 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
1449 switch (I->getOpcode()) {
1450 case Instruction::Sub: {
1451 // Op0 - Op1 does not wrap unsigned, if Op0 >=u Op1.
1452 if (!Info.doesHold(CmpInst::ICMP_UGE, Op0, Op1))
1453 return false;
1454 LLVM_DEBUG(dbgs() << "Adding nuw to " << *I << "\n");
1455 I->setHasNoUnsignedWrap();
1456 return true;
1457 }
1458 case Instruction::Add:
1459 return tryToStrengthenBinOpFlags(I, Op0, Op1, Info);
1460 case Instruction::Mul:
1461 case Instruction::Shl: {
1462 auto Opcode = static_cast<Instruction::BinaryOps>(I->getOpcode());
1463 bool Changed = tryToStrengthenBinOpFlags(I, Op0, Op1, Info);
1464 if (!I->hasNoUnsignedWrap() && I->hasNoSignedWrap() &&
1465 Info.isKnownNonNegative(Op0) &&
1466 (Opcode == Instruction::Shl || Info.isKnownNonNegative(Op1))) {
1467 LLVM_DEBUG(dbgs() << "Adding nuw to " << *I << "\n");
1468 I->setHasNoUnsignedWrap();
1469 Changed = true;
1470 }
1471 return Changed;
1472 }
1473 default:
1474 return false;
1475 }
1476}
1477
1478void State::addInfoFor(BasicBlock &BB) {
1479 addBoundsForHeaderInductions(BB);
1480 addInfoForInductions(BB);
1481 auto &DL = BB.getDataLayout();
1482
1483 Value *A, *B;
1484 CmpPredicate Pred;
1485 // True as long as the current instruction is guaranteed to execute.
1486 bool GuaranteedToExecute = true;
1487 // Queue conditions and assumes.
1488 for (Instruction &I : BB) {
1489 if (match(&I, m_ICmpLike(Pred, m_Value(), m_Value()))) {
1490 for (Use &U : I.uses()) {
1491 auto *UserI = getContextInstForUse(U);
1492 auto *DTN = DT.getNode(UserI->getParent());
1493 if (!DTN)
1494 continue;
1495 WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1496 }
1497 continue;
1498 }
1499
1500 auto AddFactFromMemoryAccess = [&](Value *Ptr, Type *AccessType) {
1501 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1502 if (!GEP)
1503 return;
1504 TypeSize AccessSize = DL.getTypeStoreSize(AccessType);
1505 if (!AccessSize.isFixed())
1506 return;
1507 if (GuaranteedToExecute) {
1509 Pred, A, B, DL, TLI)) {
1510 // The memory access is guaranteed to execute when BB is entered,
1511 // hence the constraint holds on entry to BB.
1512 WorkList.emplace_back(FactOrCheck::getConditionFact(
1513 DT.getNode(I.getParent()), Pred, A, B));
1514 }
1515 } else {
1516 WorkList.emplace_back(
1517 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1518 }
1519 };
1520
1521 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1522 if (!LI->isVolatile())
1523 AddFactFromMemoryAccess(LI->getPointerOperand(), LI->getAccessType());
1524 }
1525 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1526 if (!SI->isVolatile())
1527 AddFactFromMemoryAccess(SI->getPointerOperand(), SI->getAccessType());
1528 }
1529
1530 auto *II = dyn_cast<IntrinsicInst>(&I);
1531 Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1532 switch (ID) {
1533 case Intrinsic::assume: {
1534 if (!match(I.getOperand(0), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1535 break;
1536 if (GuaranteedToExecute) {
1537 // The assume is guaranteed to execute when BB is entered, hence Cond
1538 // holds on entry to BB.
1539 WorkList.emplace_back(FactOrCheck::getConditionFact(
1540 DT.getNode(I.getParent()), Pred, A, B));
1541 } else {
1542 WorkList.emplace_back(
1543 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1544 }
1545 break;
1546 }
1547 // Enqueue intrinsics for simplification.
1548 case Intrinsic::sadd_with_overflow:
1549 case Intrinsic::ssub_with_overflow:
1550 case Intrinsic::ucmp:
1551 case Intrinsic::scmp:
1552 WorkList.push_back(
1553 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1554 break;
1555 // Enqueue the intrinsics to add extra info.
1556 case Intrinsic::umin:
1557 case Intrinsic::umax:
1558 case Intrinsic::smin:
1559 case Intrinsic::smax:
1560 case Intrinsic::usub_sat:
1561 // TODO: handle llvm.abs as well
1562 WorkList.push_back(
1563 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1564 [[fallthrough]];
1565 case Intrinsic::uadd_sat:
1566 // TODO: Check if it is possible to instead only added the min/max facts
1567 // when simplifying uses of the min/max intrinsics.
1569 break;
1570 [[fallthrough]];
1571 case Intrinsic::abs:
1572 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1573 break;
1574 }
1575
1576 // Add facts from unsigned division, remainder and logical shift right, and
1577 // from signed remainder.
1578 // urem x, n: result < n and result <= x
1579 // udiv x, n: result <= x
1580 // lshr x, n: result <= x
1581 // srem x, n: result >= 0 and result <= x, if x >= 0
1582 // result < n, if n > 0
1583 if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1584 if ((BO->getOpcode() == Instruction::URem ||
1585 BO->getOpcode() == Instruction::UDiv ||
1586 BO->getOpcode() == Instruction::LShr ||
1587 BO->getOpcode() == Instruction::SRem) &&
1589 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), BO));
1590 }
1591
1592 // Queue instructions whose flags may be strengthened, checked at the
1593 // closest point dominating all uses.
1594 if (canStrengthenFlags(&I)) {
1595 Instruction *CommonDom = findCommonDominatorOfUses(I, DT);
1596 WorkList.push_back(FactOrCheck::getCheck(
1597 DT.getNode(CommonDom->getParent()), &I, CommonDom));
1598 }
1599
1600 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1601 }
1602
1603 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1604 for (auto &Case : Switch->cases()) {
1605 BasicBlock *Succ = Case.getCaseSuccessor();
1606 Value *V = Case.getCaseValue();
1607 if (!canAddSuccessor(BB, Succ))
1608 continue;
1609 WorkList.emplace_back(FactOrCheck::getConditionFact(
1610 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1611 }
1612 return;
1613 }
1614
1615 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1616 if (!Br)
1617 return;
1618
1619 Value *Cond = Br->getCondition();
1620
1621 // If the condition is a chain of ORs/AND and the successor only has the
1622 // current block as predecessor, queue conditions for the successor.
1623 Value *Op0, *Op1;
1624 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1625 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1626 bool IsOr = match(Cond, m_LogicalOr());
1627 bool IsAnd = match(Cond, m_LogicalAnd());
1628 // If there's a select that matches both AND and OR, we need to commit to
1629 // one of the options. Arbitrarily pick OR.
1630 if (IsOr && IsAnd)
1631 IsAnd = false;
1632
1633 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1634 if (canAddSuccessor(BB, Successor)) {
1635 SmallVector<Value *> CondWorkList;
1636 SmallPtrSet<Value *, 8> SeenCond;
1637 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1638 if (SeenCond.insert(V).second)
1639 CondWorkList.push_back(V);
1640 };
1641 QueueValue(Op1);
1642 QueueValue(Op0);
1643 while (!CondWorkList.empty()) {
1644 Value *Cur = CondWorkList.pop_back_val();
1645 if (match(Cur, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
1646 WorkList.emplace_back(FactOrCheck::getConditionFact(
1647 DT.getNode(Successor),
1648 IsOr ? CmpPredicate::getInverse(Pred) : Pred, A, B));
1649 continue;
1650 }
1651 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1652 QueueValue(Op1);
1653 QueueValue(Op0);
1654 continue;
1655 }
1656 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1657 QueueValue(Op1);
1658 QueueValue(Op0);
1659 continue;
1660 }
1661 }
1662 }
1663 return;
1664 }
1665
1666 if (!match(Br->getCondition(), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1667 return;
1668 if (canAddSuccessor(BB, Br->getSuccessor(0)))
1669 WorkList.emplace_back(FactOrCheck::getConditionFact(
1670 DT.getNode(Br->getSuccessor(0)), Pred, A, B));
1671 if (canAddSuccessor(BB, Br->getSuccessor(1)))
1672 WorkList.emplace_back(FactOrCheck::getConditionFact(
1673 DT.getNode(Br->getSuccessor(1)), CmpPredicate::getInverse(Pred), A, B));
1674}
1675
1676#ifndef NDEBUG
1678 Value *LHS, Value *RHS) {
1679 OS << "icmp " << Pred << ' ';
1680 LHS->printAsOperand(OS, /*PrintType=*/true);
1681 OS << ", ";
1682 RHS->printAsOperand(OS, /*PrintType=*/false);
1683}
1684#endif
1685
1686namespace {
1687/// Helper to keep track of a condition and if it should be treated as negated
1688/// for reproducer construction.
1689/// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1690/// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1691struct ReproducerEntry {
1692 ICmpInst::Predicate Pred;
1693 Value *LHS;
1694 Value *RHS;
1695
1696 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1697 : Pred(Pred), LHS(LHS), RHS(RHS) {}
1698};
1699} // namespace
1700
1701/// Helper function to generate a reproducer function for simplifying \p Cond.
1702/// The reproducer function contains a series of @llvm.assume calls, one for
1703/// each condition in \p Stack. For each condition, the operand instruction are
1704/// cloned until we reach operands that have an entry in \p Value2Index. Those
1705/// will then be added as function arguments. \p DT is used to order cloned
1706/// instructions. The reproducer function will get added to \p M, if it is
1707/// non-null. Otherwise no reproducer function is generated.
1708static void generateReproducer(Instruction *Cond, bool IsSigned, Module *M,
1710 ConstraintInfo &Info, DominatorTree &DT) {
1711 if (!M)
1712 return;
1713
1714 LLVMContext &Ctx = Cond->getContext();
1715
1716 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1717
1718 ValueToValueMapTy Old2New;
1721 // Traverse Cond and its operands recursively until we reach a value that's in
1722 // Value2Index or not an instruction, or not a operation that
1723 // ConstraintElimination can decompose. Such values will be considered as
1724 // external inputs to the reproducer, they are collected and added as function
1725 // arguments later.
1726 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1727 auto &Value2Index = Info.getValue2Index(IsSigned);
1728 SmallVector<Value *, 4> WorkList(Ops);
1729 while (!WorkList.empty()) {
1730 Value *V = WorkList.pop_back_val();
1731 if (!Seen.insert(V).second)
1732 continue;
1733 if (Old2New.find(V) != Old2New.end())
1734 continue;
1735 if (isa<Constant>(V))
1736 continue;
1737
1738 auto *I = dyn_cast<Instruction>(V);
1739 if (Value2Index.contains(V) || !I ||
1741 Old2New[V] = V;
1742 Args.push_back(V);
1743 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n");
1744 } else {
1745 append_range(WorkList, I->operands());
1746 }
1747 }
1748 };
1749
1750 for (auto &Entry : Stack)
1751 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1752 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1753 CollectArguments(Cond, IsSigned);
1754
1755 SmallVector<Type *> ParamTys;
1756 for (auto *P : Args)
1757 ParamTys.push_back(P->getType());
1758
1759 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1760 /*isVarArg=*/false);
1762 Cond->getModule()->getName() +
1763 Cond->getFunction()->getName() + "repro",
1764 M);
1765 // Add arguments to the reproducer function for each external value collected.
1766 for (unsigned I = 0; I < Args.size(); ++I) {
1767 F->getArg(I)->setName(Args[I]->getName());
1768 Old2New[Args[I]] = F->getArg(I);
1769 }
1770
1771 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1772 IRBuilder<> Builder(Entry);
1773 Builder.CreateRet(Builder.getTrue());
1774 Builder.SetInsertPoint(Entry->getTerminator());
1775
1776 // Clone instructions in \p Ops and their operands recursively until reaching
1777 // an value in Value2Index (external input to the reproducer). Update Old2New
1778 // mapping for the original and cloned instructions. Sort instructions to
1779 // clone by dominance, then insert the cloned instructions in the function.
1780 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1781 SmallVector<Value *, 4> WorkList(Ops);
1783 auto &Value2Index = Info.getValue2Index(IsSigned);
1784 while (!WorkList.empty()) {
1785 Value *V = WorkList.pop_back_val();
1786 if (Old2New.find(V) != Old2New.end())
1787 continue;
1788
1789 auto *I = dyn_cast<Instruction>(V);
1790 if (!Value2Index.contains(V) && I) {
1791 Old2New[V] = nullptr;
1792 ToClone.push_back(I);
1793 append_range(WorkList, I->operands());
1794 }
1795 }
1796
1797 sort(ToClone,
1798 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1799 for (Instruction *I : ToClone) {
1800 Instruction *Cloned = I->clone();
1801 Old2New[I] = Cloned;
1802 Old2New[I]->setName(I->getName());
1803 Cloned->insertBefore(Builder.GetInsertPoint());
1805 Cloned->setDebugLoc({});
1806 }
1807 };
1808
1809 // Materialize the assumptions for the reproducer using the entries in Stack.
1810 // That is, first clone the operands of the condition recursively until we
1811 // reach an external input to the reproducer and add them to the reproducer
1812 // function. Then add an ICmp for the condition (with the inverse predicate if
1813 // the entry is negated) and an assert using the ICmp.
1814 for (auto &Entry : Stack) {
1815 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1816 continue;
1817
1818 LLVM_DEBUG(dbgs() << " Materializing assumption ";
1819 dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
1820 dbgs() << "\n");
1821 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1822
1823 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1824 Builder.CreateAssumption(Cmp);
1825 }
1826
1827 // Finally, clone the condition to reproduce and remap instruction operands in
1828 // the reproducer using Old2New.
1829 CloneInstructions(Cond, IsSigned);
1830 Entry->getTerminator()->setOperand(0, Cond);
1831 remapInstructionsInBlocks({Entry}, Old2New);
1832
1833 assert(!verifyFunction(*F, &dbgs()));
1834}
1835
1836static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
1837 Value *B, Instruction *CheckInst,
1838 ConstraintInfo &Info) {
1839 LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1840
1841 auto TryWithConstraint = [&](const ConstraintTy &R) -> std::optional<bool> {
1842 if (R.empty()) {
1843 LLVM_DEBUG(dbgs() << " failed to decompose condition\n");
1844 return std::nullopt;
1845 }
1846
1847 auto &CSToUse = Info.getCS(R.IsSigned);
1848 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1849 if (!DebugCounter::shouldExecute(EliminatedCounter))
1850 return std::nullopt;
1851 LLVM_DEBUG({
1852 dbgs() << "Condition ";
1854 *ImpliedCondition ? Pred
1856 A, B);
1857 dbgs() << " implied by dominating constraints\n";
1858 CSToUse.dump();
1859 });
1860 return ImpliedCondition;
1861 }
1862 return std::nullopt;
1863 };
1864
1865 auto R = Info.getConstraintForSolving(Pred, A, B);
1866 if (auto ImpliedCondition = TryWithConstraint(R))
1867 return ImpliedCondition;
1868
1869 // For non-negative operands unsigned queries can also be checked against the
1870 // signed system.
1871 if (CmpInst::isUnsigned(Pred) && A->getType()->isIntegerTy()) {
1872 SmallVector<Value *> NewVariables;
1873 auto SR = Info.getConstraint(ICmpInst::getSignedPredicate(Pred), A, B,
1874 NewVariables);
1875 if (NewVariables.empty() && !SR.empty() && Info.isKnownNonNegative(A) &&
1876 Info.isKnownNonNegative(B))
1877 if (auto ImpliedCondition = TryWithConstraint(SR))
1878 return ImpliedCondition;
1879 }
1880
1881 // Additionally, query the signed system for eq/ne predicates if we know about
1882 // A or B.
1883 if (CmpInst::isEquality(Pred)) {
1884 const auto &Value2Index = Info.getValue2Index(/*Signed=*/true);
1885 if (!Value2Index.contains(A) && !Value2Index.contains(B))
1886 return std::nullopt;
1887
1888 SmallVector<Value *> NewVariables;
1889 auto SR = Info.getConstraint(Pred, A, B, NewVariables,
1890 /*ForceSignedSystem=*/true);
1891 if (NewVariables.empty())
1892 if (auto ImpliedCondition = TryWithConstraint(SR))
1893 return ImpliedCondition;
1894 }
1895 return std::nullopt;
1896}
1897
1899 CmpPredicate Pred, Value *A, Value *B, Instruction *CheckInst,
1900 ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1901 Instruction *ContextInst, Module *ReproducerModule,
1902 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1904 auto ReplaceCmpWithConstant = [&](Instruction *CheckInst, bool IsTrue) {
1905 generateReproducer(CheckInst, ICmpInst::isSigned(Pred), ReproducerModule,
1906 ReproducerCondStack, Info, DT);
1907 Constant *ConstantC = ConstantInt::getBool(
1908 CmpInst::makeCmpResultType(CheckInst->getType()), IsTrue);
1909 bool Changed = CheckInst->replaceUsesWithIf(ConstantC, [&](Use &U) {
1910 auto *UserI = getContextInstForUse(U);
1911 auto *DTN = DT.getNode(UserI->getParent());
1912 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1913 return false;
1914 if (UserI->getParent() == ContextInst->getParent() &&
1915 UserI->comesBefore(ContextInst))
1916 return false;
1917
1918 // Conditions in an assume trivially simplify to true. Skip uses
1919 // in assume calls to not destroy the available information.
1920 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1921 return !II || II->getIntrinsicID() != Intrinsic::assume;
1922 });
1923 NumCondsRemoved++;
1924
1925 // Update the debug value records that satisfy the same condition used
1926 // in replaceUsesWithIf.
1928 findDbgUsers(CheckInst, DVRUsers);
1929
1930 for (auto *DVR : DVRUsers) {
1931 auto *DTN = DT.getNode(DVR->getParent());
1932 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1933 continue;
1934
1935 auto *MarkedI = DVR->getInstruction();
1936 if (MarkedI->getParent() == ContextInst->getParent() &&
1937 MarkedI->comesBefore(ContextInst))
1938 continue;
1939
1940 DVR->replaceVariableLocationOp(CheckInst, ConstantC);
1941 }
1942
1943 if (CheckInst->use_empty())
1944 ToRemove.push_back(CheckInst);
1945
1946 return Changed;
1947 };
1948
1949 if (auto ImpliedCondition = checkCondition(Pred, A, B, CheckInst, Info))
1950 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
1951
1952 // When the predicate is samesign and unsigned, we can also make use of the
1953 // signed predicate information.
1954 if (Pred.hasSameSign() && ICmpInst::isUnsigned(Pred))
1955 if (auto ImpliedCondition = checkCondition(
1956 ICmpInst::getSignedPredicate(Pred), A, B, CheckInst, Info))
1957 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
1958
1959 return false;
1960}
1961
1962static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
1964 auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
1965 // TODO: generate reproducer for min/max.
1966 MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
1967 ToRemove.push_back(MinMax);
1968 return true;
1969 };
1970
1971 ICmpInst::Predicate Pred =
1972 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1973 if (auto ImpliedCondition = checkCondition(
1974 Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
1975 return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
1976 if (auto ImpliedCondition = checkCondition(
1977 Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
1978 return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
1979 return false;
1980}
1981
1982static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
1984 Value *LHS = I->getOperand(0);
1985 Value *RHS = I->getOperand(1);
1986 if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1987 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
1988 ToRemove.push_back(I);
1989 return true;
1990 }
1991 if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1992 I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
1993 ToRemove.push_back(I);
1994 return true;
1995 }
1996 if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
1997 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
1998 ToRemove.push_back(I);
1999 return true;
2000 }
2001 return false;
2002}
2003
2004/// Try to replace \p USub by a plain subtract, if \p Info proves it cannot
2005/// saturate. Returns true if \p USub was replaced.
2006static bool checkAndReplaceUSubSat(SaturatingInst *USub, ConstraintInfo &Info,
2008 // usub.sat(A, B) is A - B exactly when A >=u B.
2009 Value *A = USub->getLHS();
2010 Value *B = USub->getRHS();
2011 if (!checkCondition(CmpInst::ICMP_UGE, A, B, USub, Info).value_or(false))
2012 return false;
2013
2014 IRBuilder<> Builder(USub);
2015 Value *Sub = Builder.CreateSub(A, B, "", /*HasNUW=*/true,
2016 /*HasNSW=*/Info.isKnownNonNegative(A));
2017 USub->replaceAllUsesWith(Sub);
2018 Sub->takeName(USub);
2019 ToRemove.push_back(USub);
2020 return true;
2021}
2022
2023static void
2024removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
2025 Module *ReproducerModule,
2026 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2027 SmallVectorImpl<StackEntry> &DFSInStack) {
2028 Info.popLastConstraint(E.IsSigned);
2029 // Remove variables in the system that went out of scope.
2030 auto &Mapping = Info.getValue2Index(E.IsSigned);
2031 for (Value *V : E.ValuesToRelease)
2032 Mapping.erase(V);
2033 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
2034 DFSInStack.pop_back();
2035 if (ReproducerModule)
2036 ReproducerCondStack.pop_back();
2037}
2038
2039/// Check if either the first condition of an AND or OR is implied by the
2040/// (negated in case of OR) second condition or vice versa.
2042 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
2043 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2044 SmallVectorImpl<StackEntry> &DFSInStack,
2046 Instruction *JoinOp = CB.getContextInst();
2047 if (JoinOp->use_empty())
2048 return false;
2049
2050 Instruction *CmpToCheck = cast<Instruction>(CB.getInstructionToSimplify());
2051 unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
2052
2053 // Don't try to simplify the first condition of a select by the second, as
2054 // this may make the select more poisonous than the original one.
2055 // TODO: check if the first operand may be poison.
2056 if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
2057 return false;
2058
2059 unsigned OldSize = DFSInStack.size();
2060 llvm::scope_exit InfoRestorer([&]() {
2061 // Remove entries again.
2062 while (OldSize < DFSInStack.size()) {
2063 StackEntry E = DFSInStack.back();
2064 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
2065 DFSInStack);
2066 }
2067 });
2068 bool IsOr = match(JoinOp, m_LogicalOr());
2069 SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
2070 // Do a traversal of the AND/OR tree to add facts from leaf compares.
2071 while (!Worklist.empty()) {
2072 Value *Val = Worklist.pop_back_val();
2073 Value *LHS, *RHS;
2074 CmpPredicate Pred;
2075 if (match(Val, m_ICmpLike(Pred, m_Value(LHS), m_Value(RHS)))) {
2076 // For OR, check if the negated condition implies CmpToCheck.
2077 if (IsOr)
2078 Pred = CmpInst::getInversePredicate(Pred);
2079 // Optimistically add fact from the other compares in the AND/OR.
2080 Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
2081 continue;
2082 }
2083 if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
2084 : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
2085 Worklist.push_back(LHS);
2086 Worklist.push_back(RHS);
2087 }
2088 }
2089 if (OldSize == DFSInStack.size())
2090 return false;
2091
2092 Value *A, *B;
2093 CmpPredicate Pred;
2094 [[maybe_unused]] bool Matched =
2095 match(CmpToCheck, m_ICmpLike(Pred, m_Value(A), m_Value(B)));
2096 assert(Matched && "expected icmp-like match");
2097 // Check if the second condition can be simplified now.
2098 if (auto ImpliedCondition = checkCondition(Pred, A, B, CmpToCheck, Info)) {
2099 if (IsOr == *ImpliedCondition)
2100 JoinOp->replaceAllUsesWith(
2101 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
2102 else
2103 JoinOp->replaceAllUsesWith(JoinOp->getOperand(OtherOpIdx));
2104 ToRemove.push_back(JoinOp);
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
2112 unsigned NumIn, unsigned NumOut,
2113 SmallVectorImpl<StackEntry> &DFSInStack) {
2114 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, false);
2115 // If the Pred is eq/ne, also add the fact to signed system.
2116 if (CmpInst::isEquality(Pred))
2117 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, true);
2118 if (Pred == CmpInst::ICMP_NE)
2119 tightenBoundUsingNe(A, B, NumIn, NumOut, DFSInStack);
2120}
2121
2122void ConstraintInfo::tightenBoundUsingNe(
2123 Value *A, Value *B, unsigned NumIn, unsigned NumOut,
2124 SmallVectorImpl<StackEntry> &DFSInStack) {
2125 if (!A->getType()->isIntegerTy())
2126 return;
2127
2128 for (bool IsSigned : {false, true}) {
2129 // In the unsigned system `A u>= 0` holds for every A, so getConstraint
2130 // already turned `A != 0` into `A u> 0`.
2131 if (!IsSigned && match(B, m_Zero()))
2132 continue;
2133
2134 // Skip if there are any unknown variables.
2135 const auto &Value2Index = getValue2Index(IsSigned);
2136 if (any_of(decompose(A, *this, IsSigned, DL).Vars,
2137 [&Value2Index](const DecompEntry &E) {
2138 return !Value2Index.contains(E.Variable);
2139 }))
2140 continue;
2141
2142 // If the system implies `A >= B` then together with `A != B` we get the
2143 // strict `A > B`; symmetrically `A <= B` becomes `A < B`.
2144 CmpInst::Predicate GEPred =
2146 CmpInst::Predicate LEPred =
2148 for (CmpInst::Predicate NonStrict : {GEPred, LEPred}) {
2149 if (!doesHold(NonStrict, A, B))
2150 continue;
2152 LLVM_DEBUG(dbgs() << "Tightening '";
2153 dumpUnpackedICmp(dbgs(), NonStrict, A, B); dbgs() << "' to '";
2155 dbgs() << "' using inequality\n");
2156 addFactImpl(Strict, A, B, NumIn, NumOut, DFSInStack,
2157 /*ForceSignedSystem=*/false);
2158 break;
2159 }
2160 }
2161}
2162
2163void ConstraintInfo::addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B,
2164 unsigned NumIn, unsigned NumOut,
2165 SmallVectorImpl<StackEntry> &DFSInStack,
2166 bool ForceSignedSystem) {
2167 SmallVector<Value *> NewVariables;
2168 auto R = getConstraint(Pred, A, B, NewVariables, ForceSignedSystem);
2169
2170 // TODO: Support non-equality for facts as well.
2171 if (R.empty() || R.isNe())
2172 return;
2173
2174 LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
2175 dbgs() << "'\n");
2176 auto &CSToUse = getCS(R.IsSigned);
2177 bool Added = CSToUse.addRow(R.Coefficients, R.NumVars);
2178 if (!Added)
2179 return;
2180
2181 // If R has been added to the system, add the new variables and queue it for
2182 // removal once it goes out-of-scope.
2183 SmallVector<Value *, 2> ValuesToRelease;
2184 auto &Value2Index = getValue2Index(R.IsSigned);
2185 for (Value *V : NewVariables) {
2186 Value2Index.try_emplace(V, Value2Index.size() + 1);
2187 ValuesToRelease.push_back(V);
2188 }
2189
2190 LLVM_DEBUG({
2191 dbgs() << " constraint: ";
2192 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
2193 dbgs() << "\n";
2194 });
2195
2196 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2197 std::move(ValuesToRelease));
2198
2199 if (!R.IsSigned) {
2200 for (Value *V : NewVariables) {
2201 // Add V > -1 constraints for all new variables.
2202 CSToUse.addRow({Entry(0, 0), Entry(-1, Value2Index.at(V))},
2203 Value2Index.size());
2204 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2205 SmallVector<Value *, 2>());
2206 }
2207 }
2208
2209 if (R.isEq()) {
2210 // Also add the inverted constraint for equality constraints.
2211 for (Entry &E : R.Coefficients)
2212 if (MulOverflow(E.Coefficient, int64_t(-1), E.Coefficient))
2213 return;
2214 CSToUse.addRow(R.Coefficients, R.NumVars);
2215
2216 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2217 SmallVector<Value *, 2>());
2218 }
2219}
2220
2221/// Replace the uses of the overflow intrinsic \p II, which has been proven not
2222/// to signed-overflow, by (Opcode A, B).
2225 Value *B,
2227 bool Changed = false;
2228 IRBuilder<> Builder(II->getParent(), II->getIterator());
2229 Value *Res = nullptr;
2230 for (User *U : make_early_inc_range(II->users())) {
2231 if (match(U, m_ExtractValue<0>(m_Value()))) {
2232 if (!Res)
2233 Res = Builder.CreateNoWrapBinOp(Opcode, A, B, /*IsNUW=*/false,
2234 /*IsNSW=*/true);
2235 U->replaceAllUsesWith(Res);
2236 Changed = true;
2237 } else if (match(U, m_ExtractValue<1>(m_Value()))) {
2238 U->replaceAllUsesWith(Builder.getFalse());
2239 Changed = true;
2240 } else
2241 continue;
2242
2243 if (U->use_empty()) {
2244 auto *I = cast<Instruction>(U);
2245 ToRemove.push_back(I);
2246 I->setOperand(0, PoisonValue::get(II->getType()));
2247 Changed = true;
2248 }
2249 }
2250
2251 if (II->use_empty()) {
2252 // Do not erase II here: the worklist may still hold Uses of II's operands.
2253 for (Use &Arg : II->args())
2254 Arg.set(PoisonValue::get(Arg->getType()));
2255 ToRemove.push_back(II);
2256 Changed = true;
2257 }
2258 return Changed;
2259}
2260
2261static bool
2264 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
2265 ConstraintInfo &Info) {
2266 auto R = Info.getConstraintForSolving(Pred, A, B);
2267 // Nothing can be proven if the constraint has no variables. This also
2268 // covers rows that could not be decomposed, which are empty.
2269 if (R.isConstantOnly())
2270 return false;
2271
2272 auto &CSToUse = Info.getCS(R.IsSigned);
2273 return CSToUse.isConditionImpliedInSubSystem(R.Coefficients);
2274 };
2275
2276 switch (II->getIntrinsicID()) {
2277 case Intrinsic::ssub_with_overflow: {
2278 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
2279 // can be simplified to a regular sub.
2280 Value *A = II->getArgOperand(0);
2281 Value *B = II->getArgOperand(1);
2282 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
2283 !DoesConditionHold(CmpInst::ICMP_SGE, B,
2284 ConstantInt::get(A->getType(), 0), Info))
2285 return false;
2286 return replaceOverflowUses(II, Instruction::Sub, A, B, ToRemove);
2287 }
2288 case Intrinsic::sadd_with_overflow: {
2289 Value *A = II->getArgOperand(0);
2290 Value *B = II->getArgOperand(1);
2291 auto *C = dyn_cast<ConstantInt>(B);
2292 if (!C ||
2293 !doesHoldInRange(Info, A,
2295 Instruction::Add, ConstantRange(C->getValue()),
2297 /*Signed=*/true))
2298 return false;
2299 return replaceOverflowUses(II, Instruction::Add, A, B, ToRemove);
2300 }
2301 default:
2302 return false;
2303 }
2304}
2305
2307 ScalarEvolution &SE,
2309 TargetLibraryInfo &TLI) {
2310 bool Changed = false;
2311 DT.updateDFSNumbers();
2312 SmallVector<Value *> FunctionArgs(llvm::make_pointer_range(F.args()));
2313 ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
2314 State S(DT, LI, SE, TLI);
2315 std::unique_ptr<Module> ReproducerModule(
2316 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
2317
2318 // First, collect conditions implied by branches and blocks with their
2319 // Dominator DFS in and out numbers.
2320 for (BasicBlock &BB : F) {
2321 if (!DT.getNode(&BB))
2322 continue;
2323 S.addInfoFor(BB);
2324 }
2325
2326 // Next, sort worklist by dominance, so that dominating conditions to check
2327 // and facts come before conditions and facts dominated by them. If a
2328 // condition to check and a fact have the same numbers, conditional facts come
2329 // first. Assume facts and checks are ordered according to their relative
2330 // order in the containing basic block. Also make sure conditions with
2331 // constant operands come before conditions without constant operands. This
2332 // increases the effectiveness of the current signed <-> unsigned fact
2333 // transfer logic.
2334 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
2335 auto HasNoConstOp = [](const FactOrCheck &B) {
2336 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
2337 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
2338 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
2339 };
2340 // If both entries have the same In numbers, conditional facts come first.
2341 // Otherwise use the relative order in the basic block.
2342 if (A.NumIn == B.NumIn) {
2343 if (A.isConditionFact() && B.isConditionFact()) {
2344 bool NoConstOpA = HasNoConstOp(A);
2345 bool NoConstOpB = HasNoConstOp(B);
2346 return NoConstOpA < NoConstOpB;
2347 }
2348 if (A.isConditionFact())
2349 return true;
2350 if (B.isConditionFact())
2351 return false;
2352 auto *InstA = A.getContextInst();
2353 auto *InstB = B.getContextInst();
2354 return InstA->comesBefore(InstB);
2355 }
2356 return A.NumIn < B.NumIn;
2357 });
2358
2359 SmallVector<Instruction *> ToRemove;
2360
2361 // Finally, process ordered worklist and eliminate implied conditions.
2362 SmallVector<StackEntry, 16> DFSInStack;
2363 SmallVector<ReproducerEntry> ReproducerCondStack;
2364 for (FactOrCheck &CB : S.WorkList) {
2365 // First, pop entries from the stack that are out-of-scope for CB. Remove
2366 // the corresponding entry from the constraint system.
2367 while (!DFSInStack.empty()) {
2368 auto &E = DFSInStack.back();
2369 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
2370 << "\n");
2371 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
2372 assert(E.NumIn <= CB.NumIn);
2373 if (CB.NumOut <= E.NumOut)
2374 break;
2375 LLVM_DEBUG({
2376 dbgs() << "Removing ";
2377 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
2378 Info.getValue2Index(E.IsSigned));
2379 dbgs() << "\n";
2380 });
2381 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
2382 DFSInStack);
2383 }
2384
2385 CmpPredicate Pred;
2386 Value *A, *B;
2387 // For a block, check if any CmpInsts become known based on the current set
2388 // of constraints.
2389 if (CB.isCheck()) {
2390 Instruction *Inst = CB.getInstructionToSimplify();
2391 if (!Inst)
2392 continue;
2393 if (canStrengthenFlags(Inst)) {
2394 Changed |= tryToStrengthenFlags(Inst, Info, ToRemove);
2395 continue;
2396 }
2397 LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
2398 << "\n");
2399 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
2401 } else if (match(Inst, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
2403 Pred, A, B, Inst, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
2404 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
2405 if (!Simplified &&
2406 match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
2408 CB, Info, ReproducerModule.get(), ReproducerCondStack, DFSInStack,
2409 ToRemove);
2410 }
2412 } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
2413 Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
2414 } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
2415 Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
2416 } else if (match(Inst, m_Intrinsic<Intrinsic::usub_sat>())) {
2417 Changed |=
2419 }
2420 continue;
2421 }
2422
2423 auto AddFact = [&](CmpPredicate Pred, Value *A, Value *B) {
2424 LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
2425 dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
2426 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
2427 LLVM_DEBUG(
2428 dbgs()
2429 << "Skip adding constraint because system has too many rows.\n");
2430 return;
2431 }
2432
2433 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
2434 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
2435 ReproducerCondStack.emplace_back(Pred, A, B);
2436
2437 if (ICmpInst::isRelational(Pred)) {
2438 // If samesign is present on the ICmp, simply flip the sign of the
2439 // predicate, transferring the information from the signed system to the
2440 // unsigned system, and viceversa.
2441 if (Pred.hasSameSign())
2443 CB.NumIn, CB.NumOut, DFSInStack);
2444 else
2445 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut,
2446 DFSInStack);
2447 }
2448
2449 // (X | Y) >s -1 implies X >s -1 and Y >s -1, because the sign bit of an
2450 // OR is the OR of the operand sign bits. Similarly, (X & Y) <s 0 implies
2451 // X <s 0 and Y <s 0. Look through these canonical forms produced by
2452 // InstCombine so the sign facts on the operands are available to the
2453 // solver.
2454 if ((Pred == CmpInst::ICMP_SGT && match(B, m_AllOnes())) ||
2455 (Pred == CmpInst::ICMP_SLT && match(B, m_Zero()))) {
2456 unsigned Opc =
2457 Pred == CmpInst::ICMP_SGT ? Instruction::Or : Instruction::And;
2458 SmallVector<Value *> Worklist = {A};
2459 SmallPtrSet<Value *, 4> Seen;
2460 while (!Worklist.empty()) {
2461 Value *Cur = Worklist.pop_back_val();
2462 auto *BO = dyn_cast<BinaryOperator>(Cur);
2463 if (!BO || BO->getOpcode() != Opc)
2464 continue;
2465 for (Value *Op : {BO->getOperand(0), BO->getOperand(1)}) {
2466 if (!Seen.insert(Op).second)
2467 continue;
2468 Worklist.push_back(Op);
2469 Info.addFact(Pred, Op, B, CB.NumIn, CB.NumOut, DFSInStack);
2470 }
2471 }
2472 }
2473
2474 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
2475 // Add dummy entries to ReproducerCondStack to keep it in sync with
2476 // DFSInStack.
2477 for (unsigned I = 0,
2478 E = (DFSInStack.size() - ReproducerCondStack.size());
2479 I < E; ++I) {
2480 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
2481 nullptr, nullptr);
2482 }
2483 }
2484 };
2485
2486 if (!CB.isConditionFact()) {
2487 Value *X;
2488 if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
2489 // If is_int_min_poison is true then we may assume llvm.abs >= 0.
2490 if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
2491 AddFact(CmpInst::ICMP_SGE, CB.Inst,
2492 ConstantInt::get(CB.Inst->getType(), 0));
2493 AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
2494 continue;
2495 }
2496
2497 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
2498 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
2499 AddFact(Pred, MinMax, MinMax->getLHS());
2500 AddFact(Pred, MinMax, MinMax->getRHS());
2501 continue;
2502 }
2503 if (auto *USatI = dyn_cast<SaturatingInst>(CB.Inst)) {
2504 switch (USatI->getIntrinsicID()) {
2505 default:
2506 llvm_unreachable("Unexpected intrinsic.");
2507 case Intrinsic::uadd_sat:
2508 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getLHS());
2509 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getRHS());
2510 break;
2511 case Intrinsic::usub_sat:
2512 AddFact(ICmpInst::ICMP_ULE, USatI, USatI->getLHS());
2513 break;
2514 }
2515 continue;
2516 }
2517
2518 if (auto *BO = dyn_cast<BinaryOperator>(CB.Inst)) {
2519 if (BO->getOpcode() == Instruction::URem) {
2520 // urem x, n: result < n (remainder is always less than divisor)
2521 AddFact(CmpInst::ICMP_ULT, BO, BO->getOperand(1));
2522 // urem x, n: result <= x (remainder is at most the dividend)
2523 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2524 continue;
2525 }
2526 if (BO->getOpcode() == Instruction::UDiv) {
2527 // udiv x, n: result <= x (quotient is at most the dividend)
2528 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2529 continue;
2530 }
2531 if (BO->getOpcode() == Instruction::LShr) {
2532 // lshr x, n: result <= x (right shift cannot increase the value)
2533 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2534 continue;
2535 }
2536 if (BO->getOpcode() == Instruction::SRem) {
2537 Value *X = BO->getOperand(0);
2538 Value *N = BO->getOperand(1);
2539 Constant *Zero = Constant::getNullValue(BO->getType());
2540 if (Info.doesHold(CmpInst::ICMP_SGE, X, Zero) ||
2541 isKnownNonNegative(X, F.getDataLayout())) {
2542 // srem x, n: result >= 0, if x >= 0 (result has the sign of x)
2543 AddFact(CmpInst::ICMP_SGE, BO, Zero);
2544 // srem x, n: result <= x, if x >= 0 (|result| <= |x| and both are
2545 // non-negative)
2546 AddFact(CmpInst::ICMP_SLE, BO, X);
2547 }
2548 if (Info.doesHold(CmpInst::ICMP_SGE, N, Zero) ||
2549 isKnownPositive(N, F.getDataLayout())) {
2550 // srem x, n: result <= n, if n >= 0 (|result| < n, so result <= n -
2551 // 1
2552 AddFact(CmpInst::ICMP_SLT, BO, N);
2553 }
2554 continue;
2555 }
2556 }
2557
2558 auto &DL = F.getDataLayout();
2559 auto AddFactsAboutIndices = [&](Value *Ptr, Type *AccessType) {
2560 CmpPredicate Pred;
2561 Value *A, *B;
2564 DL.getTypeStoreSize(AccessType).getFixedValue(), Pred, A, B, DL,
2565 TLI))
2566 AddFact(Pred, A, B);
2567 };
2568
2569 if (auto *LI = dyn_cast<LoadInst>(CB.Inst)) {
2570 AddFactsAboutIndices(LI->getPointerOperand(), LI->getAccessType());
2571 continue;
2572 }
2573 if (auto *SI = dyn_cast<StoreInst>(CB.Inst)) {
2574 AddFactsAboutIndices(SI->getPointerOperand(), SI->getAccessType());
2575 continue;
2576 }
2577 }
2578
2579 if (CB.isConditionFact()) {
2580 Pred = CB.Cond.Pred;
2581 A = CB.Cond.Op0;
2582 B = CB.Cond.Op1;
2583 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
2584 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
2585 LLVM_DEBUG({
2586 dbgs() << "Not adding fact ";
2587 dumpUnpackedICmp(dbgs(), Pred, A, B);
2588 dbgs() << " because precondition ";
2589 dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
2590 CB.DoesHold.Op1);
2591 dbgs() << " does not hold.\n";
2592 });
2593 continue;
2594 }
2595 } else {
2596 [[maybe_unused]] bool Matched =
2598 m_ICmpLike(Pred, m_Value(A), m_Value(B))));
2599 assert(Matched &&
2600 "Must have an assume intrinsic with a icmp like operand");
2601 }
2602 AddFact(Pred, A, B);
2603 }
2604
2605 if (ReproducerModule && !ReproducerModule->functions().empty()) {
2606 std::string S;
2607 raw_string_ostream StringS(S);
2608 ReproducerModule->print(StringS, nullptr);
2609 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
2610 Rem << ore::NV("module") << S;
2611 ORE.emit(Rem);
2612 }
2613
2614#ifndef NDEBUG
2615 unsigned SignedEntries =
2616 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
2617 assert(Info.getCS(false).size() - FunctionArgs.size() ==
2618 DFSInStack.size() - SignedEntries &&
2619 "updates to CS and DFSInStack are out of sync");
2620 assert(Info.getCS(true).size() == SignedEntries &&
2621 "updates to CS and DFSInStack are out of sync");
2622#endif
2623
2624 for (Instruction *I : ToRemove)
2625 I->eraseFromParent();
2626 return Changed;
2627}
2628
2631 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2632 auto &LI = AM.getResult<LoopAnalysis>(F);
2633 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
2635 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2636 if (!eliminateConstraints(F, DT, LI, SE, ORE, TLI))
2637 return PreservedAnalyses::all();
2638
2642 return PA;
2643}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
std::pair< ICmpInst *, unsigned > ConditionTy
static int64_t MaxConstraintValue
static bool canStrengthenFlags(Instruction *I)
Returns true if I is a candidate whose poison-generating flags may be strengthened using the constrai...
static int64_t MinSignedConstraintValue
static auto m_IncrementOf(const PhiMatchTy &PhiM, const APInt *&Off)
Matches an increment of PhiM by a constant offset, captured in Off.
static Instruction * getContextInstForUse(Use &U)
static bool replaceOverflowUses(IntrinsicInst *II, Instruction::BinaryOps Opcode, Value *A, Value *B, SmallVectorImpl< Instruction * > &ToRemove)
Replace the uses of the overflow intrinsic II, which has been proven not to signed-overflow,...
static bool doesHoldInRange(const ConstraintInfo &Info, Value *Op, const ConstantRange &R, bool Signed)
Returns true if Info implies that Op is in R, interpreting R as a signed range if Signed is set and a...
static bool preconditionHolds(const ConstraintInfo &Info, CmpInst::Predicate Pred, Value *Op, int64_t RHS)
Returns true if the pre-condition Op Pred RHS, required to look through an expression while decomposi...
static bool canUseSExt(ConstantInt *CI)
static bool tryToStrengthenBinOpFlags(Instruction *I, Value *Op0, Value *Op1, ConstraintInfo &Info)
static void removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack)
static std::optional< bool > checkCondition(CmpInst::Predicate Pred, Value *A, Value *B, Instruction *CheckInst, ConstraintInfo &Info)
static cl::opt< unsigned > MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, cl::desc("Maximum number of rows to keep in constraint system"))
static cl::opt< bool > DumpReproducers("constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, cl::desc("Dump IR to reproduce successful transformations."))
static bool checkOrAndOpImpliedByOther(FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack, SmallVectorImpl< Instruction * > &ToRemove)
Check if either the first condition of an AND or OR is implied by the (negated in case of OR) second ...
static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, OptimizationRemarkEmitter &ORE, TargetLibraryInfo &TLI)
static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL)
static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static Decomposition decompose(Value *V, const ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
static Decomposition decomposeGEP(GEPOperator &GEP, const ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
static void dumpConstraint(ArrayRef< Entry > C, const DenseMap< Value *, unsigned > &Value2Index)
static bool getConstraintFromMemoryAccess(GetElementPtrInst &GEP, uint64_t AccessSize, CmpPredicate &Pred, Value *&A, Value *&B, const DataLayout &DL, const TargetLibraryInfo &TLI)
static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
static void generateReproducer(Instruction *Cond, bool IsSigned, Module *M, ArrayRef< ReproducerEntry > Stack, ConstraintInfo &Info, DominatorTree &DT)
Helper function to generate a reproducer function for simplifying Cond.
static bool checkAndReplaceUSubSat(SaturatingInst *USub, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
Try to replace USub by a plain subtract, if Info proves it cannot saturate.
static bool checkAndReplaceCondition(CmpPredicate Pred, Value *A, Value *B, Instruction *CheckInst, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, Instruction *ContextInst, Module *ReproducerModule, ArrayRef< ReproducerEntry > ReproducerCondStack, DominatorTree &DT, SmallVectorImpl< Instruction * > &ToRemove)
static bool tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static Instruction * findCommonDominatorOfUses(Instruction &I, DominatorTree &DT)
Returns the closest program point dominating all uses of I.
static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
Try to strengthen I's poison generating flags using Info.
static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static std::pair< Value *, Value * > getStartAndBackedgeValue(const PHINode &PN, const BasicBlock *LoopPred)
Splits the induction phi PN into the start value, coming from the loop predecessor LoopPred,...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
This class represents a ucmp/scmp intrinsic.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getInverse(CmpPredicate P)
Get the inverse predicate of a CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isNegative() const
Definition Constants.h:214
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
bool addRow(ArrayRef< Entry > R, size_t NumVars)
static RowTy negate(RowTy R)
LLVM_ABI std::pair< ConstraintSystem, RowTy > getSubSystem(ArrayRef< Entry > R) const
Build and return a sub-system of constraints connected (transitively) to query R, with variables comp...
static RowTy toStrictLessThan(RowTy R)
Converts the given row to form a strict less than inequality.
SmallVector< Entry, 8 > RowTy
A single constraint of the form 'c >= v1 * c1 + ... + vn * cn'.
static RowTy negateOrEqual(RowTy R)
Multiplies each coefficient in the given row by -1.
LLVM_ABI void dump() const
Print the constraints in the system.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static bool shouldExecute(CounterInfo &Counter)
unsigned size() const
Definition DenseMap.h:200
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
NodeT * getBlock() const
unsigned getDFSNumOut() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2908
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
size_type size() const
Definition MapVector.h:58
This class represents min/max intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Represents a saturating add/sub intrinsic.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
MonotonicPredicateType
A predicate is said to be monotonically increasing if may go from being false to being true as the lo...
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void truncate(size_type N)
Like resize, but requires that N is less than size().
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI const Value * stripPointerCastsSameRepresentation() const
Strip off pointer casts, all-zero GEPs and address space casts but ensures the representation of the ...
Definition Value.cpp:721
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:561
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2116
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > SubOverflow(T X, T Y)
Subtract two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:735
constexpr unsigned MaxAnalysisRecursionDepth
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:772
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342