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