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 "ScalarOptions.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/Statistic.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Module.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
47
48#include <optional>
49#include <string>
50
51using namespace llvm;
52using namespace PatternMatch;
53using namespace SCEVPatternMatch;
54
55#define DEBUG_TYPE "constraint-elimination"
56
57STATISTIC(NumCondsRemoved, "Number of instructions removed");
58DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
59 "Controls which conditions are eliminated");
60
61static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
62static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
63
65 Instruction *UserI = cast<Instruction>(U.getUser());
66 if (auto *Phi = dyn_cast<PHINode>(UserI))
67 UserI = Phi->getIncomingBlock(U)->getTerminator();
68 return UserI;
69}
70
71/// Returns the closest program point dominating all uses of \p I.
73 DominatorTree &DT) {
74 Instruction *CommonDom = nullptr;
75 unsigned NumUses = 0;
76 for (Use &U : I.uses()) {
77 // Conservatively use original instruction, if there are too many uses.
78 if (++NumUses == 16)
79 return &I;
81 CommonDom =
82 CommonDom ? DT.findNearestCommonDominator(CommonDom, UserI) : UserI;
83 }
84 if (!CommonDom)
85 return &I;
86 // Uses in unreachable blocks are not in the dominator tree.
87 return DT.getNode(CommonDom->getParent()) ? CommonDom : &I;
88}
89
90namespace {
91using Entry = ConstraintSystem::Entry;
92using RowTy = ConstraintSystem::RowTy;
93
94/// Struct to express a condition of the form %Op0 Pred %Op1.
95struct ConditionTy {
96 CmpPredicate Pred;
97 Value *Op0 = nullptr;
98 Value *Op1 = nullptr;
99
100 ConditionTy() = default;
101 ConditionTy(CmpPredicate Pred, Value *Op0, Value *Op1)
102 : Pred(Pred), Op0(Op0), Op1(Op1) {}
103};
104
105/// Represents either
106/// * a condition that holds on entry to a block (=condition fact)
107/// * an assume (=assume fact)
108/// * a use of a compare instruction to simplify.
109/// It also tracks the Dominator DFS in and out numbers for each entry.
110struct FactOrCheck {
111 enum class EntryTy {
112 ConditionFact, /// A condition that holds on entry to a block.
113 InstFact, /// A fact that holds after Inst executed (e.g. an assume or
114 /// min/mix intrinsic.
115 InstCheck, /// An instruction to simplify (e.g. an overflow math
116 /// intrinsics) or whose flags may be strengthened.
117 UseCheck /// An use of a compare instruction to simplify.
118 };
119
120 union {
121 Instruction *Inst;
122 Use *U;
124 };
125
126 union {
127 /// A pre-condition that must hold for the current fact to be added to the
128 /// system. Only used by condition facts.
129 ConditionTy DoesHold;
130
131 /// Context instruction for the point where conditions are checked for
132 /// InstCheck simplifications.
133 Instruction *ContextInst;
134 };
135
136 unsigned NumIn;
137 unsigned NumOut;
138 EntryTy Ty;
139
140 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst,
141 Instruction *ContextInst = nullptr)
142 : Inst(Inst), ContextInst(ContextInst ? ContextInst : Inst),
143 NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), Ty(Ty) {}
144
145 FactOrCheck(DomTreeNode *DTN, Use *U)
146 : U(U), ContextInst(nullptr), NumIn(DTN->getDFSNumIn()),
147 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::UseCheck) {}
148
149 FactOrCheck(DomTreeNode *DTN, CmpPredicate Pred, Value *Op0, Value *Op1,
150 ConditionTy Precond = {})
151 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
152 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
153
154 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpPredicate Pred,
155 Value *Op0, Value *Op1,
156 ConditionTy Precond = {}) {
157 return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
158 }
159
160 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
161 return FactOrCheck(EntryTy::InstFact, DTN, Inst);
162 }
163
164 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
165 return FactOrCheck(DTN, U);
166 }
167
168 static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *I,
169 Instruction *ContextInst = nullptr) {
170 assert((ContextInst ? ContextInst : I)->getParent() == DTN->getBlock() &&
171 "anchoring instruction must be in DTN's block");
172 return FactOrCheck(EntryTy::InstCheck, DTN, I, ContextInst);
173 }
174
175 bool isCheck() const {
176 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
177 }
178
179 Instruction *getContextInst() const {
180 assert(!isConditionFact());
181 if (Ty == EntryTy::UseCheck)
182 return getContextInstForUse(*U);
183 return ContextInst;
184 }
185
186 Instruction *getInstructionToSimplify() const {
187 assert(isCheck());
188 if (Ty == EntryTy::InstCheck)
189 return Inst;
190 // The use may have been simplified to a constant already.
191 return dyn_cast<Instruction>(*U);
192 }
193
194 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
195};
196
197/// The senses in which an induction phi is monotonic, together with the
198/// direction it moves in.
199struct MonotonicInfo {
200 /// True if the phi steps by a negative constant.
201 bool Decreasing = false;
202 /// True if the phi is monotonic in the unsigned sense.
203 bool Unsigned = false;
204 /// True if the phi is monotonic in the signed sense.
205 bool Signed = false;
206};
207
208/// Keep state required to build worklist.
209struct State {
210 DominatorTree &DT;
211 LoopInfo &LI;
212 /// Only available for functions with loops.
213 ScalarEvolution *SE;
214 TargetLibraryInfo &TLI;
216
217 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE,
218 TargetLibraryInfo &TLI)
219 : DT(DT), LI(LI), SE(SE), TLI(TLI) {}
220
221 /// Process block \p BB and add known facts to work-list.
222 void addInfoFor(BasicBlock &BB);
223
224 /// If \p BB is a loop header, bound each induction phi in it by its start
225 /// value.
226 void addBoundsForHeaderInductions(BasicBlock &BB);
227
228 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
229 /// controlling the loop header.
230 void addInfoForInductions(BasicBlock &BB);
231
232 /// Returns the direction the induction phi \p PN with backedge value \p Step
233 /// moves in, and the senses in which it is monotonic in that direction.
234 MonotonicInfo getMonotonicityInfo(PHINode &PN, Value *Step);
235
236 /// Returns true if we can add a known condition from BB to its successor
237 /// block Succ.
238 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
239 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
240 }
241};
242
243class ConstraintInfo;
244
245struct StackEntry {
246 unsigned NumIn;
247 unsigned NumOut;
248 bool IsSigned = false;
249 /// Variables that can be removed from the system once the stack entry gets
250 /// removed.
251 SmallVector<Value *, 2> ValuesToRelease;
252
253 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
254 SmallVector<Value *, 2> ValuesToRelease)
255 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
256 ValuesToRelease(std::move(ValuesToRelease)) {}
257};
258
259struct ConstraintTy {
260 RowTy Coefficients;
261
262 /// Number of variables the constraint is defined over.
263 unsigned NumVars = 0;
264
265 bool IsSigned = false;
266
267 ConstraintTy() = default;
268
269 ConstraintTy(RowTy Coefficients, unsigned NumVars, bool IsSigned, bool IsEq,
270 bool IsNe)
271 : Coefficients(std::move(Coefficients)), NumVars(NumVars),
272 IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {}
273
274 bool empty() const { return Coefficients.empty(); }
275
276 bool isEq() const { return IsEq; }
277
278 bool isNe() const { return IsNe; }
279
280 /// Check if the current constraint is implied by the given ConstraintSystem.
281 ///
282 /// \return true or false if the constraint is proven to be respectively true,
283 /// or false. When the constraint cannot be proven to be either true or false,
284 /// std::nullopt is returned.
285 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
286
287private:
288 bool IsEq = false;
289 bool IsNe = false;
290};
291
292/// Represents a (Coefficient * Variable) entry after IR decomposition.
293struct DecompEntry {
294 int64_t Coefficient;
295 Value *Variable;
296
297 DecompEntry(int64_t Coefficient, Value *Variable)
298 : Coefficient(Coefficient), Variable(Variable) {}
299};
300
301/// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
302struct Decomposition {
303 int64_t Offset = 0;
305
306 Decomposition(int64_t Offset) : Offset(Offset) {}
307 Decomposition(Value *V) { Vars.emplace_back(1, V); }
308 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
309 : Offset(Offset), Vars(Vars) {}
310
311 /// Add \p OtherOffset and return true if the operation overflows, i.e. the
312 /// new decomposition is invalid.
313 [[nodiscard]] bool add(int64_t OtherOffset) {
314 return AddOverflow(Offset, OtherOffset, Offset);
315 }
316
317 /// Add \p Other and return true if the operation overflows, i.e. the new
318 /// decomposition is invalid.
319 [[nodiscard]] bool add(const Decomposition &Other) {
320 if (add(Other.Offset))
321 return true;
322 append_range(Vars, Other.Vars);
323 return false;
324 }
325
326 /// Subtract \p Other and return true if the operation overflows, i.e. the new
327 /// decomposition is invalid.
328 [[nodiscard]] bool sub(const Decomposition &Other) {
329 Decomposition Tmp = Other;
330 if (Tmp.mul(-1))
331 return true;
332 if (add(Tmp.Offset))
333 return true;
334 append_range(Vars, Tmp.Vars);
335 return false;
336 }
337
338 /// Multiply all coefficients by \p Factor and return true if the operation
339 /// overflows, i.e. the new decomposition is invalid.
340 [[nodiscard]] bool mul(int64_t Factor) {
341 if (MulOverflow(Offset, Factor, Offset))
342 return true;
343 for (auto &Var : Vars)
344 if (MulOverflow(Var.Coefficient, Factor, Var.Coefficient))
345 return true;
346 return false;
347 }
348};
349
350/// Wrapper encapsulating separate constraint systems and corresponding value
351/// mappings for both unsigned and signed information. Facts are added to and
352/// conditions are checked against the corresponding system depending on the
353/// signed-ness of their predicates. While the information is kept separate
354/// based on signed-ness, certain conditions can be transferred between the two
355/// systems.
356class ConstraintInfo {
357
358 ConstraintSystem UnsignedCS;
359 ConstraintSystem SignedCS;
360
361 const DataLayout &DL;
362
363 /// Decompositions computed against the current state of the systems. Must be
364 /// cleared when the system changes.
365 DenseMap<PointerIntPair<Value *, 1, bool>, Decomposition> DecomposeCache;
366
367public:
368 DenseMap<PointerIntPair<Value *, 1, bool>, Decomposition> &
369 getDecomposeCache() {
370 return DecomposeCache;
371 }
372
373 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
374 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
375 auto &Value2Index = getValue2Index(false);
376 // Add Arg > -1 constraints to unsigned system for all function arguments.
377 for (Value *Arg : FunctionArgs)
378 UnsignedCS.addRow({Entry(0, 0), Entry(-1, Value2Index.at(Arg))},
379 Value2Index.size());
380 }
381
382 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
383 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
384 }
385 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
386 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
387 }
388
389 ConstraintSystem &getCS(bool Signed) {
390 return Signed ? SignedCS : UnsignedCS;
391 }
392 const ConstraintSystem &getCS(bool Signed) const {
393 return Signed ? SignedCS : UnsignedCS;
394 }
395
396 void popLastConstraint(bool Signed) {
397 assert(DecomposeCache.empty() && "Cache must be cleared");
398 getCS(Signed).popLastConstraint();
399 }
400 void popLastNVariables(bool Signed, unsigned N) {
401 assert(DecomposeCache.empty() && "Cache must be cleared");
402 getCS(Signed).popLastNVariables(N);
403 }
404
405 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B);
406
407 /// Returns the result of \p Solve. If it does not return a value, retries
408 /// after adding A == decompose(A) and B == decompose(B) to the system of \p
409 /// C, if needed, and removes them afterwards.
410 std::optional<bool>
411 tryWithLinkRows(Value *A, Value *B, const ConstraintTy &C,
412 function_ref<std::optional<bool>()> Solve);
413
414 /// Returns true if \p V is known to be non-negative, either because the
415 /// signed system implies it or because ValueTracking can prove it.
417
418 /// Returns true if \p V is known to be positive, either because the signed
419 /// system implies it or because ValueTracking can prove it.
420 bool isKnownPositive(Value *V);
421
422 /// Returns the sign of \p V, if known. The result is false if \p V is known
423 /// to be non-negative. Otherwise it is true if \p V is known to be negative
424 /// (if \p StrictlyNegative), or non-positive (if not \p StrictlyNegative).
425 /// Returns std::nullopt if neither ValueTracking, nor the signed system can
426 /// prove either fact.
427 std::optional<bool> getKnownSign(Value *V, bool StrictlyNegative);
428
429 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
430 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
431
432 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
433 /// constraints, using indices from the corresponding constraint system.
434 /// New variables that need to be added to the system are collected in
435 /// \p NewVariables.
436 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
437 SmallVectorImpl<Value *> &NewVariables,
438 bool ForceSignedSystem = false);
439
440 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
441 /// constraints using getConstraint. Returns an empty constraint if the result
442 /// cannot be used to query the existing constraint system, e.g. because it
443 /// would require adding new variables. Also tries to convert signed
444 /// predicates to unsigned ones if possible to allow using the unsigned system
445 /// which increases the effectiveness of the signed <-> unsigned transfer
446 /// logic.
447 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
448 Value *Op1);
449
450 /// Try to add information from \p A \p Pred \p B to the unsigned/signed
451 /// system if \p Pred is signed/unsigned.
452 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
453 unsigned NumIn, unsigned NumOut,
454 SmallVectorImpl<StackEntry> &DFSInStack);
455
456private:
457 /// Adds facts into constraint system. \p ForceSignedSystem can be set when
458 /// the \p Pred is eq/ne, and signed constraint system is used when it's
459 /// specified.
460 void addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
461 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack,
462 bool ForceSignedSystem);
463
464 /// Try to use the inequality \p A != \p B to tighten a non-strict bound the
465 /// system already implies to the corresponding strict bound.
466 void tightenBoundUsingNe(Value *A, Value *B, unsigned NumIn, unsigned NumOut,
467 SmallVectorImpl<StackEntry> &DFSInStack);
468};
469
470// Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
471struct OffsetResult {
472 Value *BasePtr;
473 APInt ConstantOffset;
474 SmallMapVector<Value *, APInt, 4> VariableOffsets;
475 GEPNoWrapFlags NW;
476
477 OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
478
479 OffsetResult(GEPOperator &GEP, const DataLayout &DL)
480 : BasePtr(GEP.getPointerOperand()), NW(GEP.getNoWrapFlags()) {
481 ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
482 }
483};
484} // namespace
485
486// Try to collect variable and constant offsets for \p GEP, partly traversing
487// nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
488// the offset fails.
490 OffsetResult Result(GEP, DL);
491 unsigned BitWidth = Result.ConstantOffset.getBitWidth();
492 if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
493 Result.ConstantOffset))
494 return {};
495
496 // If we have a nested GEP, check if we can combine the constant offset of the
497 // inner GEP with the outer GEP.
498 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
499 SmallMapVector<Value *, APInt, 4> VariableOffsets2;
500 APInt ConstantOffset2(BitWidth, 0);
501 bool CanCollectInner = InnerGEP->collectOffset(
502 DL, BitWidth, VariableOffsets2, ConstantOffset2);
503 // TODO: Support cases with more than 1 variable offset.
504 if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
505 VariableOffsets2.size() > 1 ||
506 (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
507 // More than 1 variable index, use outer result.
508 return Result;
509 }
510 // The GEPs' wrap flags do not prevent the sum of the offsets from
511 // sign-wrapping.
512 bool Overflow = false;
513 APInt CombinedOffset =
514 Result.ConstantOffset.sadd_ov(ConstantOffset2, Overflow);
515 if (Overflow)
516 return Result;
517
518 Result.BasePtr = InnerGEP->getPointerOperand();
519 Result.ConstantOffset = CombinedOffset;
520 if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
521 Result.VariableOffsets = std::move(VariableOffsets2);
522 Result.NW &= InnerGEP->getNoWrapFlags();
523 }
524 return Result;
525}
526
527static Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned,
528 const DataLayout &DL);
529
530static bool canUseSExt(ConstantInt *CI) {
531 const APInt &Val = CI->getValue();
533}
534
535/// Returns true if `Op <= MaxVal - Slack` holds in the system for \p Signed, by
536/// scanning it for a row of the form `Op - W <= -Slack`, where W is an integer
537/// variable no wider than \p Op. If \p Upper is false, returns true if
538/// `Op >= MinVal + Slack` holds, using rows of the form `W - Op <= -Slack`.
539static bool hasLimitWitness(const ConstraintInfo &Info, Value *Op,
540 const APInt &Slack, bool Signed, bool Upper) {
541 if (!Slack.isIntN(63))
542 return false;
543 int64_t RequiredOffset = -static_cast<int64_t>(Slack.getZExtValue());
544
545 const auto &Value2Index = Info.getValue2Index(Signed);
546 unsigned OpIdx = Value2Index.lookup(Op);
547 if (!OpIdx)
548 return false;
549
550 int64_t OpCoefficient = Upper ? 1 : -1;
551 unsigned OpSize = Op->getType()->getScalarSizeInBits();
552
553 for (ArrayRef<Entry> Row : Info.getCS(Signed).getConstraints()) {
554 // Match `OpCoefficient * (Op - W) <= C` with C <= -Slack.
555 if (Row.size() != 3 || Row[0].Id != 0 ||
556 Row[0].Coefficient > RequiredOffset)
557 continue;
558 bool OpFirst = Row[1].Id == OpIdx;
559 const Entry &OpE = Row[OpFirst ? 1 : 2];
560 const Entry &WitnessE = Row[OpFirst ? 2 : 1];
561 if (OpE.Id != OpIdx || OpE.Coefficient != OpCoefficient ||
562 WitnessE.Coefficient != -OpCoefficient)
563 continue;
564
565 auto Witness = find_if(
566 Value2Index, [&](const auto &KV) { return KV.second == WitnessE.Id; });
567 assert(Witness != Value2Index.end() && "row variables must be mapped");
568 Type *WitnessTy = Witness->first->getType();
569 if (WitnessTy->isIntegerTy() && WitnessTy->getIntegerBitWidth() <= OpSize)
570 return true;
571 }
572 return false;
573}
574
575/// Returns true if \p Info implies that \p Op is in \p R, interpreting \p R as
576/// a signed range if \p Signed is set and as an unsigned range otherwise.
577static bool doesHoldInRange(ConstraintInfo &Info, Value *Op,
578 const ConstantRange &R, bool Signed) {
579 if (R.isEmptySet() || (Signed ? R.isSignWrappedSet() : R.isWrappedSet()))
580 return false;
581
582 if (R.isFullSet())
583 return true;
584
585 unsigned BitWidth = R.getBitWidth();
586 APInt Min = Signed ? R.getSignedMin() : R.getUnsignedMin();
587 APInt Max = Signed ? R.getSignedMax() : R.getUnsignedMax();
592 // What a witness has to bridge; computed before Max is clamped below.
593 APInt UpperSlack = MaxVal - Max;
594 // Replace bound too large to be decomposed by the largest usable one.
595 if (!Signed && Max.uge(MaxConstraintValue))
597
598 Type *Ty = Op->getType();
599 if (Min != MinVal &&
600 !Info.doesHold(Signed ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE, Op,
601 ConstantInt::get(Ty, Min)) &&
602 !hasLimitWitness(Info, Op, Min - MinVal, Signed, /*Upper=*/false))
603 return false;
604 if (Max != MaxVal &&
605 !Info.doesHold(Signed ? CmpInst::ICMP_SLE : CmpInst::ICMP_ULE, Op,
606 ConstantInt::get(Ty, Max)) &&
607 !hasLimitWitness(Info, Op, UpperSlack, Signed, /*Upper=*/true))
608 return false;
609 return true;
610}
611
612/// Returns true if \p Opcode applied to \p Op0 and \p Op1 with \p NoWrapFlags
613/// is known to not wrap in signed or unsigned, depending on \p Signed.
614static bool isKnownNoWrap(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
615 unsigned NoWrapFlags, ConstraintInfo &Info,
616 bool Signed) {
617 using OBO = OverflowingBinaryOperator;
618
619 if (NoWrapFlags & (Signed ? OBO::NoSignedWrap : OBO::NoUnsignedWrap))
620 return true;
621
622 if (Opcode == Instruction::Sub) {
623 // Op0 - Op1 does not wrap unsigned if Op0 >=u Op1.
624 if (!Signed)
625 return Info.doesHold(CmpInst::ICMP_UGE, Op0, Op1);
626
627 // Op0 - Op1 does not wrap signed if 0 <=s Op1 <=s Op0.
628 if (Info.isKnownNonNegative(Op1) &&
629 Info.doesHold(CmpInst::ICMP_SGE, Op0, Op1))
630 return true;
631 }
632
633 // A signed sum of operands with opposite signs cannot wrap.
634 if (Signed && Opcode == Instruction::Add) {
635 std::optional<bool> Op0Sign =
636 Info.getKnownSign(Op0, /*StrictlyNegative=*/false);
637 std::optional<bool> Op1Sign =
638 Info.getKnownSign(Op1, /*StrictlyNegative=*/false);
639 if (Op0Sign && Op1Sign && *Op0Sign != *Op1Sign)
640 return true;
641 }
642
643 if (!Signed && (NoWrapFlags & OBO::NoSignedWrap) &&
644 (Opcode == Instruction::Shl || Info.isKnownNonNegative(Op1)) &&
645 Info.isKnownNonNegative(Op0))
646 return true;
647
648 // For a constant Op1, the ranges of Op0 for which the operation does not
649 // wrap are known exactly; check if the systems imply one of them.
650 auto *C = dyn_cast<ConstantInt>(Op1);
651 if (!C)
652 return false;
653
654 return doesHoldInRange(Info, Op0,
656 Opcode, C->getValue(),
657 Signed ? OBO::NoSignedWrap : OBO::NoUnsignedWrap),
658 Signed);
659}
660
661/// Returns true if \p V is known to not wrap in signed or unsigned, depending
662/// on \p Signed.
663static bool isKnownNoWrap(Value *V, ConstraintInfo &Info, bool Signed) {
664 if (match(V, m_DisjointOr(m_Value(), m_Value())))
665 return true;
666
667 if (auto *WO = dyn_cast<WithOverflowInst>(V))
668 return isKnownNoWrap(WO->getBinaryOp(), WO->getLHS(), WO->getRHS(),
669 /*NoWrapFlags=*/0, Info, Signed);
670
671 if (auto *Trunc = dyn_cast<TruncInst>(V)) {
672 if (Signed)
673 return Trunc->hasNoSignedWrap();
674
675 // A trunc nsw only truncates without unsigned wrap if its operand is
676 // non-negative.
677 return Trunc->hasNoUnsignedWrap() ||
678 (Trunc->hasNoSignedWrap() &&
679 Info.isKnownNonNegative(Trunc->getOperand(0)));
680 }
681
683 return BO &&
684 isKnownNoWrap(static_cast<Instruction::BinaryOps>(BO->getOpcode()),
685 BO->getOperand(0), BO->getOperand(1),
686 BO->getNoWrapKind(), Info, Signed);
687}
688
689static Decomposition decomposeGEP(GEPOperator &GEP, ConstraintInfo &Info,
690 bool IsSigned, const DataLayout &DL) {
691 // Do not reason about pointers where the index size is larger than 64 bits,
692 // as the coefficients used to encode constraints are 64 bit integers.
693 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
694 return &GEP;
695
696 assert(!IsSigned && "The logic below only supports decomposition for "
697 "unsigned predicates at the moment.");
698 const auto &[BasePtr, ConstantOffset, VariableOffsets, NW] =
700 // We support either plain gep nuw, or gep nusw with non-negative offset,
701 // which implies gep nuw.
702 if (!BasePtr || NW == GEPNoWrapFlags::none())
703 return &GEP;
704
705 // For a nuw-only GEP (nuw without nusw/inbounds), the offset must be
706 // interpreted as unsigned.
707 if (!NW.hasNoUnsignedSignedWrap() && ConstantOffset.isNegative())
708 return &GEP;
709
710 Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
711 for (auto [Index, Scale] : VariableOffsets) {
712 // Indices narrower or wider than the index type are implicitly
713 // sign-extended or truncated. Don't reason about them.
714 if (Index->getType()->getScalarSizeInBits() != Scale.getBitWidth())
715 return &GEP;
716 if (!NW.hasNoUnsignedWrap()) {
717 // Try to prove nuw from nusw and nneg. If the index cannot be proven
718 // non-negative, keep the GEP as-is instead of decomposing it.
719 assert(NW.hasNoUnsignedSignedWrap() && "Must have nusw flag");
720 if (!Info.isKnownNonNegative(Index))
721 return &GEP;
722 } else if (!NW.hasNoUnsignedSignedWrap()) {
723 // For a nuw-only GEP, the scale is unsigned and must fit in the signed
724 // coefficient.
725 if (Scale.isNegative())
726 return &GEP;
727 }
728
729 auto IdxResult = decompose(Index, Info, IsSigned, DL);
730 if (IdxResult.mul(Scale.getSExtValue()))
731 return &GEP;
732 if (Result.add(IdxResult))
733 return &GEP;
734 }
735 return Result;
736}
737
738// Decomposes \p V into a constant offset + list of pairs { Coefficient,
739// Variable } where Coefficient * Variable. The sum of the constant offset and
740// pairs equals \p V.
741//
742// Looking through certain expressions is only valid if a pre-condition holds.
743// Pre-conditions are checked against \p Info as needed.
744static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info,
745 bool IsSigned, const DataLayout &DL);
746
747/// Returns true if \p V is an operation decomposeImpl can look through.
748static bool mayLookThrough(Value *V) {
749 auto *Op = dyn_cast<Operator>(V);
750 if (!Op)
751 return false;
752 switch (Op->getOpcode()) {
753 case Instruction::GetElementPtr:
754 case Instruction::Add:
755 case Instruction::Sub:
756 case Instruction::Mul:
757 case Instruction::Shl:
758 case Instruction::LShr:
759 case Instruction::AShr:
760 case Instruction::ZExt:
761 case Instruction::SExt:
762 case Instruction::Trunc:
763 case Instruction::Or:
764 case Instruction::Xor:
765 return true;
766 default:
767 return false;
768 }
769}
770
771static Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned,
772 const DataLayout &DL) {
773 if (!mayLookThrough(V))
774 return decomposeImpl(V, Info, IsSigned, DL);
775
777 auto &Cache = Info.getDecomposeCache();
778 auto It = Cache.find(Key);
779 if (It != Cache.end())
780 return It->second;
781
782 Decomposition Result = decomposeImpl(V, Info, IsSigned, DL);
783 Info.getDecomposeCache().insert({Key, Result});
784 return Result;
785}
786
787static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info,
788 bool IsSigned, const DataLayout &DL) {
789 auto MergeResults = [&Info, IsSigned,
790 &DL](Value *A, Value *B,
791 bool IsSignedB) -> std::optional<Decomposition> {
792 auto ResA = decompose(A, Info, IsSigned, DL);
793 auto ResB = decompose(B, Info, IsSignedB, DL);
794 if (ResA.add(ResB))
795 return std::nullopt;
796 return ResA;
797 };
798
799 Type *Ty = V->getType()->getScalarType();
800 if (Ty->isPointerTy() && !IsSigned) {
801 if (auto *GEP = dyn_cast<GEPOperator>(V))
802 return decomposeGEP(*GEP, Info, IsSigned, DL);
804 return int64_t(0);
805
806 return V;
807 }
808
809 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
810 // coefficient add/mul may wrap, while the operation in the full bit width
811 // would not.
812 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
813 return V;
814
815 if (auto *CI = dyn_cast<ConstantInt>(V)) {
816 if (IsSigned) {
817 if (canUseSExt(CI))
818 return CI->getSExtValue();
819 } else if (!CI->uge(MaxConstraintValue)) {
820 return int64_t(CI->getZExtValue());
821 }
822 return V;
823 }
824
825 Value *Op0;
826 Value *Op1;
827 ConstantInt *CI;
828
829 if (match(V, m_ZExt(m_Value(Op0)))) {
830 // In the signed system, the ZExt must be non-negative.
831 if (IsSigned && !cast<ZExtInst>(V)->hasNonNeg())
832 return V;
833 V = Op0;
834 } else if (match(V, m_SExt(m_Value(Op0)))) {
835 // In the unsigned system, the SExt operand must be non-negative.
836 if (!IsSigned && !Info.isKnownNonNegative(Op0))
837 return V;
838 V = Op0;
839 } else if (auto *Trunc = dyn_cast<TruncInst>(V)) {
840 if (Trunc->getSrcTy()->getScalarSizeInBits() <= 64 &&
841 isKnownNoWrap(Trunc, Info, IsSigned))
842 V = Trunc->getOperand(0);
843 }
844
845 if (match(V, m_AddLike(m_Value(Op0), m_Value(Op1)))) {
846 if (isKnownNoWrap(V, Info, IsSigned)) {
847 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
848 return *Decomp;
849 return V;
850 }
851 // In the unsigned system, adding a negative constant only wraps if Op0 is
852 // smaller than it.
853 if (!IsSigned && match(Op1, m_ConstantInt(CI)) && CI->isNegative() &&
854 canUseSExt(CI) &&
855 Info.doesHold(CmpInst::ICMP_UGE, Op0,
856 ConstantInt::get(Op0->getType(), -CI->getSExtValue())))
857 if (auto Decomp = MergeResults(Op0, CI, /*IsSignedB=*/true))
858 return *Decomp;
859 return V;
860 }
861
862 // `xor %x, -1` is equivalent to `sub nsw -1, %x`.
863 if (IsSigned && match(V, m_Not(m_Value(Op0)))) {
864 Decomposition Result(-1);
865 if (!Result.sub(decompose(Op0, Info, IsSigned, DL)))
866 return Result;
867 return V;
868 }
869
870 if (match(V, m_Sub(m_Value(Op0), m_Value(Op1)))) {
871 if (isKnownNoWrap(V, Info, IsSigned)) {
872 auto ResA = decompose(Op0, Info, IsSigned, DL);
873 auto ResB = decompose(Op1, Info, IsSigned, DL);
874 if (!ResA.sub(ResB))
875 return ResA;
876 }
877 return V;
878 }
879
880 if (match(V, m_Mul(m_Value(Op0), m_ConstantInt(CI)))) {
881 // A negative constant is only a valid coefficient in the signed system; in
882 // the unsigned system the multiplier is the constant's unsigned value.
883 if (canUseSExt(CI) && (IsSigned || !CI->isNegative()) &&
884 isKnownNoWrap(V, Info, IsSigned)) {
885 auto Result = decompose(Op0, Info, IsSigned, DL);
886 if (!Result.mul(CI->getSExtValue()))
887 return Result;
888 }
889 return V;
890 }
891
892 if (match(V, m_Exact(m_Shr(m_Value(Op0), m_ConstantInt(CI))))) {
893 bool IsAShr = cast<Operator>(V)->getOpcode() == Instruction::AShr;
894 if (CI->getValue().ult(std::min(63u, CI->getBitWidth())) &&
895 (IsSigned == IsAShr || Info.isKnownNonNegative(Op0))) {
896 int64_t Factor = int64_t(1) << CI->getZExtValue();
897 auto Result = decompose(Op0, Info, IsSigned, DL);
898 if (Result.Offset % Factor == 0 &&
899 all_of(Result.Vars, [Factor](const DecompEntry &E) {
900 return E.Coefficient % Factor == 0;
901 })) {
902 Result.Offset /= Factor;
903 for (auto &E : Result.Vars)
904 E.Coefficient /= Factor;
905 return Result;
906 }
907 }
908 return V;
909 }
910
911 if (match(V, m_Shl(m_Value(Op0), m_ConstantInt(CI)))) {
912 // (shl x, shift) is (mul x, 1 << shift). The scale must fit in the signed
913 // coefficient, so reject shifts >= 63. Also reject a shift of bw-1, for
914 // which the product is not representable.
915 int64_t MaxShift = IsSigned ? Ty->getIntegerBitWidth() - 1 : 63;
916 if (!CI->isNegative() && CI->getSExtValue() < MaxShift &&
917 isKnownNoWrap(V, Info, IsSigned)) {
918 auto Result = decompose(Op0, Info, IsSigned, DL);
919 if (!Result.mul(int64_t{1} << CI->getSExtValue()))
920 return Result;
921 }
922 return V;
923 }
924
925 return V;
926}
927
928/// Build the row for 'ADec <= BDec', using the indices from \p Value2Index.
929/// Variables not in \p Value2Index are appended to \p NewVariables and get the
930/// indices following the ones in \p Value2Index. Returns an empty row if the
931/// coefficients overflow.
932static RowTy getRowForLessEqual(const Decomposition &ADec,
933 const Decomposition &BDec,
934 const DenseMap<Value *, unsigned> &Value2Index,
935 SmallVectorImpl<Value *> &NewVariables) {
936 // Build the row, by first adding all coefficients from A and then subtracting
937 // all coefficients from B.
938 int64_t OffsetSum;
939 if (SubOverflow(BDec.Offset, ADec.Offset, OffsetSum))
940 return {};
941 RowTy R(1, Entry(OffsetSum, 0));
942 auto GetCoefficient = [&R](unsigned Idx) -> int64_t & {
943 // The entry for Idx, or the place to insert it at, is the first entry with
944 // an index >= Idx.
945 Entry *I =
946 find_if(drop_begin(R), [Idx](const Entry &E) { return E.Id >= Idx; });
947 if (I == R.end() || I->Id != Idx)
948 I = R.insert(I, Entry(0, Idx));
949 return I->Coefficient;
950 };
951 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
952 // new entry to NewVariables.
953 auto GetOrAddIndex = [&Value2Index, &NewVariables](Value *V) -> unsigned {
954 auto V2I = Value2Index.find(V);
955 if (V2I != Value2Index.end())
956 return V2I->second;
957 unsigned Idx = find(NewVariables, V) - NewVariables.begin();
958 if (Idx == NewVariables.size())
959 NewVariables.push_back(V);
960 return Value2Index.size() + Idx + 1;
961 };
962 for (const DecompEntry &KV : ADec.Vars)
963 GetCoefficient(GetOrAddIndex(KV.Variable)) += KV.Coefficient;
964
965 for (const DecompEntry &KV : BDec.Vars) {
966 auto &Coeff = GetCoefficient(GetOrAddIndex(KV.Variable));
967 if (SubOverflow(Coeff, KV.Coefficient, Coeff))
968 return {};
969 }
970
971 // Drop coefficients that cancelled out.
972 erase_if(R, [](const Entry &E) { return E.Id != 0 && E.Coefficient == 0; });
973 return R;
974}
975
976ConstraintTy
977ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
978 SmallVectorImpl<Value *> &NewVariables,
979 bool ForceSignedSystem) {
980 assert(NewVariables.empty() && "NewVariables must be empty when passed in");
981 assert((!ForceSignedSystem || CmpInst::isEquality(Pred)) &&
982 "signed system can only be forced on eq/ne");
983
984 bool IsEq = false;
985 bool IsNe = false;
986
987 // Try to convert Pred to one of ULE/ULT/SLE/SLT.
988 switch (Pred) {
992 case CmpInst::ICMP_SGE: {
994 std::swap(Op0, Op1);
995 break;
996 }
997 case CmpInst::ICMP_EQ:
998 if (!ForceSignedSystem && match(Op1, m_Zero())) {
1000 } else {
1001 IsEq = true;
1003 }
1004 break;
1005 case CmpInst::ICMP_NE:
1006 if (!ForceSignedSystem && match(Op1, m_Zero())) {
1008 std::swap(Op0, Op1);
1009 } else {
1010 IsNe = true;
1012 }
1013 break;
1014 default:
1015 break;
1016 }
1017
1020 return {};
1021
1022 bool IsSigned = ForceSignedSystem || CmpInst::isSigned(Pred);
1023 auto &Value2Index = getValue2Index(IsSigned);
1024 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), *this,
1025 IsSigned, DL);
1026 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), *this,
1027 IsSigned, DL);
1028 RowTy R = getRowForLessEqual(ADec, BDec, Value2Index, NewVariables);
1029 if (R.empty())
1030 return {};
1031
1033 if (AddOverflow(R[0].Coefficient, int64_t(-1), R[0].Coefficient))
1034 return {};
1035
1036 // Remove any new variable without a coefficient in the row.
1037 unsigned NumV2I = Value2Index.size();
1038 NewVariables.truncate(R.back().Id > NumV2I ? R.back().Id - NumV2I : 0);
1039
1040 return ConstraintTy(std::move(R), Value2Index.size() + NewVariables.size(),
1041 IsSigned, IsEq, IsNe);
1042}
1043
1044ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
1045 Value *Op0, Value *Op1) {
1046 Constant *NullC = Constant::getNullValue(Op0->getType());
1047 // Handle trivially true compares directly to avoid adding V UGE 0 constraints
1048 // for all variables in the unsigned system.
1049 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
1050 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
1051 // Return constraint that's trivially true.
1052 return ConstraintTy(RowTy(1, Entry(0, 0)), /*NumVars=*/0,
1053 /*IsSigned=*/false, /*IsEq=*/false, /*IsNe=*/false);
1054 }
1055
1056 // If both operands are known to be non-negative, change signed predicates to
1057 // unsigned ones. This increases the reasoning effectiveness in combination
1058 // with the signed <-> unsigned transfer logic.
1059 if (CmpInst::isSigned(Pred) &&
1060 ::isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
1063
1064 SmallVector<Value *> NewVariables;
1065 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
1066 if (!NewVariables.empty())
1067 return {};
1068 return R;
1069}
1070
1071std::optional<bool>
1072ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
1073 const auto &[SubCS, NewCoefficients] = CS.getSubSystem(Coefficients);
1074 bool IsConditionImplied = SubCS.isConditionImplied(NewCoefficients);
1075
1076 if (IsEq || IsNe) {
1077 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(NewCoefficients);
1078 bool IsNegatedOrEqualImplied =
1079 !NegatedOrEqual.empty() && SubCS.isConditionImplied(NegatedOrEqual);
1080
1081 // In order to check that `%a == %b` is true (equality), both conditions `%a
1082 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
1083 // is true), we return true if they both hold, false in the other cases.
1084 if (IsConditionImplied && IsNegatedOrEqualImplied)
1085 return IsEq;
1086
1087 auto Negated = ConstraintSystem::negate(NewCoefficients);
1088 bool IsNegatedImplied =
1089 !Negated.empty() && SubCS.isConditionImplied(Negated);
1090
1091 auto StrictLessThan = ConstraintSystem::toStrictLessThan(NewCoefficients);
1092 bool IsStrictLessThanImplied =
1093 !StrictLessThan.empty() && SubCS.isConditionImplied(StrictLessThan);
1094
1095 // In order to check that `%a != %b` is true (non-equality), either
1096 // condition `%a > %b` or `%a < %b` must hold true. When checking for
1097 // non-equality (`IsNe` is true), we return true if one of the two holds,
1098 // false in the other cases.
1099 if (IsNegatedImplied || IsStrictLessThanImplied)
1100 return IsNe;
1101
1102 return std::nullopt;
1103 }
1104
1105 if (IsConditionImplied)
1106 return true;
1107
1108 auto Negated = ConstraintSystem::negate(NewCoefficients);
1109 auto IsNegatedImplied = !Negated.empty() && SubCS.isConditionImplied(Negated);
1110 if (IsNegatedImplied)
1111 return false;
1112
1113 // Neither the condition nor its negated holds, did not prove anything.
1114 return std::nullopt;
1115}
1116
1117static RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C,
1118 ConstraintInfo &Info,
1119 const DataLayout &DL);
1120
1121std::optional<bool>
1122ConstraintInfo::tryWithLinkRows(Value *A, Value *B, const ConstraintTy &C,
1123 function_ref<std::optional<bool>()> Solve) {
1124 if (std::optional<bool> Res = Solve())
1125 return Res;
1126 if (C.empty())
1127 return std::nullopt;
1128
1129 auto &CS = getCS(C.IsSigned);
1130 unsigned NumVars = getValue2Index(C.IsSigned).size();
1131 unsigned NumPushed = 0;
1132 for (Value *V : {A, B}) {
1133 RowTy Row = getDecompositionLinkRow(V, C, *this, DL);
1134 RowTy Negated = ConstraintSystem::negateOrEqual(Row);
1135 if (Row.empty() || Negated.empty())
1136 continue;
1137 NumPushed += CS.addRow(Row, NumVars);
1138 NumPushed += CS.addRow(Negated, NumVars);
1139 }
1140 if (NumPushed == 0)
1141 return std::nullopt;
1142#ifndef NDEBUG
1143 unsigned NumRows = CS.size();
1144#endif
1145 std::optional<bool> Res = Solve();
1146 assert(CS.size() == NumRows && "rows added while link rows are pushed");
1147 while (NumPushed--)
1148 CS.popLastConstraint();
1149 return Res;
1150}
1151
1152bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, Value *B) {
1153 auto R = getConstraintForSolving(Pred, A, B);
1154 if (R.empty())
1155 return false;
1156 auto &CS = getCS(R.IsSigned);
1157 return tryWithLinkRows(A, B, R,
1158 [&]() -> std::optional<bool> {
1159 if (CS.isConditionImpliedInSubSystem(R.Coefficients))
1160 return true;
1161 return std::nullopt;
1162 })
1163 .value_or(false);
1164}
1165
1166bool ConstraintInfo::isKnownNonNegative(Value *V) {
1167 if (auto *CI = dyn_cast<ConstantInt>(V))
1168 return !CI->isNegative();
1169 return ::isKnownNonNegative(V, DL) ||
1170 doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0));
1171}
1172
1173bool ConstraintInfo::isKnownPositive(Value *V) {
1174 if (auto *CI = dyn_cast<ConstantInt>(V))
1175 return CI->getValue().isStrictlyPositive();
1176 return ::isKnownPositive(V, DL) ||
1177 doesHold(CmpInst::ICMP_SGT, V, ConstantInt::get(V->getType(), 0));
1178}
1179
1180std::optional<bool> ConstraintInfo::getKnownSign(Value *V,
1181 bool StrictlyNegative) {
1182 KnownBits Known = computeKnownBits(V, DL);
1183 if (Known.isNonNegative())
1184 return false;
1185 if (StrictlyNegative ? Known.isNegative() : Known.isNonPositive())
1186 return true;
1187 Constant *Zero = ConstantInt::get(V->getType(), 0);
1188 if (doesHold(CmpInst::ICMP_SGE, V, Zero))
1189 return false;
1190 auto NegativePred = StrictlyNegative ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE;
1191 if (doesHold(NegativePred, V, Zero))
1192 return true;
1193 return std::nullopt;
1194}
1195
1196void ConstraintInfo::transferToOtherSystem(
1197 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
1198 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
1199 // Check if we can combine facts from the signed and unsigned systems to
1200 // derive additional facts.
1201 if (!A->getType()->isIntegerTy())
1202 return;
1203 // FIXME: This currently depends on the order we add facts. Ideally we
1204 // would first add all known facts and only then try to add additional
1205 // facts.
1206 switch (Pred) {
1207 default:
1208 break;
1209 case CmpInst::ICMP_ULT:
1210 case CmpInst::ICMP_ULE:
1211 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
1212 if (isKnownNonNegative(B)) {
1213 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
1214 NumOut, DFSInStack);
1215 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
1216 DFSInStack);
1217 }
1218 break;
1219 case CmpInst::ICMP_UGE:
1220 case CmpInst::ICMP_UGT:
1221 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
1222 if (isKnownNonNegative(A)) {
1223 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
1224 NumOut, DFSInStack);
1225 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
1226 DFSInStack);
1227 }
1228 break;
1229 case CmpInst::ICMP_SLT:
1230 case CmpInst::ICMP_SLE:
1231 if (isKnownNonNegative(A))
1232 addFact(ICmpInst::getUnsignedPredicate(Pred), A, B, NumIn, NumOut,
1233 DFSInStack);
1234 break;
1235 case CmpInst::ICMP_SGT: {
1236 if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
1237 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
1238 NumOut, DFSInStack);
1239 if (isKnownNonNegative(B))
1240 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
1241
1242 break;
1243 }
1244 case CmpInst::ICMP_SGE:
1245 if (isKnownNonNegative(B))
1246 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
1247 break;
1248 }
1249}
1250
1251#ifndef NDEBUG
1252
1254 const DenseMap<Value *, unsigned> &Value2Index) {
1255 ConstraintSystem CS(Value2Index);
1256 CS.addRow(C, Value2Index.size());
1257 CS.dump();
1258}
1259#endif
1260
1261/// Splits the induction phi \p PN into the start value, coming from the loop
1262/// predecessor \p LoopPred, and the backedge value, coming from inside the
1263/// loop. Returns {nullptr, nullptr} if \p PN has other incoming values.
1264static std::pair<Value *, Value *>
1265getStartAndBackedgeValue(const PHINode &PN, const BasicBlock *LoopPred) {
1266 assert(PN.getBasicBlockIndex(LoopPred) >= 0 &&
1267 "LoopPred must be a predecessor of the phi's block");
1268 if (PN.getNumIncomingValues() != 2)
1269 return {nullptr, nullptr};
1270 unsigned StartIdx = PN.getIncomingBlock(0) == LoopPred ? 0 : 1;
1271 return {PN.getIncomingValue(StartIdx), PN.getIncomingValue(1 - StartIdx)};
1272}
1273
1274/// Matches an increment of \p PhiM by a constant offset, captured in \p Off.
1275/// The increment must be a plain IR add or [u|s]add.with.overflow.
1276template <typename PhiMatchTy>
1277static auto m_IncrementOf(const PhiMatchTy &PhiM, const APInt *&Off) {
1278 return m_CombineOr(
1279 m_c_Add(PhiM, m_APInt(Off)),
1283}
1284
1285MonotonicInfo State::getMonotonicityInfo(PHINode &PN, Value *Step) {
1286 MonotonicInfo Info;
1287 const APInt *StepOffset = nullptr;
1288 if (match(Step, m_IncrementOf(m_Specific(&PN), StepOffset))) {
1289 Info.Decreasing = StepOffset->isNegative();
1290 if (const auto *Add = dyn_cast<OverflowingBinaryOperator>(Step)) {
1291 Info.Unsigned = !Info.Decreasing && Add->hasNoUnsignedWrap();
1292 Info.Signed = Add->hasNoSignedWrap();
1293 }
1294 } else if (const auto *GEP = dyn_cast<GEPOperator>(Step)) {
1295 // TODO: Handle the non-increasing direction, which needs a nusw GEP with a
1296 // negative constant offset.
1297 const DataLayout &DL = PN.getDataLayout();
1298 APInt GEPOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1299 Info.Unsigned = GEP->getPointerOperand() == &PN &&
1300 (GEP->hasNoUnsignedWrap() ||
1301 ((GEP->hasNoUnsignedSignedWrap() &&
1302 GEP->accumulateConstantOffset(DL, GEPOffset) &&
1303 !GEPOffset.isNegative())));
1304 }
1305
1306 // Forming the SCEV of a phi is expensive, so only consult it for a PN + C
1307 // step whose no-wrap flags prove nothing.
1308 if (Info.Unsigned || Info.Signed || !StepOffset)
1309 return Info;
1310
1311 const auto *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&PN));
1312 if (!AR)
1313 return Info;
1317 auto IsMonotonic = [&](CmpInst::Predicate Pred) {
1318 return SE->getMonotonicPredicateType(AR, Pred) == Expected;
1319 };
1320 Info.Signed = IsMonotonic(CmpInst::ICMP_SGT);
1321 Info.Unsigned = !Info.Decreasing && IsMonotonic(CmpInst::ICMP_UGT);
1322 return Info;
1323}
1324
1325void State::addBoundsForHeaderInductions(BasicBlock &BB) {
1326 Loop *L = LI.getLoopFor(&BB);
1327 if (!L || L->getHeader() != &BB)
1328 return;
1329 BasicBlock *LoopPred = L->getLoopPredecessor();
1330 if (!LoopPred)
1331 return;
1332
1333 DomTreeNode *DTN = DT.getNode(&BB);
1334 for (PHINode &PN : BB.phis()) {
1335 if (!PN.getType()->isIntegerTy() && !PN.getType()->isPointerTy())
1336 continue;
1337
1338 auto [Start, Step] = getStartAndBackedgeValue(PN, LoopPred);
1339 if (!Start)
1340 continue;
1341
1342 MonotonicInfo Info = getMonotonicityInfo(PN, Step);
1343 // Every variable in the unsigned system already has a `V >= 0` row, so a
1344 // zero start value would just duplicate it.
1345 if (match(Start, m_Zero()))
1346 Info.Unsigned = false;
1347 if (!Info.Unsigned && !Info.Signed)
1348 continue;
1349
1350 // A non-decreasing induction cannot step below its start value, and a
1351 // non-increasing one cannot step above it.
1352 Value *LHS = &PN, *RHS = Start;
1353 if (Info.Decreasing)
1354 std::swap(LHS, RHS);
1355 CmpPredicate Pred(Info.Unsigned ? CmpInst::ICMP_UGE : CmpInst::ICMP_SGE,
1356 /*HasSameSign=*/Info.Unsigned && Info.Signed);
1357 WorkList.push_back(FactOrCheck::getConditionFact(DTN, Pred, LHS, RHS));
1358 }
1359}
1360
1361void State::addInfoForInductions(BasicBlock &BB) {
1362 auto *L = LI.getLoopFor(&BB);
1363 if (!L)
1364 return;
1365
1366 BasicBlock *Header = L->getHeader();
1367 BasicBlock *Latch = L->getLoopLatch();
1368 if (Header != &BB && Latch != &BB)
1369 return;
1370
1371 // A is either a phi or a post-increment PN + C with constant step. For the
1372 // latter, extract the constant IncStep.
1373 Value *A;
1374 Value *B;
1375 PHINode *PN = nullptr;
1376 const APInt *IncStep = nullptr;
1377 CmpPredicate Pred;
1378 auto IndValue =
1379 m_Value(A, m_CombineOr(m_Phi(PN), m_IncrementOf(m_Phi(PN), IncStep)));
1380
1381 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1382 if (!Br)
1383 return;
1384
1385 auto CountingCmp = m_c_ICmp(Pred, IndValue, m_Value(B));
1386 std::optional<bool> PeeledOnEdge;
1387 if (!match(Br->getCondition(), CountingCmp)) {
1388 // Look through AND/OR, and remember which edge requires all operands to be
1389 // true.
1390 if (match(Br->getCondition(), m_c_LogicalAnd(CountingCmp, m_Value())))
1391 PeeledOnEdge = true;
1392 else if (match(Br->getCondition(), m_c_LogicalOr(CountingCmp, m_Value())))
1393 PeeledOnEdge = false;
1394 else
1395 return;
1396 }
1397
1398 if (PN->getParent() != Header || PN->getNumIncomingValues() != 2 ||
1399 !SE->isSCEVable(PN->getType()))
1400 return;
1401
1402 bool ContinueOnTrue =
1404 CmpInst::Predicate ContinuePred =
1405 ContinueOnTrue ? Pred.dropSameSign() : CmpInst::getInversePredicate(Pred);
1406 BasicBlock *InLoopSucc = Br->getSuccessor(ContinueOnTrue ? 0 : 1);
1407
1408 // The peeled condition only implies the compare on the edge where the
1409 // combined condition forces its operands, which must be the in-loop edge.
1410 if (PeeledOnEdge && *PeeledOnEdge != ContinueOnTrue)
1411 return;
1412
1413 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB))
1414 return;
1415
1416 BasicBlock *LoopPred = L->getLoopPredecessor();
1417 if (!LoopPred || !L->isLoopInvariant(B))
1418 return;
1419
1420 auto [StartValue, Backedge] = getStartAndBackedgeValue(*PN, LoopPred);
1421 DomTreeNode *DTN = DT.getNode(InLoopSucc);
1422 DomTreeNode *HeaderDTN = DT.getNode(Header);
1423
1424 // BB is the header or the latch, so every iteration taking the backedge
1425 // checked PN ContinuePred B, which guarantees PN != B for NE and LT
1426 // predicates. For an increment by one, PN != B together with StartValue <= B
1427 // (added precondition) imply PN <= B.
1428 const APInt *Step;
1429 bool HasHeaderBound =
1430 !IncStep && match(Backedge, m_IncrementOf(m_Specific(PN), Step)) &&
1431 Step->isOne() &&
1432 (ContinuePred == CmpInst::ICMP_NE || ICmpInst::isLT(ContinuePred));
1433 if (HasHeaderBound) {
1435 WorkList.push_back(FactOrCheck::getConditionFact(
1436 HeaderDTN, BoundPred, PN, B, ConditionTy(BoundPred, StartValue, B)));
1437 }
1438
1439 // For latch conditions, we need to inject the condition that holds for the
1440 // next iteration into the header. We limit to post-inc conditions, for which
1441 // an original PN + Step != B condition results in a PN < B constraint in the
1442 // header, which also holds for the next loop iteration. This would no longer
1443 // be correct if the post-inc handling would inject a more precise PN + Step <
1444 // B constraint instead.
1445 if (&BB == Latch && !IncStep)
1446 return;
1447
1448 if (ICmpInst::isRelational(ContinuePred)) {
1449 if (A != Backedge)
1450 return;
1451
1452 // The condition ensures ContinuePred holds in the header on each iteration
1453 // other than the first. Together with a precondition on the start value
1454 // (StartValue ContinuePred B), we can add B as bound of PN.
1455 WorkList.push_back(FactOrCheck::getConditionFact(
1456 HeaderDTN, ContinuePred, PN, B,
1457 ConditionTy(ContinuePred, StartValue, B)));
1458
1459 // A signed bound can be translated to the unsigned system if PN is signed
1460 // non-decreasing (StartValue s<= PN s< B) and StartValue u< B holds.
1461 // Then StartValue, PN and B must all have the same sign.
1462 if (ICmpInst::isSigned(ContinuePred)) {
1463 assert((ContinuePred == CmpInst::ICMP_SLT ||
1464 ContinuePred == CmpInst::ICMP_SLE) &&
1465 "Expected a signed less-than continuation predicate");
1466 MonotonicInfo Info = getMonotonicityInfo(*PN, Backedge);
1467 if (Info.Signed && !Info.Decreasing) {
1469 WorkList.push_back(FactOrCheck::getConditionFact(
1470 HeaderDTN, UPred, PN, B, ConditionTy(UPred, StartValue, B)));
1471 }
1472 }
1473
1474 // A relational latch steps past B rather than landing on it, so none of the
1475 // reasoning below applies.
1476 return;
1477 }
1478
1479 const APInt *StepOffset = nullptr;
1480 const SCEV *StartSCEV = nullptr;
1481 if (match(Backedge, m_c_Add(m_Specific(PN), m_APInt(StepOffset)))) {
1482 if (StepOffset->isZero())
1483 return;
1484 } else {
1485 const SCEV *Expr = SE->getSCEV(PN);
1486 if (!match(Expr,
1487 m_scev_AffineAddRec(m_SCEV(StartSCEV), m_scev_APInt(StepOffset),
1488 m_SpecificLoop(L))))
1489 return;
1490 }
1491
1492 // If we looked through `PN + C`, only derive facts when that add is
1493 // really the induction's post-increment or post-decrement.
1494 if (IncStep && *IncStep != *StepOffset)
1495 return;
1496
1497 MonotonicInfo Info = getMonotonicityInfo(*PN, Backedge);
1498
1499 // Handle negative steps.
1500 if (StepOffset->isNegative()) {
1501 // TODO: Extend to allow steps > -1.
1502 if (!(-*StepOffset).isOne())
1503 return;
1504
1505 // AR may wrap.
1506 // The loop exits once the compared value reaches B, that is at PN == B when
1507 // comparing the phi, and at PN == B + 1 for a post-decrement. Use
1508 // non-strict predicate for the former, and a strict one for the latter to
1509 // ensure the loop exits before wrapping.
1510 CmpInst::Predicate UPrecond =
1512 ConditionTy BBeforeStartUnsigned = {UPrecond, B, StartValue};
1513 ConditionTy BBeforeStartSigned = {ICmpInst::getSignedPredicate(UPrecond), B,
1514 StartValue};
1515
1516 // AR may wrap, so both facts are conditional on B being below StartValue.
1517 // Add StartValue >= PN, which holds as the loop exits before wrapping.
1518 WorkList.push_back(FactOrCheck::getConditionFact(
1519 DTN, CmpInst::ICMP_UGE, StartValue, PN, BBeforeStartUnsigned));
1520 if (!(Info.Decreasing && Info.Signed))
1521 WorkList.push_back(FactOrCheck::getConditionFact(
1522 DTN, CmpInst::ICMP_SGE, StartValue, PN, BBeforeStartSigned));
1523 // Add PN > B, which holds as the loop exits when reaching B.
1524 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGT, PN,
1525 B, BBeforeStartUnsigned));
1526 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGT, PN,
1527 B, BBeforeStartSigned));
1528 return;
1529 }
1530
1531 // Make sure AR either steps by 1 or that the value we compare against is a
1532 // GEP based on the same start value and all offsets are a multiple of the
1533 // step size, to guarantee that the induction will reach the value.
1534 if (StepOffset->isZero() || StepOffset->isNegative())
1535 return;
1536
1537 if (!StepOffset->isOne()) {
1538 // Check whether B-Start is known to be a multiple of StepOffset.
1539 if (!StartSCEV)
1540 StartSCEV = SE->getSCEV(StartValue);
1541 const SCEV *BMinusStart = SE->getMinusSCEV(SE->getSCEV(B), StartSCEV);
1542 if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1543 !SE->getConstantMultiple(BMinusStart).urem(*StepOffset).isZero())
1544 return;
1545 }
1546
1547 // We already established that B - Start is a multiple of Step above. The loop
1548 // exits once the compared value reaches B, that is at PN == B when comparing
1549 // the phi, and at PN + Step == B for a post-increment. Together with the
1550 // added precondition StartValue <= B for the former and the strict
1551 // StartValue < B for the latter (which implies StartValue + Step <= B),
1552 // neither PN nor the increment can wrap.
1554 ConditionTy StartBeforeBoundUnsigned = {UPrecond, StartValue, B};
1555 ConditionTy StartBeforeBoundSigned = {ICmpInst::getSignedPredicate(UPrecond),
1556 StartValue, B};
1557
1558 // Add PN >= StartValue, as the loop exits before wrapping.
1559 if (!Info.Unsigned)
1560 WorkList.push_back(FactOrCheck::getConditionFact(
1561 DTN, CmpInst::ICMP_UGE, PN, StartValue, StartBeforeBoundUnsigned));
1562 if (!Info.Signed)
1563 WorkList.push_back(FactOrCheck::getConditionFact(
1564 DTN, CmpInst::ICMP_SGE, PN, StartValue, StartBeforeBoundSigned));
1565 // Add PN < B, as the loop exits once the compared value reaches B. With a
1566 // header bound, the PN != B condition fact in InLoopSucc already tightens it
1567 // to PN < B.
1568 if (!HasHeaderBound || !canAddSuccessor(BB, InLoopSucc)) {
1569 WorkList.push_back(FactOrCheck::getConditionFact(
1570 DTN, CmpInst::ICMP_SLT, PN, B, StartBeforeBoundSigned));
1571 WorkList.push_back(FactOrCheck::getConditionFact(
1572 DTN, CmpInst::ICMP_ULT, PN, B, StartBeforeBoundUnsigned));
1573 }
1574
1575 // Try to add condition from the header or latch to the dedicated exit
1576 // blocks. When exiting either with EQ or NE, we know that the induction value
1577 // must be u<= B, as other exits may only exit earlier.
1578 assert(!StepOffset->isNegative() && "induction must be increasing");
1579 assert(ContinuePred == CmpInst::ICMP_NE && "unsupported predicate");
1580 // The header bound already implies PN u<= B in the exits.
1581 if (HasHeaderBound)
1582 return;
1584 L->getExitBlocks(ExitBBs);
1585 for (BasicBlock *EB : ExitBBs) {
1586 // Bail out on non-dedicated exits.
1587 if (DT.dominates(&BB, EB)) {
1588 WorkList.emplace_back(FactOrCheck::getConditionFact(
1589 DT.getNode(EB), CmpInst::ICMP_ULE, A, B, StartBeforeBoundUnsigned));
1590 }
1591 }
1592}
1593
1595 uint64_t AccessSize,
1597 Value *&B, const DataLayout &DL,
1598 const TargetLibraryInfo &TLI) {
1599 if (!GEP.hasNoUnsignedWrap())
1600 return false;
1601
1602 Value *Base = GEP.getPointerOperand();
1603 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Base))
1604 Base = InnerGEP->getPointerOperand();
1605
1606 ObjectSizeOpts Opts;
1607 // Workaround for gep inbounds, ptr null, idx.
1608 Opts.NullIsUnknownSize = true;
1609 // Be conservative since we are not clear on whether an out of bounds access
1610 // to the padding is UB or not.
1611 Opts.RoundToAlign = true;
1612 std::optional<TypeSize> Size = getBaseObjectSize(Base, DL, &TLI, Opts);
1613 if (!Size || Size->isScalable())
1614 return false;
1615
1617 if (Offset.BasePtr != Base || !Offset.NW.hasNoUnsignedWrap())
1618 return false;
1619
1620 if (Offset.VariableOffsets.size() != 1)
1621 return false;
1622
1623 uint64_t BitWidth = Offset.ConstantOffset.getBitWidth();
1624 auto &[Index, Scale] = Offset.VariableOffsets.front();
1625 // Bail out on non-canonical GEPs.
1626 if (Index->getType()->getScalarSizeInBits() != BitWidth)
1627 return false;
1628
1629 // Index * Scale + ConstOffset + AccessSize <= AllocSize
1630 // With nuw flag, we know that the index addition doesn't have unsigned wrap.
1631 // If (AllocSize - (ConstOffset + AccessSize)) wraps around, there is no valid
1632 // value for Index.
1633 APInt MaxIndex = (APInt(BitWidth, Size->getFixedValue() - AccessSize,
1634 /*isSigned=*/false, /*implicitTrunc=*/true) -
1635 Offset.ConstantOffset)
1636 .udiv(Scale);
1638 A = Index;
1639 B = ConstantInt::get(Index->getType(), MaxIndex);
1640 return true;
1641}
1642
1643/// Returns true if \p I is a candidate whose poison-generating flags may be
1644/// strengthened using the constraint systems.
1646 if (auto *Trunc = dyn_cast<TruncInst>(I))
1647 return Trunc->getType()->isIntegerTy() && Trunc->hasNoSignedWrap() &&
1648 !Trunc->hasNoUnsignedWrap();
1649
1650 auto *BO = dyn_cast<BinaryOperator>(I);
1651 if (!BO || !BO->getType()->isIntegerTy())
1652 return false;
1653
1654 switch (BO->getOpcode()) {
1655 case Instruction::Sub:
1656 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
1657 return false;
1658 // A - B does not wrap unsigned if A >=u B, and does not wrap signed if
1659 // 0 <=s B <=s A. With a constant B, bounds on A can refine both flags.
1660 return true;
1661 case Instruction::Add:
1662 case Instruction::Mul:
1663 case Instruction::Shl:
1664 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
1665 return false;
1666 // With a constant second operand, we can use bounds on the first operand to
1667 // refine no-wrap flags. Independently, nuw can be added for nsw if the
1668 // operands are non-negative.
1669 return isa<ConstantInt>(BO->getOperand(1)) || BO->hasNoSignedWrap();
1670 default:
1671 return false;
1672 }
1673}
1674
1675/// Try to strengthen \p I's poison generating flags using \p Info. Returns
1676/// true if \p I was modified.
1677static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info) {
1678 assert(canStrengthenFlags(I) && "not a candidate for flag strengthening");
1679
1680 bool Changed = false;
1681 if (!I->hasNoSignedWrap() && isKnownNoWrap(I, Info, /*Signed=*/true)) {
1682 LLVM_DEBUG(dbgs() << "Adding nsw to " << *I << "\n");
1683 I->setHasNoSignedWrap();
1684 Changed = true;
1685 }
1686 if (!I->hasNoUnsignedWrap() && isKnownNoWrap(I, Info, /*Signed=*/false)) {
1687 LLVM_DEBUG(dbgs() << "Adding nuw to " << *I << "\n");
1688 I->setHasNoUnsignedWrap();
1689 Changed = true;
1690 }
1691 return Changed;
1692}
1693
1694void State::addInfoFor(BasicBlock &BB) {
1695 addBoundsForHeaderInductions(BB);
1696 addInfoForInductions(BB);
1697 auto &DL = BB.getDataLayout();
1698
1699 Value *A, *B;
1700 CmpPredicate Pred;
1701 // True as long as the current instruction is guaranteed to execute.
1702 bool GuaranteedToExecute = true;
1703 // Queue conditions and assumes.
1704 for (Instruction &I : BB) {
1705 if (match(&I, m_ICmpLike(Pred, m_Value(), m_Value()))) {
1706 for (Use &U : I.uses()) {
1707 auto *UserI = getContextInstForUse(U);
1708 auto *DTN = DT.getNode(UserI->getParent());
1709 if (!DTN)
1710 continue;
1711 WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1712 }
1713 continue;
1714 }
1715
1716 auto AddFactFromMemoryAccess = [&](Value *Ptr, Type *AccessType) {
1717 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1718 if (!GEP)
1719 return;
1720 TypeSize AccessSize = DL.getTypeStoreSize(AccessType);
1721 if (!AccessSize.isFixed())
1722 return;
1723 if (GuaranteedToExecute) {
1725 Pred, A, B, DL, TLI)) {
1726 // The memory access is guaranteed to execute when BB is entered,
1727 // hence the constraint holds on entry to BB.
1728 WorkList.emplace_back(FactOrCheck::getConditionFact(
1729 DT.getNode(I.getParent()), Pred, A, B));
1730 }
1731 } else {
1732 WorkList.emplace_back(
1733 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1734 }
1735 };
1736
1737 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1738 if (!LI->isVolatile())
1739 AddFactFromMemoryAccess(LI->getPointerOperand(), LI->getAccessType());
1740 }
1741 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1742 if (!SI->isVolatile())
1743 AddFactFromMemoryAccess(SI->getPointerOperand(), SI->getAccessType());
1744 }
1745
1746 auto *II = dyn_cast<IntrinsicInst>(&I);
1747 Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1748 switch (ID) {
1749 case Intrinsic::assume: {
1750 if (!match(I.getOperand(0), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1751 break;
1752 if (GuaranteedToExecute) {
1753 // The assume is guaranteed to execute when BB is entered, hence Cond
1754 // holds on entry to BB.
1755 WorkList.emplace_back(FactOrCheck::getConditionFact(
1756 DT.getNode(I.getParent()), Pred, A, B));
1757 } else {
1758 WorkList.emplace_back(
1759 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1760 }
1761 break;
1762 }
1763 // Enqueue intrinsics for simplification.
1764 case Intrinsic::uadd_with_overflow:
1765 case Intrinsic::sadd_with_overflow:
1766 case Intrinsic::usub_with_overflow:
1767 case Intrinsic::ssub_with_overflow:
1768 case Intrinsic::umul_with_overflow:
1769 case Intrinsic::smul_with_overflow:
1770 case Intrinsic::ucmp:
1771 case Intrinsic::scmp:
1772 WorkList.push_back(
1773 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1774 break;
1775 // Enqueue the intrinsics to add extra info.
1776 case Intrinsic::umin:
1777 case Intrinsic::umax:
1778 case Intrinsic::smin:
1779 case Intrinsic::smax:
1780 case Intrinsic::usub_sat:
1781 // TODO: handle llvm.abs as well
1782 WorkList.push_back(
1783 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1784 [[fallthrough]];
1785 case Intrinsic::uadd_sat:
1786 // TODO: Check if it is possible to instead only added the min/max facts
1787 // when simplifying uses of the min/max intrinsics.
1789 break;
1790 [[fallthrough]];
1791 case Intrinsic::abs:
1792 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1793 break;
1794 }
1795
1796 // Add facts from unsigned division, remainder and logical shift right, and
1797 // from signed division and remainder.
1798 // urem x, n: result < n and result <= x
1799 // udiv x, n: result <= x
1800 // lshr x, n: result <= x
1801 // srem x, n: result >= 0 and result <= x, if x >= 0
1802 // result < n, if n > 0
1803 // sdiv x, n: result >= 0 and result <= x, if x >= 0 and n > 0
1804 // result >= 0 and result < x, if x > 0 and n > 1
1805 if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1806 if ((BO->getOpcode() == Instruction::URem ||
1807 BO->getOpcode() == Instruction::UDiv ||
1808 BO->getOpcode() == Instruction::LShr ||
1809 BO->getOpcode() == Instruction::SRem ||
1810 BO->getOpcode() == Instruction::SDiv) &&
1812 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), BO));
1813 }
1814
1815 // Queue instructions whose flags may be strengthened, checked at the
1816 // closest point dominating all uses.
1817 if (canStrengthenFlags(&I)) {
1818 Instruction *CommonDom = findCommonDominatorOfUses(I, DT);
1819 WorkList.push_back(FactOrCheck::getCheck(
1820 DT.getNode(CommonDom->getParent()), &I, CommonDom));
1821 }
1822
1823 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1824 }
1825
1826 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1827 for (auto &Case : Switch->cases()) {
1828 BasicBlock *Succ = Case.getCaseSuccessor();
1829 Value *V = Case.getCaseValue();
1830 if (!canAddSuccessor(BB, Succ))
1831 continue;
1832 WorkList.emplace_back(FactOrCheck::getConditionFact(
1833 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1834 }
1835 return;
1836 }
1837
1838 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1839 if (!Br)
1840 return;
1841
1842 Value *Cond = Br->getCondition();
1843
1844 // If the condition is a chain of ORs/AND and the successor only has the
1845 // current block as predecessor, queue conditions for the successor.
1846 Value *Op0, *Op1;
1847 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1848 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1849 bool IsOr = match(Cond, m_LogicalOr());
1850 bool IsAnd = match(Cond, m_LogicalAnd());
1851 // If there's a select that matches both AND and OR, we need to commit to
1852 // one of the options. Arbitrarily pick OR.
1853 if (IsOr && IsAnd)
1854 IsAnd = false;
1855
1856 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1857 if (canAddSuccessor(BB, Successor)) {
1858 SmallVector<Value *> CondWorkList;
1859 SmallPtrSet<Value *, 8> SeenCond;
1860 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1861 if (SeenCond.insert(V).second)
1862 CondWorkList.push_back(V);
1863 };
1864 QueueValue(Op1);
1865 QueueValue(Op0);
1866 while (!CondWorkList.empty()) {
1867 Value *Cur = CondWorkList.pop_back_val();
1868 if (match(Cur, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
1869 WorkList.emplace_back(FactOrCheck::getConditionFact(
1870 DT.getNode(Successor),
1871 IsOr ? CmpPredicate::getInverse(Pred) : Pred, A, B));
1872 continue;
1873 }
1874 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1875 QueueValue(Op1);
1876 QueueValue(Op0);
1877 continue;
1878 }
1879 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1880 QueueValue(Op1);
1881 QueueValue(Op0);
1882 continue;
1883 }
1884 }
1885 }
1886 return;
1887 }
1888
1889 if (!match(Br->getCondition(), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1890 return;
1891 if (canAddSuccessor(BB, Br->getSuccessor(0)))
1892 WorkList.emplace_back(FactOrCheck::getConditionFact(
1893 DT.getNode(Br->getSuccessor(0)), Pred, A, B));
1894 if (canAddSuccessor(BB, Br->getSuccessor(1)))
1895 WorkList.emplace_back(FactOrCheck::getConditionFact(
1896 DT.getNode(Br->getSuccessor(1)), CmpPredicate::getInverse(Pred), A, B));
1897}
1898
1899#ifndef NDEBUG
1901 Value *LHS, Value *RHS) {
1902 OS << "icmp " << Pred << ' ';
1903 LHS->printAsOperand(OS, /*PrintType=*/true);
1904 OS << ", ";
1905 RHS->printAsOperand(OS, /*PrintType=*/false);
1906}
1907#endif
1908
1909namespace {
1910/// Helper to keep track of a condition and if it should be treated as negated
1911/// for reproducer construction.
1912/// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1913/// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1914struct ReproducerEntry {
1915 ICmpInst::Predicate Pred;
1916 Value *LHS;
1917 Value *RHS;
1918
1919 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1920 : Pred(Pred), LHS(LHS), RHS(RHS) {}
1921};
1922} // namespace
1923
1924/// Helper function to generate a reproducer function for simplifying \p Cond.
1925/// The reproducer function contains a series of @llvm.assume calls, one for
1926/// each condition in \p Stack. For each condition, the operand instruction are
1927/// cloned until we reach operands that have an entry in \p Value2Index. Those
1928/// will then be added as function arguments. \p DT is used to order cloned
1929/// instructions. The reproducer function will get added to \p M, if it is
1930/// non-null. Otherwise no reproducer function is generated.
1931static void generateReproducer(Instruction *Cond, bool IsSigned, Module *M,
1933 ConstraintInfo &Info, DominatorTree &DT) {
1934 if (!M)
1935 return;
1936
1937 LLVMContext &Ctx = Cond->getContext();
1938
1939 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1940
1941 ValueToValueMapTy Old2New;
1944 // Traverse Cond and its operands recursively until we reach a value that's in
1945 // Value2Index or not an instruction, or not a operation that
1946 // ConstraintElimination can decompose. Such values will be considered as
1947 // external inputs to the reproducer, they are collected and added as function
1948 // arguments later.
1949 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1950 auto &Value2Index = Info.getValue2Index(IsSigned);
1951 SmallVector<Value *, 4> WorkList(Ops);
1952 while (!WorkList.empty()) {
1953 Value *V = WorkList.pop_back_val();
1954 if (!Seen.insert(V).second)
1955 continue;
1956 if (Old2New.find(V) != Old2New.end())
1957 continue;
1958 if (isa<Constant>(V))
1959 continue;
1960
1961 auto *I = dyn_cast<Instruction>(V);
1962 if (Value2Index.contains(V) || !I ||
1964 Old2New[V] = V;
1965 Args.push_back(V);
1966 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n");
1967 } else {
1968 append_range(WorkList, I->operands());
1969 }
1970 }
1971 };
1972
1973 for (auto &Entry : Stack)
1974 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1975 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1976 CollectArguments(Cond, IsSigned);
1977
1978 SmallVector<Type *> ParamTys;
1979 for (auto *P : Args)
1980 ParamTys.push_back(P->getType());
1981
1982 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1983 /*isVarArg=*/false);
1985 Cond->getModule()->getName() +
1986 Cond->getFunction()->getName() + "repro",
1987 M);
1988 // Add arguments to the reproducer function for each external value collected.
1989 for (unsigned I = 0; I < Args.size(); ++I) {
1990 F->getArg(I)->setName(Args[I]->getName());
1991 Old2New[Args[I]] = F->getArg(I);
1992 }
1993
1994 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1995 IRBuilder<> Builder(Entry);
1996 Builder.CreateRet(Builder.getTrue());
1997 Builder.SetInsertPoint(Entry->getTerminator());
1998
1999 // Clone instructions in \p Ops and their operands recursively until reaching
2000 // an value in Value2Index (external input to the reproducer). Update Old2New
2001 // mapping for the original and cloned instructions. Sort instructions to
2002 // clone by dominance, then insert the cloned instructions in the function.
2003 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
2004 SmallVector<Value *, 4> WorkList(Ops);
2006 auto &Value2Index = Info.getValue2Index(IsSigned);
2007 while (!WorkList.empty()) {
2008 Value *V = WorkList.pop_back_val();
2009 if (Old2New.find(V) != Old2New.end())
2010 continue;
2011
2012 auto *I = dyn_cast<Instruction>(V);
2013 if (!Value2Index.contains(V) && I) {
2014 Old2New[V] = nullptr;
2015 ToClone.push_back(I);
2016 append_range(WorkList, I->operands());
2017 }
2018 }
2019
2020 sort(ToClone,
2021 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
2022 for (Instruction *I : ToClone) {
2023 Instruction *Cloned = I->clone();
2024 Old2New[I] = Cloned;
2025 Old2New[I]->setName(I->getName());
2026 Cloned->insertBefore(Builder.GetInsertPoint());
2028 Cloned->setDebugLoc({});
2029 }
2030 };
2031
2032 // Materialize the assumptions for the reproducer using the entries in Stack.
2033 // That is, first clone the operands of the condition recursively until we
2034 // reach an external input to the reproducer and add them to the reproducer
2035 // function. Then add an ICmp for the condition (with the inverse predicate if
2036 // the entry is negated) and an assert using the ICmp.
2037 for (auto &Entry : Stack) {
2038 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
2039 continue;
2040
2041 LLVM_DEBUG(dbgs() << " Materializing assumption ";
2042 dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
2043 dbgs() << "\n");
2044 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
2045
2046 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
2047 Builder.CreateAssumption(Cmp);
2048 }
2049
2050 // Finally, clone the condition to reproduce and remap instruction operands in
2051 // the reproducer using Old2New.
2052 CloneInstructions(Cond, IsSigned);
2053 Entry->getTerminator()->setOperand(0, Cond);
2054 remapInstructionsInBlocks({Entry}, Old2New);
2055
2056 assert(!verifyFunction(*F, &dbgs()));
2057}
2058
2059/// If \p V is a variable in the system and constraint \p C does not contain \p
2060/// V, we managed to decompose \p V at this point, but likely not earlier when
2061/// the fact involving \p V was added. In that case, return a new row for
2062/// V <= decompose(V) to link the variable with the decomposition result.
2063static RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C,
2064 ConstraintInfo &Info,
2065 const DataLayout &DL) {
2066 const auto &Value2Index = Info.getValue2Index(C.IsSigned);
2067 auto It = Value2Index.find(V);
2068 if (It == Value2Index.end() ||
2069 any_of(C.Coefficients,
2070 [Id = It->second](const Entry &E) { return E.Id == Id; }))
2071 return {};
2072
2073 SmallVector<Value *> NewVariables;
2074 RowTy Row =
2075 getRowForLessEqual(Decomposition(V), decompose(V, Info, C.IsSigned, DL),
2076 Value2Index, NewVariables);
2077 return NewVariables.empty() ? Row : RowTy();
2078}
2079
2080static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
2081 Value *B, Instruction *CheckInst,
2082 ConstraintInfo &Info) {
2083 LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
2084
2085 auto TryWithConstraint = [&](const ConstraintTy &R) -> std::optional<bool> {
2086 if (R.empty()) {
2087 LLVM_DEBUG(dbgs() << " failed to decompose condition\n");
2088 return std::nullopt;
2089 }
2090
2091 auto &CSToUse = Info.getCS(R.IsSigned);
2092 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
2093 if (!DebugCounter::shouldExecute(EliminatedCounter))
2094 return std::nullopt;
2095 LLVM_DEBUG({
2096 dbgs() << "Condition ";
2098 *ImpliedCondition ? Pred
2100 A, B);
2101 dbgs() << " implied by dominating constraints\n";
2102 CSToUse.dump();
2103 });
2104 return ImpliedCondition;
2105 }
2106 return std::nullopt;
2107 };
2108
2109 // Retry the query after adding additional facts for A == decompose(A) and B
2110 // == decompose(B), if needed.
2111 auto TryWithLinkedDecomposition =
2112 [&](const ConstraintTy &C) -> std::optional<bool> {
2113 return Info.tryWithLinkRows(A, B, C, [&] { return TryWithConstraint(C); });
2114 };
2115
2116 auto R = Info.getConstraintForSolving(Pred, A, B);
2117 if (auto ImpliedCondition = TryWithLinkedDecomposition(R))
2118 return ImpliedCondition;
2119
2120 // For non-negative operands unsigned queries can also be checked against the
2121 // signed system.
2122 if (CmpInst::isUnsigned(Pred) && A->getType()->isIntegerTy()) {
2123 SmallVector<Value *> NewVariables;
2124 auto SR = Info.getConstraint(ICmpInst::getSignedPredicate(Pred), A, B,
2125 NewVariables);
2126 if (NewVariables.empty() && !SR.empty() && Info.isKnownNonNegative(A) &&
2127 Info.isKnownNonNegative(B))
2128 if (auto ImpliedCondition = TryWithConstraint(SR))
2129 return ImpliedCondition;
2130 }
2131
2132 // Additionally, query the signed system for eq/ne predicates if we know about
2133 // A or B.
2135 const auto &Value2Index = Info.getValue2Index(/*Signed=*/true);
2136 if (!Value2Index.contains(A) && !Value2Index.contains(B))
2137 return std::nullopt;
2138
2139 SmallVector<Value *> NewVariables;
2140 auto SR = Info.getConstraint(Pred, A, B, NewVariables,
2141 /*ForceSignedSystem=*/true);
2142 if (NewVariables.empty()) {
2143 if (auto ImpliedCondition = TryWithLinkedDecomposition(SR))
2144 return ImpliedCondition;
2145 }
2146 }
2147 return std::nullopt;
2148}
2149
2151 CmpPredicate Pred, Value *A, Value *B, Instruction *CheckInst,
2152 ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
2153 Instruction *ContextInst, Module *ReproducerModule,
2154 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
2156 auto ReplaceCmpWithConstant = [&](Instruction *CheckInst, bool IsTrue) {
2157 generateReproducer(CheckInst, ICmpInst::isSigned(Pred), ReproducerModule,
2158 ReproducerCondStack, Info, DT);
2159 Constant *ConstantC = ConstantInt::getBool(
2160 CmpInst::makeCmpResultType(CheckInst->getType()), IsTrue);
2161 bool Changed = CheckInst->replaceUsesWithIf(ConstantC, [&](Use &U) {
2162 auto *UserI = getContextInstForUse(U);
2163 auto *DTN = DT.getNode(UserI->getParent());
2164 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
2165 return false;
2166 if (UserI->getParent() == ContextInst->getParent() &&
2167 UserI->comesBefore(ContextInst))
2168 return false;
2169
2170 // Conditions in an assume trivially simplify to true. Skip uses
2171 // in assume calls to not destroy the available information.
2172 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
2173 return !II || II->getIntrinsicID() != Intrinsic::assume;
2174 });
2175 NumCondsRemoved++;
2176
2177 // Update the debug value records that satisfy the same condition used
2178 // in replaceUsesWithIf.
2180 findDbgUsers(CheckInst, DVRUsers);
2181
2182 for (auto *DVR : DVRUsers) {
2183 auto *DTN = DT.getNode(DVR->getParent());
2184 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
2185 continue;
2186
2187 auto *MarkedI = DVR->getInstruction();
2188 if (MarkedI->getParent() == ContextInst->getParent() &&
2189 MarkedI->comesBefore(ContextInst))
2190 continue;
2191
2192 DVR->replaceVariableLocationOp(CheckInst, ConstantC);
2193 }
2194
2195 if (CheckInst->use_empty())
2196 ToRemove.push_back(CheckInst);
2197
2198 return Changed;
2199 };
2200
2201 if (auto ImpliedCondition = checkCondition(Pred, A, B, CheckInst, Info))
2202 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
2203
2204 // When the predicate is samesign and unsigned, we can also make use of the
2205 // signed predicate information.
2206 if (Pred.hasSameSign() && ICmpInst::isUnsigned(Pred))
2207 if (auto ImpliedCondition = checkCondition(
2208 ICmpInst::getSignedPredicate(Pred), A, B, CheckInst, Info))
2209 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
2210
2211 return false;
2212}
2213
2214static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
2216 auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
2217 // TODO: generate reproducer for min/max.
2218 MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
2219 ToRemove.push_back(MinMax);
2220 return true;
2221 };
2222
2224 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
2225 if (auto ImpliedCondition = checkCondition(
2226 Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
2227 return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
2228 if (auto ImpliedCondition = checkCondition(
2229 Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
2230 return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
2231 return false;
2232}
2233
2234static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
2236 Value *LHS = I->getOperand(0);
2237 Value *RHS = I->getOperand(1);
2238 if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
2239 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
2240 ToRemove.push_back(I);
2241 return true;
2242 }
2243 if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
2244 I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
2245 ToRemove.push_back(I);
2246 return true;
2247 }
2248 if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
2249 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
2250 ToRemove.push_back(I);
2251 return true;
2252 }
2253 return false;
2254}
2255
2256/// Try to replace \p USub by a plain subtract, if \p Info proves it cannot
2257/// saturate. Returns true if \p USub was replaced.
2258static bool checkAndReplaceUSubSat(SaturatingInst *USub, ConstraintInfo &Info,
2260 // usub.sat(A, B) is A - B exactly when A >=u B.
2261 Value *A = USub->getLHS();
2262 Value *B = USub->getRHS();
2263 if (!checkCondition(CmpInst::ICMP_UGE, A, B, USub, Info).value_or(false))
2264 return false;
2265
2266 IRBuilder<> Builder(USub);
2267 Value *Sub = Builder.CreateSub(A, B, "", /*HasNUW=*/true,
2268 /*HasNSW=*/Info.isKnownNonNegative(A));
2269 USub->replaceAllUsesWith(Sub);
2270 Sub->takeName(USub);
2271 ToRemove.push_back(USub);
2272 return true;
2273}
2274
2275static void
2276removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
2277 Module *ReproducerModule,
2278 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2279 SmallVectorImpl<StackEntry> &DFSInStack) {
2280 Info.getDecomposeCache().clear();
2281 Info.popLastConstraint(E.IsSigned);
2282 // Remove variables in the system that went out of scope.
2283 auto &Mapping = Info.getValue2Index(E.IsSigned);
2284 for (Value *V : E.ValuesToRelease)
2285 Mapping.erase(V);
2286 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
2287 DFSInStack.pop_back();
2288 if (ReproducerModule)
2289 ReproducerCondStack.pop_back();
2290}
2291
2292/// Check if either the first condition of an AND or OR is implied by the
2293/// (negated in case of OR) second condition or vice versa.
2295 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
2296 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2297 SmallVectorImpl<StackEntry> &DFSInStack,
2299 Instruction *JoinOp = CB.getContextInst();
2300 if (JoinOp->use_empty())
2301 return false;
2302
2303 Instruction *CmpToCheck = cast<Instruction>(CB.getInstructionToSimplify());
2304 unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
2305
2306 // Don't try to simplify the first condition of a select by the second, as
2307 // this may make the select more poisonous than the original one.
2308 // TODO: check if the first operand may be poison.
2309 if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
2310 return false;
2311
2312 unsigned OldSize = DFSInStack.size();
2313 llvm::scope_exit InfoRestorer([&]() {
2314 // Remove entries again.
2315 while (OldSize < DFSInStack.size()) {
2316 StackEntry E = DFSInStack.back();
2317 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
2318 DFSInStack);
2319 }
2320 });
2321 bool IsOr = match(JoinOp, m_LogicalOr());
2322 SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
2323 // Do a traversal of the AND/OR tree to add facts from leaf compares.
2324 while (!Worklist.empty()) {
2325 Value *Val = Worklist.pop_back_val();
2326 Value *LHS, *RHS;
2328 if (match(Val, m_ICmpLike(Pred, m_Value(LHS), m_Value(RHS)))) {
2329 // For OR, check if the negated condition implies CmpToCheck.
2330 if (IsOr)
2332 // Optimistically add fact from the other compares in the AND/OR.
2333 Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
2334 continue;
2335 }
2336 if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
2337 : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
2338 Worklist.push_back(LHS);
2339 Worklist.push_back(RHS);
2340 }
2341 }
2342 if (OldSize == DFSInStack.size())
2343 return false;
2344
2345 Value *A, *B;
2347 [[maybe_unused]] bool Matched =
2348 match(CmpToCheck, m_ICmpLike(Pred, m_Value(A), m_Value(B)));
2349 assert(Matched && "expected icmp-like match");
2350 // Check if the second condition can be simplified now.
2351 if (auto ImpliedCondition = checkCondition(Pred, A, B, CmpToCheck, Info)) {
2352 if (IsOr == *ImpliedCondition)
2353 JoinOp->replaceAllUsesWith(
2354 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
2355 else
2356 JoinOp->replaceAllUsesWith(JoinOp->getOperand(OtherOpIdx));
2357 ToRemove.push_back(JoinOp);
2358 return true;
2359 }
2360
2361 return false;
2362}
2363
2364void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
2365 unsigned NumIn, unsigned NumOut,
2366 SmallVectorImpl<StackEntry> &DFSInStack) {
2367 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, false);
2368 // If the Pred is eq/ne, also add the fact to signed system.
2370 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, true);
2371 if (Pred == CmpInst::ICMP_NE)
2372 tightenBoundUsingNe(A, B, NumIn, NumOut, DFSInStack);
2373}
2374
2375void ConstraintInfo::tightenBoundUsingNe(
2376 Value *A, Value *B, unsigned NumIn, unsigned NumOut,
2377 SmallVectorImpl<StackEntry> &DFSInStack) {
2378 if (!A->getType()->isIntOrPtrTy())
2379 return;
2380
2381 for (bool IsSigned : {false, true}) {
2382 // In the unsigned system `A u>= 0` holds for every A, so getConstraint
2383 // already turned `A != 0` into `A u> 0`.
2384 if (!IsSigned && match(B, m_Zero()))
2385 continue;
2386
2387 // Skip if there are any unknown variables.
2388 const auto &Value2Index = getValue2Index(IsSigned);
2389 if (any_of(decompose(A, *this, IsSigned, DL).Vars,
2390 [&Value2Index](const DecompEntry &E) {
2391 return !Value2Index.contains(E.Variable);
2392 }))
2393 continue;
2394
2395 // If the system implies `A >= B` then together with `A != B` we get the
2396 // strict `A > B`; symmetrically `A <= B` becomes `A < B`.
2397 CmpInst::Predicate GEPred =
2399 CmpInst::Predicate LEPred =
2401 for (CmpInst::Predicate NonStrict : {GEPred, LEPred}) {
2402 if (!doesHold(NonStrict, A, B))
2403 continue;
2405 LLVM_DEBUG(dbgs() << "Tightening '";
2406 dumpUnpackedICmp(dbgs(), NonStrict, A, B); dbgs() << "' to '";
2408 dbgs() << "' using inequality\n");
2409 addFactImpl(Strict, A, B, NumIn, NumOut, DFSInStack,
2410 /*ForceSignedSystem=*/false);
2411 break;
2412 }
2413 }
2414}
2415
2416void ConstraintInfo::addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B,
2417 unsigned NumIn, unsigned NumOut,
2418 SmallVectorImpl<StackEntry> &DFSInStack,
2419 bool ForceSignedSystem) {
2420 SmallVector<Value *> NewVariables;
2421 auto R = getConstraint(Pred, A, B, NewVariables, ForceSignedSystem);
2422
2423 // TODO: Support non-equality for facts as well.
2424 if (R.empty() || R.isNe())
2425 return;
2426
2427 auto &CSToUse = getCS(R.IsSigned);
2428 // A row implied by a single existing row adds no information. Rows in the
2429 // system are removed in reverse order, so the existing row outlives R. Rows
2430 // in the system are normalized, so normalize R before comparing.
2431 if (!R.isEq() && NewVariables.empty()) {
2432 ConstraintSystem::normalizeByGCD(R.Coefficients);
2433 if (CSToUse.isImpliedBySingleRow(R.Coefficients))
2434 return;
2435 }
2436 LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
2437 dbgs() << "'\n");
2438 bool Added = CSToUse.addRow(R.Coefficients, R.NumVars);
2439 if (!Added)
2440 return;
2441
2442 DecomposeCache.clear();
2443
2444 // If R has been added to the system, add the new variables and queue it for
2445 // removal once it goes out-of-scope.
2446 SmallVector<Value *, 2> ValuesToRelease;
2447 auto &Value2Index = getValue2Index(R.IsSigned);
2448 for (Value *V : NewVariables) {
2449 Value2Index.try_emplace(V, Value2Index.size() + 1);
2450 ValuesToRelease.push_back(V);
2451 }
2452
2453 LLVM_DEBUG({
2454 dbgs() << " constraint: ";
2455 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
2456 dbgs() << "\n";
2457 });
2458
2459 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2460 std::move(ValuesToRelease));
2461
2462 if (!R.IsSigned) {
2463 for (Value *V : NewVariables) {
2464 // Add V > -1 constraints for all new variables.
2465 CSToUse.addRow({Entry(0, 0), Entry(-1, Value2Index.at(V))},
2466 Value2Index.size());
2467 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2468 SmallVector<Value *, 2>());
2469 }
2470 }
2471
2472 if (R.isEq()) {
2473 // Also add the inverted constraint for equality constraints.
2474 for (Entry &E : R.Coefficients)
2475 if (MulOverflow(E.Coefficient, int64_t(-1), E.Coefficient))
2476 return;
2477 CSToUse.addRow(R.Coefficients, R.NumVars);
2478
2479 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2480 SmallVector<Value *, 2>());
2481 }
2482}
2483
2484/// Replace the uses of \p II, which is known not to overflow, by the
2485/// corresponding plain binary operation and a false overflow flag.
2488 bool Changed = false;
2489 IRBuilder<> Builder(II->getIterator());
2490 Value *Res = nullptr;
2491 for (User *U : make_early_inc_range(II->users())) {
2492 if (match(U, m_ExtractValue<0>(m_Value()))) {
2493 if (!Res)
2494 Res = Builder.CreateNoWrapBinOp(II->getBinaryOp(), II->getLHS(),
2495 II->getRHS(),
2496 /*IsNUW=*/!II->isSigned(),
2497 /*IsNSW=*/II->isSigned());
2498 U->replaceAllUsesWith(Res);
2499 Changed = true;
2500 } else if (match(U, m_ExtractValue<1>(m_Value()))) {
2501 U->replaceAllUsesWith(ConstantInt::getFalse(U->getType()));
2502 Changed = true;
2503 } else
2504 continue;
2505
2506 if (U->use_empty()) {
2507 auto *I = cast<Instruction>(U);
2508 ToRemove.push_back(I);
2509 I->setOperand(0, PoisonValue::get(II->getType()));
2510 Changed = true;
2511 }
2512 }
2513
2514 if (II->use_empty()) {
2515 // Do not erase II here: the worklist may still hold Uses of II's operands.
2516 for (Use &Arg : II->args())
2517 Arg.set(PoisonValue::get(Arg->getType()));
2518 ToRemove.push_back(II);
2519 Changed = true;
2520 }
2521 return Changed;
2522}
2523
2524static bool
2527 if (!isKnownNoWrap(II, Info, II->isSigned()))
2528 return false;
2530}
2531
2533 ScalarEvolution *SE,
2536 const ScalarOptions &Opts = getScalarOptions(F);
2537 bool Changed = false;
2538 DT.updateDFSNumbers();
2539 SmallVector<Value *> FunctionArgs(llvm::make_pointer_range(F.args()));
2540 ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
2541 State S(DT, LI, SE, TLI);
2542 std::unique_ptr<Module> ReproducerModule(
2543 Opts.constraint_elimination_dump_reproducers
2544 ? new Module(F.getName(), F.getContext())
2545 : nullptr);
2546
2547 // First, collect conditions implied by branches and blocks with their
2548 // Dominator DFS in and out numbers.
2549 for (BasicBlock &BB : F) {
2550 if (!DT.getNode(&BB))
2551 continue;
2552 S.addInfoFor(BB);
2553 }
2554
2555 // Next, sort worklist by dominance, so that dominating conditions to check
2556 // and facts come before conditions and facts dominated by them. If a
2557 // condition to check and a fact have the same numbers, conditional facts come
2558 // first. Assume facts and checks are ordered according to their relative
2559 // order in the containing basic block. Also make sure conditions with
2560 // constant operands come before conditions without constant operands. This
2561 // increases the effectiveness of the current signed <-> unsigned fact
2562 // transfer logic.
2563 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
2564 auto HasNoConstOp = [](const FactOrCheck &B) {
2565 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
2566 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
2567 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
2568 };
2569 // If both entries have the same In numbers, conditional facts come first.
2570 // Otherwise use the relative order in the basic block.
2571 if (A.NumIn == B.NumIn) {
2572 if (A.isConditionFact() && B.isConditionFact()) {
2573 bool NoConstOpA = HasNoConstOp(A);
2574 bool NoConstOpB = HasNoConstOp(B);
2575 return NoConstOpA < NoConstOpB;
2576 }
2577 if (A.isConditionFact())
2578 return true;
2579 if (B.isConditionFact())
2580 return false;
2581 auto *InstA = A.getContextInst();
2582 auto *InstB = B.getContextInst();
2583 return InstA->comesBefore(InstB);
2584 }
2585 return A.NumIn < B.NumIn;
2586 });
2587
2588 SmallVector<Instruction *> ToRemove;
2589
2590 // Finally, process ordered worklist and eliminate implied conditions.
2591 SmallVector<StackEntry, 16> DFSInStack;
2592 SmallVector<ReproducerEntry> ReproducerCondStack;
2593 for (FactOrCheck &CB : S.WorkList) {
2594 // First, pop entries from the stack that are out-of-scope for CB. Remove
2595 // the corresponding entry from the constraint system.
2596 while (!DFSInStack.empty()) {
2597 auto &E = DFSInStack.back();
2598 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
2599 << "\n");
2600 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
2601 assert(E.NumIn <= CB.NumIn);
2602 if (CB.NumOut <= E.NumOut)
2603 break;
2604 LLVM_DEBUG({
2605 dbgs() << "Removing ";
2606 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
2607 Info.getValue2Index(E.IsSigned));
2608 dbgs() << "\n";
2609 });
2610 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
2611 DFSInStack);
2612 }
2613
2614 CmpPredicate Pred;
2615 Value *A, *B;
2616 // For a block, check if any CmpInsts become known based on the current set
2617 // of constraints.
2618 if (CB.isCheck()) {
2619 Instruction *Inst = CB.getInstructionToSimplify();
2620 if (!Inst)
2621 continue;
2622 if (canStrengthenFlags(Inst)) {
2623 Changed |= tryToStrengthenFlags(Inst, Info);
2624 continue;
2625 }
2626 LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
2627 << "\n");
2628 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
2630 } else if (match(Inst, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
2632 Pred, A, B, Inst, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
2633 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
2634 if (!Simplified &&
2635 match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
2637 CB, Info, ReproducerModule.get(), ReproducerCondStack, DFSInStack,
2638 ToRemove);
2639 }
2641 } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
2642 Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
2643 } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
2644 Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
2645 } else if (match(Inst, m_Intrinsic<Intrinsic::usub_sat>())) {
2646 Changed |=
2648 }
2649 continue;
2650 }
2651
2652 auto AddFact = [&](CmpPredicate Pred, Value *A, Value *B) {
2653 LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
2654 dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
2655 if (Info.getCS(CmpInst::isSigned(Pred)).size() >
2656 Opts.constraint_elimination_max_rows) {
2657 LLVM_DEBUG(
2658 dbgs()
2659 << "Skip adding constraint because system has too many rows.\n");
2660 return;
2661 }
2662
2663 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
2664 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
2665 ReproducerCondStack.emplace_back(Pred, A, B);
2666
2668 // If samesign is present on the ICmp, simply flip the sign of the
2669 // predicate, transferring the information from the signed system to the
2670 // unsigned system, and viceversa.
2671 if (Pred.hasSameSign()) {
2673 CB.NumIn, CB.NumOut, DFSInStack);
2674 // The operands also have the same sign: if one of them is known to
2675 // be non-negative (or negative), so is the other.
2676 if (A->getType()->isIntegerTy()) {
2677 std::optional<bool> ASign =
2678 Info.getKnownSign(A, /*StrictlyNegative=*/true);
2679 std::optional<bool> BSign =
2680 Info.getKnownSign(B, /*StrictlyNegative=*/true);
2681 if (ASign.has_value() != BSign.has_value()) {
2682 bool IsNegative = ASign ? *ASign : *BSign;
2683 Value *OtherOp = ASign ? B : A;
2684 Info.addFact(IsNegative ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGE,
2685 OtherOp, Constant::getNullValue(A->getType()),
2686 CB.NumIn, CB.NumOut, DFSInStack);
2687 }
2688 }
2689 } else {
2690 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut,
2691 DFSInStack);
2692 }
2693 }
2694
2695 // (X | Y) >s -1 implies X >s -1 and Y >s -1, because the sign bit of an
2696 // OR is the OR of the operand sign bits. Similarly, (X & Y) <s 0 implies
2697 // X <s 0 and Y <s 0. Look through these canonical forms produced by
2698 // InstCombine so the sign facts on the operands are available to the
2699 // solver.
2700 if ((Pred == CmpInst::ICMP_SGT && match(B, m_AllOnes())) ||
2701 (Pred == CmpInst::ICMP_SLT && match(B, m_Zero()))) {
2702 unsigned Opc =
2703 Pred == CmpInst::ICMP_SGT ? Instruction::Or : Instruction::And;
2704 SmallVector<Value *> Worklist = {A};
2705 SmallPtrSet<Value *, 4> Seen;
2706 while (!Worklist.empty()) {
2707 Value *Cur = Worklist.pop_back_val();
2708 auto *BO = dyn_cast<BinaryOperator>(Cur);
2709 if (!BO || BO->getOpcode() != Opc)
2710 continue;
2711 for (Value *Op : {BO->getOperand(0), BO->getOperand(1)}) {
2712 if (!Seen.insert(Op).second)
2713 continue;
2714 Worklist.push_back(Op);
2715 Info.addFact(Pred, Op, B, CB.NumIn, CB.NumOut, DFSInStack);
2716 }
2717 }
2718 }
2719
2720 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
2721 // Add dummy entries to ReproducerCondStack to keep it in sync with
2722 // DFSInStack.
2723 for (unsigned I = 0,
2724 E = (DFSInStack.size() - ReproducerCondStack.size());
2725 I < E; ++I) {
2726 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
2727 nullptr, nullptr);
2728 }
2729 }
2730 };
2731
2732 if (!CB.isConditionFact()) {
2733 Value *X;
2734 if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
2735 // If is_int_min_poison is true then we may assume llvm.abs >= 0.
2736 if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
2737 AddFact(CmpInst::ICMP_SGE, CB.Inst,
2738 ConstantInt::get(CB.Inst->getType(), 0));
2739 AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
2740 continue;
2741 }
2742
2743 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
2744 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
2745 AddFact(Pred, MinMax, MinMax->getLHS());
2746 AddFact(Pred, MinMax, MinMax->getRHS());
2747 continue;
2748 }
2749 if (auto *USatI = dyn_cast<SaturatingInst>(CB.Inst)) {
2750 switch (USatI->getIntrinsicID()) {
2751 default:
2752 llvm_unreachable("Unexpected intrinsic.");
2753 case Intrinsic::uadd_sat:
2754 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getLHS());
2755 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getRHS());
2756 break;
2757 case Intrinsic::usub_sat:
2758 AddFact(ICmpInst::ICMP_ULE, USatI, USatI->getLHS());
2759 break;
2760 }
2761 continue;
2762 }
2763
2764 if (auto *BO = dyn_cast<BinaryOperator>(CB.Inst)) {
2765 if (BO->getOpcode() == Instruction::URem) {
2766 // urem x, n: result < n (remainder is always less than divisor)
2767 AddFact(CmpInst::ICMP_ULT, BO, BO->getOperand(1));
2768 // urem x, n: result <= x (remainder is at most the dividend)
2769 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2770 continue;
2771 }
2772 if (BO->getOpcode() == Instruction::UDiv) {
2773 // udiv x, n: result <= x (quotient is at most the dividend)
2774 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2775 continue;
2776 }
2777 if (BO->getOpcode() == Instruction::LShr) {
2778 // lshr x, n: result <= x (right shift cannot increase the value)
2779 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2780 continue;
2781 }
2782 if (BO->getOpcode() == Instruction::SRem) {
2783 Value *X = BO->getOperand(0);
2784 Value *N = BO->getOperand(1);
2785 Constant *Zero = Constant::getNullValue(BO->getType());
2786 if (Info.doesHold(CmpInst::ICMP_SGE, X, Zero) ||
2787 isKnownNonNegative(X, F.getDataLayout())) {
2788 // srem x, n: result >= 0, if x >= 0 (result has the sign of x)
2789 AddFact(CmpInst::ICMP_SGE, BO, Zero);
2790 // srem x, n: result <= x, if x >= 0 (|result| <= |x| and both are
2791 // non-negative)
2792 AddFact(CmpInst::ICMP_SLE, BO, X);
2793 }
2794 if (Info.doesHold(CmpInst::ICMP_SGE, N, Zero) ||
2795 isKnownPositive(N, F.getDataLayout())) {
2796 // srem x, n: result <= n, if n >= 0 (|result| < n, so result <= n -
2797 // 1
2798 AddFact(CmpInst::ICMP_SLT, BO, N);
2799 }
2800 continue;
2801 }
2802 if (BO->getOpcode() == Instruction::SDiv) {
2803 Value *X = BO->getOperand(0);
2804 Value *N = BO->getOperand(1);
2805 if (!Info.isKnownNonNegative(X) || !Info.isKnownPositive(N))
2806 continue;
2807
2808 bool IsStrict = Info.isKnownPositive(X) &&
2809 Info.doesHold(CmpInst::ICMP_SGT, N,
2810 ConstantInt::get(N->getType(), 1));
2811 AddFact(CmpInst::ICMP_SGE, BO, Constant::getNullValue(BO->getType()));
2812 AddFact(IsStrict ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, BO, X);
2813 continue;
2814 }
2815 }
2816
2817 auto &DL = F.getDataLayout();
2818 auto AddFactsAboutIndices = [&](Value *Ptr, Type *AccessType) {
2819 CmpPredicate Pred;
2820 Value *A, *B;
2823 DL.getTypeStoreSize(AccessType).getFixedValue(), Pred, A, B, DL,
2824 TLI))
2825 AddFact(Pred, A, B);
2826 };
2827
2828 if (auto *LI = dyn_cast<LoadInst>(CB.Inst)) {
2829 AddFactsAboutIndices(LI->getPointerOperand(), LI->getAccessType());
2830 continue;
2831 }
2832 if (auto *SI = dyn_cast<StoreInst>(CB.Inst)) {
2833 AddFactsAboutIndices(SI->getPointerOperand(), SI->getAccessType());
2834 continue;
2835 }
2836 }
2837
2838 if (CB.isConditionFact()) {
2839 Pred = CB.Cond.Pred;
2840 A = CB.Cond.Op0;
2841 B = CB.Cond.Op1;
2842 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
2843 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
2844 LLVM_DEBUG({
2845 dbgs() << "Not adding fact ";
2847 dbgs() << " because precondition ";
2848 dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
2849 CB.DoesHold.Op1);
2850 dbgs() << " does not hold.\n";
2851 });
2852 continue;
2853 }
2854 } else {
2855 [[maybe_unused]] bool Matched =
2858 assert(Matched &&
2859 "Must have an assume intrinsic with a icmp like operand");
2860 }
2861 AddFact(Pred, A, B);
2862 }
2863
2864 if (ReproducerModule && !ReproducerModule->functions().empty()) {
2865 std::string S;
2866 raw_string_ostream StringS(S);
2867 ReproducerModule->print(StringS, nullptr);
2868 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
2869 Rem << ore::NV("module") << S;
2870 ORE.emit(Rem);
2871 }
2872
2873#ifndef NDEBUG
2874 unsigned SignedEntries =
2875 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
2876 assert(Info.getCS(false).size() - FunctionArgs.size() ==
2877 DFSInStack.size() - SignedEntries &&
2878 "updates to CS and DFSInStack are out of sync");
2879 assert(Info.getCS(true).size() == SignedEntries &&
2880 "updates to CS and DFSInStack are out of sync");
2881#endif
2882
2883 for (Instruction *I : ToRemove)
2884 I->eraseFromParent();
2885 return Changed;
2886}
2887
2890 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2891 auto &LI = AM.getResult<LoopAnalysis>(F);
2892 // SCEV is only used for loops, only construct it if there are some.
2893 auto *SE = LI.empty() ? nullptr : &AM.getResult<ScalarEvolutionAnalysis>(F);
2895 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2896 if (!eliminateConstraints(F, DT, LI, SE, ORE, TLI))
2897 return PreservedAnalyses::all();
2898
2902 return PA;
2903}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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:665
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 eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, OptimizationRemarkEmitter &ORE, TargetLibraryInfo &TLI)
static bool canStrengthenFlags(Instruction *I)
Returns true if I is a candidate whose poison-generating flags may be strengthened using the constrai...
static bool doesHoldInRange(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 RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C, ConstraintInfo &Info, const DataLayout &DL)
If V is a variable in the system and constraint C does not contain V, we managed to decompose V at th...
static int64_t MinSignedConstraintValue
static bool tryToSimplifyOverflowMath(WithOverflowInst *II, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
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 isKnownNoWrap(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, unsigned NoWrapFlags, ConstraintInfo &Info, bool Signed)
Returns true if Opcode applied to Op0 and Op1 with NoWrapFlags is known to not wrap in signed or unsi...
static bool mayLookThrough(Value *V)
Returns true if V is an operation decomposeImpl can look through.
static bool canUseSExt(ConstantInt *CI)
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 Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
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 OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL)
static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info)
Try to strengthen I's poison generating flags using Info.
static RowTy getRowForLessEqual(const Decomposition &ADec, const Decomposition &BDec, const DenseMap< Value *, unsigned > &Value2Index, SmallVectorImpl< Value * > &NewVariables)
Build the row for 'ADec <= BDec', using the indices from Value2Index.
static void dumpConstraint(ArrayRef< Entry > C, const DenseMap< Value *, unsigned > &Value2Index)
static bool replaceOverflowUses(WithOverflowInst *II, SmallVectorImpl< Instruction * > &ToRemove)
Replace the uses of II, which is known not to overflow, by the corresponding plain binary operation a...
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 hasLimitWitness(const ConstraintInfo &Info, Value *Op, const APInt &Slack, bool Signed, bool Upper)
Returns true if Op <= MaxVal - Slack holds in the system for Signed, by scanning it for a row of the ...
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 Instruction * findCommonDominatorOfUses(Instruction &I, DominatorTree &DT)
Returns the closest program point dominating all uses of I.
static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
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,...
static Decomposition decomposeGEP(GEPOperator &GEP, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
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 std::optional< bool > getKnownSign(Value *Op, const SimplifyQuery &SQ)
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
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
This file defines the PointerIntPair class.
static StringRef getName(Value *V)
SmallVector< MachineOperand, 4 > 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
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
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:509
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.
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
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
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 makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:44
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)
unsigned size() const
Returns the number of rows in the constraint system.
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.
static LLVM_ABI void normalizeByGCD(MutableArrayRef< Entry > R)
Divide the variable coefficients of R by their greatest common divisor G and round the constant down ...
LLVM_ABI bool isConditionImpliedInSubSystem(ArrayRef< Entry > R) const
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)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
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:2987
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.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
size_type size() const
Definition MapVector.h:59
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.
PointerIntPair - This class implements a pair of a pointer and small integer.
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 * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
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
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
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:548
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:715
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:556
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
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
#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:83
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.
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.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
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.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
Exact_match< T > m_Exact(const T &SubPattern)
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.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
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.
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)
@ 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:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
@ Known
Known to have no common set bits.
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:2224
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
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:703
const ScalarOptions & getScalarOptions(const LLVMContext &C)
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:1762
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:740
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI bool isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ 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:1933
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:2035
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:1788
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:2208
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:777
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 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:881
#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:344