LLVM 22.0.0git
ConstraintElimination.cpp
Go to the documentation of this file.
1//===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Eliminate conditions based on constraints collected from dominating
10// conditions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DebugInfo.h"
28#include "llvm/IR/Dominators.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Module.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/Pass.h"
38#include "llvm/Support/Debug.h"
43
44#include <optional>
45#include <string>
46
47using namespace llvm;
48using namespace PatternMatch;
49
50#define DEBUG_TYPE "constraint-elimination"
51
52STATISTIC(NumCondsRemoved, "Number of instructions removed");
53DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
54 "Controls which conditions are eliminated");
55
57 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
58 cl::desc("Maximum number of rows to keep in constraint system"));
59
61 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
62 cl::desc("Dump IR to reproduce successful transformations."));
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
74namespace {
75/// Struct to express a condition of the form %Op0 Pred %Op1.
76struct ConditionTy {
77 CmpPredicate Pred;
78 Value *Op0 = nullptr;
79 Value *Op1 = nullptr;
80
81 ConditionTy() = default;
82 ConditionTy(CmpPredicate Pred, Value *Op0, Value *Op1)
83 : Pred(Pred), Op0(Op0), Op1(Op1) {}
84};
85
86/// Represents either
87/// * a condition that holds on entry to a block (=condition fact)
88/// * an assume (=assume fact)
89/// * a use of a compare instruction to simplify.
90/// It also tracks the Dominator DFS in and out numbers for each entry.
91struct FactOrCheck {
92 enum class EntryTy {
93 ConditionFact, /// A condition that holds on entry to a block.
94 InstFact, /// A fact that holds after Inst executed (e.g. an assume or
95 /// min/mix intrinsic.
96 InstCheck, /// An instruction to simplify (e.g. an overflow math
97 /// intrinsics).
98 UseCheck /// An use of a compare instruction to simplify.
99 };
100
101 union {
102 Instruction *Inst;
103 Use *U;
105 };
106
107 /// A pre-condition that must hold for the current fact to be added to the
108 /// system.
109 ConditionTy DoesHold;
110
111 unsigned NumIn;
112 unsigned NumOut;
113 EntryTy Ty;
114
115 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
116 : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
117 Ty(Ty) {}
118
119 FactOrCheck(DomTreeNode *DTN, Use *U)
120 : U(U), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
121 Ty(EntryTy::UseCheck) {}
122
123 FactOrCheck(DomTreeNode *DTN, CmpPredicate Pred, Value *Op0, Value *Op1,
124 ConditionTy Precond = {})
125 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
126 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
127
128 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpPredicate Pred,
129 Value *Op0, Value *Op1,
130 ConditionTy Precond = {}) {
131 return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
132 }
133
134 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
135 return FactOrCheck(EntryTy::InstFact, DTN, Inst);
136 }
137
138 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
139 return FactOrCheck(DTN, U);
140 }
141
142 static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
143 return FactOrCheck(EntryTy::InstCheck, DTN, CI);
144 }
145
146 bool isCheck() const {
147 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
148 }
149
150 Instruction *getContextInst() const {
151 assert(!isConditionFact());
152 if (Ty == EntryTy::UseCheck)
153 return getContextInstForUse(*U);
154 return Inst;
155 }
156
157 Instruction *getInstructionToSimplify() const {
158 assert(isCheck());
159 if (Ty == EntryTy::InstCheck)
160 return Inst;
161 // The use may have been simplified to a constant already.
162 return dyn_cast<Instruction>(*U);
163 }
164
165 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
166};
167
168/// Keep state required to build worklist.
169struct State {
170 DominatorTree &DT;
171 LoopInfo &LI;
172 ScalarEvolution &SE;
174
175 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
176 : DT(DT), LI(LI), SE(SE) {}
177
178 /// Process block \p BB and add known facts to work-list.
179 void addInfoFor(BasicBlock &BB);
180
181 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
182 /// controlling the loop header.
183 void addInfoForInductions(BasicBlock &BB);
184
185 /// Returns true if we can add a known condition from BB to its successor
186 /// block Succ.
187 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
188 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
189 }
190};
191
192class ConstraintInfo;
193
194struct StackEntry {
195 unsigned NumIn;
196 unsigned NumOut;
197 bool IsSigned = false;
198 /// Variables that can be removed from the system once the stack entry gets
199 /// removed.
200 SmallVector<Value *, 2> ValuesToRelease;
201
202 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
203 SmallVector<Value *, 2> ValuesToRelease)
204 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
205 ValuesToRelease(std::move(ValuesToRelease)) {}
206};
207
208struct ConstraintTy {
209 SmallVector<int64_t, 8> Coefficients;
210 SmallVector<ConditionTy, 2> Preconditions;
211
213
214 bool IsSigned = false;
215
216 ConstraintTy() = default;
217
218 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
219 bool IsNe)
220 : Coefficients(std::move(Coefficients)), IsSigned(IsSigned), IsEq(IsEq),
221 IsNe(IsNe) {}
222
223 unsigned size() const { return Coefficients.size(); }
224
225 unsigned empty() const { return Coefficients.empty(); }
226
227 /// Returns true if all preconditions for this list of constraints are
228 /// satisfied given \p Info.
229 bool isValid(const ConstraintInfo &Info) const;
230
231 bool isEq() const { return IsEq; }
232
233 bool isNe() const { return IsNe; }
234
235 /// Check if the current constraint is implied by the given ConstraintSystem.
236 ///
237 /// \return true or false if the constraint is proven to be respectively true,
238 /// or false. When the constraint cannot be proven to be either true or false,
239 /// std::nullopt is returned.
240 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
241
242private:
243 bool IsEq = false;
244 bool IsNe = false;
245};
246
247/// Wrapper encapsulating separate constraint systems and corresponding value
248/// mappings for both unsigned and signed information. Facts are added to and
249/// conditions are checked against the corresponding system depending on the
250/// signed-ness of their predicates. While the information is kept separate
251/// based on signed-ness, certain conditions can be transferred between the two
252/// systems.
253class ConstraintInfo {
254
255 ConstraintSystem UnsignedCS;
256 ConstraintSystem SignedCS;
257
258 const DataLayout &DL;
259
260public:
261 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
262 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
263 auto &Value2Index = getValue2Index(false);
264 // Add Arg > -1 constraints to unsigned system for all function arguments.
265 for (Value *Arg : FunctionArgs) {
266 ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
267 false, false, false);
268 VarPos.Coefficients[Value2Index[Arg]] = -1;
269 UnsignedCS.addVariableRow(VarPos.Coefficients);
270 }
271 }
272
273 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
274 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
275 }
276 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
277 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
278 }
279
280 ConstraintSystem &getCS(bool Signed) {
281 return Signed ? SignedCS : UnsignedCS;
282 }
283 const ConstraintSystem &getCS(bool Signed) const {
284 return Signed ? SignedCS : UnsignedCS;
285 }
286
287 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
288 void popLastNVariables(bool Signed, unsigned N) {
289 getCS(Signed).popLastNVariables(N);
290 }
291
292 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
293
294 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
295 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
296
297 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
298 /// constraints, using indices from the corresponding constraint system.
299 /// New variables that need to be added to the system are collected in
300 /// \p NewVariables.
301 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
302 SmallVectorImpl<Value *> &NewVariables,
303 bool ForceSignedSystem = false) const;
304
305 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
306 /// constraints using getConstraint. Returns an empty constraint if the result
307 /// cannot be used to query the existing constraint system, e.g. because it
308 /// would require adding new variables. Also tries to convert signed
309 /// predicates to unsigned ones if possible to allow using the unsigned system
310 /// which increases the effectiveness of the signed <-> unsigned transfer
311 /// logic.
312 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
313 Value *Op1) const;
314
315 /// Try to add information from \p A \p Pred \p B to the unsigned/signed
316 /// system if \p Pred is signed/unsigned.
317 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
318 unsigned NumIn, unsigned NumOut,
319 SmallVectorImpl<StackEntry> &DFSInStack);
320
321private:
322 /// Adds facts into constraint system. \p ForceSignedSystem can be set when
323 /// the \p Pred is eq/ne, and signed constraint system is used when it's
324 /// specified.
325 void addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
326 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack,
327 bool ForceSignedSystem);
328};
329
330/// Represents a (Coefficient * Variable) entry after IR decomposition.
331struct DecompEntry {
332 int64_t Coefficient;
333 Value *Variable;
334 /// True if the variable is known positive in the current constraint.
335 bool IsKnownNonNegative;
336
337 DecompEntry(int64_t Coefficient, Value *Variable,
338 bool IsKnownNonNegative = false)
339 : Coefficient(Coefficient), Variable(Variable),
340 IsKnownNonNegative(IsKnownNonNegative) {}
341};
342
343/// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
344struct Decomposition {
345 int64_t Offset = 0;
347
348 Decomposition(int64_t Offset) : Offset(Offset) {}
349 Decomposition(Value *V, bool IsKnownNonNegative = false) {
350 Vars.emplace_back(1, V, IsKnownNonNegative);
351 }
352 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
353 : Offset(Offset), Vars(Vars) {}
354
355 /// Add \p OtherOffset and return true if the operation overflows, i.e. the
356 /// new decomposition is invalid.
357 [[nodiscard]] bool add(int64_t OtherOffset) {
358 return AddOverflow(Offset, OtherOffset, Offset);
359 }
360
361 /// Add \p Other and return true if the operation overflows, i.e. the new
362 /// decomposition is invalid.
363 [[nodiscard]] bool add(const Decomposition &Other) {
364 if (add(Other.Offset))
365 return true;
366 append_range(Vars, Other.Vars);
367 return false;
368 }
369
370 /// Subtract \p Other and return true if the operation overflows, i.e. the new
371 /// decomposition is invalid.
372 [[nodiscard]] bool sub(const Decomposition &Other) {
373 Decomposition Tmp = Other;
374 if (Tmp.mul(-1))
375 return true;
376 if (add(Tmp.Offset))
377 return true;
378 append_range(Vars, Tmp.Vars);
379 return false;
380 }
381
382 /// Multiply all coefficients by \p Factor and return true if the operation
383 /// overflows, i.e. the new decomposition is invalid.
384 [[nodiscard]] bool mul(int64_t Factor) {
385 if (MulOverflow(Offset, Factor, Offset))
386 return true;
387 for (auto &Var : Vars)
388 if (MulOverflow(Var.Coefficient, Factor, Var.Coefficient))
389 return true;
390 return false;
391 }
392};
393
394// Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
395struct OffsetResult {
396 Value *BasePtr;
397 APInt ConstantOffset;
398 SmallMapVector<Value *, APInt, 4> VariableOffsets;
400
401 OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
402
404 : BasePtr(GEP.getPointerOperand()), NW(GEP.getNoWrapFlags()) {
405 ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
406 }
407};
408} // namespace
409
410// Try to collect variable and constant offsets for \p GEP, partly traversing
411// nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
412// the offset fails.
414 OffsetResult Result(GEP, DL);
415 unsigned BitWidth = Result.ConstantOffset.getBitWidth();
416 if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
417 Result.ConstantOffset))
418 return {};
419
420 // If we have a nested GEP, check if we can combine the constant offset of the
421 // inner GEP with the outer GEP.
422 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
423 SmallMapVector<Value *, APInt, 4> VariableOffsets2;
424 APInt ConstantOffset2(BitWidth, 0);
425 bool CanCollectInner = InnerGEP->collectOffset(
426 DL, BitWidth, VariableOffsets2, ConstantOffset2);
427 // TODO: Support cases with more than 1 variable offset.
428 if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
429 VariableOffsets2.size() > 1 ||
430 (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
431 // More than 1 variable index, use outer result.
432 return Result;
433 }
434 Result.BasePtr = InnerGEP->getPointerOperand();
435 Result.ConstantOffset += ConstantOffset2;
436 if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
437 Result.VariableOffsets = VariableOffsets2;
438 Result.NW &= InnerGEP->getNoWrapFlags();
439 }
440 return Result;
441}
442
443static Decomposition decompose(Value *V,
444 SmallVectorImpl<ConditionTy> &Preconditions,
445 bool IsSigned, const DataLayout &DL);
446
447static bool canUseSExt(ConstantInt *CI) {
448 const APInt &Val = CI->getValue();
450}
451
452static Decomposition decomposeGEP(GEPOperator &GEP,
453 SmallVectorImpl<ConditionTy> &Preconditions,
454 bool IsSigned, const DataLayout &DL) {
455 // Do not reason about pointers where the index size is larger than 64 bits,
456 // as the coefficients used to encode constraints are 64 bit integers.
457 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
458 return &GEP;
459
460 assert(!IsSigned && "The logic below only supports decomposition for "
461 "unsigned predicates at the moment.");
462 const auto &[BasePtr, ConstantOffset, VariableOffsets, NW] =
464 // We support either plain gep nuw, or gep nusw with non-negative offset,
465 // which implies gep nuw.
466 if (!BasePtr || NW == GEPNoWrapFlags::none())
467 return &GEP;
468
469 Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
470 for (auto [Index, Scale] : VariableOffsets) {
471 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
472 if (IdxResult.mul(Scale.getSExtValue()))
473 return &GEP;
474 if (Result.add(IdxResult))
475 return &GEP;
476
477 if (!NW.hasNoUnsignedWrap()) {
478 // Try to prove nuw from nusw and nneg.
479 assert(NW.hasNoUnsignedSignedWrap() && "Must have nusw flag");
480 if (!isKnownNonNegative(Index, DL))
481 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
482 ConstantInt::get(Index->getType(), 0));
483 }
484 }
485 return Result;
486}
487
488// Decomposes \p V into a constant offset + list of pairs { Coefficient,
489// Variable } where Coefficient * Variable. The sum of the constant offset and
490// pairs equals \p V.
491static Decomposition decompose(Value *V,
492 SmallVectorImpl<ConditionTy> &Preconditions,
493 bool IsSigned, const DataLayout &DL) {
494
495 auto MergeResults = [&Preconditions, IsSigned,
496 &DL](Value *A, Value *B,
497 bool IsSignedB) -> std::optional<Decomposition> {
498 auto ResA = decompose(A, Preconditions, IsSigned, DL);
499 auto ResB = decompose(B, Preconditions, IsSignedB, DL);
500 if (ResA.add(ResB))
501 return std::nullopt;
502 return ResA;
503 };
504
505 Type *Ty = V->getType()->getScalarType();
506 if (Ty->isPointerTy() && !IsSigned) {
507 if (auto *GEP = dyn_cast<GEPOperator>(V))
508 return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
509 if (isa<ConstantPointerNull>(V))
510 return int64_t(0);
511
512 return V;
513 }
514
515 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
516 // coefficient add/mul may wrap, while the operation in the full bit width
517 // would not.
518 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
519 return V;
520
521 bool IsKnownNonNegative = false;
522
523 // Decompose \p V used with a signed predicate.
524 if (IsSigned) {
525 if (auto *CI = dyn_cast<ConstantInt>(V)) {
526 if (canUseSExt(CI))
527 return CI->getSExtValue();
528 }
529 Value *Op0;
530 Value *Op1;
531
532 if (match(V, m_SExt(m_Value(Op0))))
533 V = Op0;
534 else if (match(V, m_NNegZExt(m_Value(Op0)))) {
535 V = Op0;
536 IsKnownNonNegative = true;
537 } else if (match(V, m_NSWTrunc(m_Value(Op0)))) {
538 if (Op0->getType()->getScalarSizeInBits() <= 64)
539 V = Op0;
540 }
541
542 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
543 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
544 return *Decomp;
545 return {V, IsKnownNonNegative};
546 }
547
548 if (match(V, m_NSWSub(m_Value(Op0), m_Value(Op1)))) {
549 auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
550 auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
551 if (!ResA.sub(ResB))
552 return ResA;
553 return {V, IsKnownNonNegative};
554 }
555
556 ConstantInt *CI;
557 if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
558 auto Result = decompose(Op0, Preconditions, IsSigned, DL);
559 if (!Result.mul(CI->getSExtValue()))
560 return Result;
561 return {V, IsKnownNonNegative};
562 }
563
564 // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
565 // shift == bw-1.
566 if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) {
567 uint64_t Shift = CI->getValue().getLimitedValue();
568 if (Shift < Ty->getIntegerBitWidth() - 1) {
569 assert(Shift < 64 && "Would overflow");
570 auto Result = decompose(Op0, Preconditions, IsSigned, DL);
571 if (!Result.mul(int64_t(1) << Shift))
572 return Result;
573 return {V, IsKnownNonNegative};
574 }
575 }
576
577 return {V, IsKnownNonNegative};
578 }
579
580 if (auto *CI = dyn_cast<ConstantInt>(V)) {
581 if (CI->uge(MaxConstraintValue))
582 return V;
583 return int64_t(CI->getZExtValue());
584 }
585
586 Value *Op0;
587 if (match(V, m_ZExt(m_Value(Op0)))) {
588 IsKnownNonNegative = true;
589 V = Op0;
590 } else if (match(V, m_SExt(m_Value(Op0)))) {
591 V = Op0;
592 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
593 ConstantInt::get(Op0->getType(), 0));
594 } else if (auto *Trunc = dyn_cast<TruncInst>(V)) {
595 if (Trunc->getSrcTy()->getScalarSizeInBits() <= 64) {
596 if (Trunc->hasNoUnsignedWrap() || Trunc->hasNoSignedWrap()) {
597 V = Trunc->getOperand(0);
598 if (!Trunc->hasNoUnsignedWrap())
599 Preconditions.emplace_back(CmpInst::ICMP_SGE, V,
600 ConstantInt::get(V->getType(), 0));
601 }
602 }
603 }
604
605 Value *Op1;
606 ConstantInt *CI;
607 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
608 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
609 return *Decomp;
610 return {V, IsKnownNonNegative};
611 }
612
613 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
614 if (!isKnownNonNegative(Op0, DL))
615 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
616 ConstantInt::get(Op0->getType(), 0));
617 if (!isKnownNonNegative(Op1, DL))
618 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
619 ConstantInt::get(Op1->getType(), 0));
620
621 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
622 return *Decomp;
623 return {V, IsKnownNonNegative};
624 }
625
626 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
627 canUseSExt(CI)) {
628 Preconditions.emplace_back(
630 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
631 if (auto Decomp = MergeResults(Op0, CI, true))
632 return *Decomp;
633 return {V, IsKnownNonNegative};
634 }
635
636 // Decompose or as an add if there are no common bits between the operands.
637 if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI)))) {
638 if (auto Decomp = MergeResults(Op0, CI, IsSigned))
639 return *Decomp;
640 return {V, IsKnownNonNegative};
641 }
642
643 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
644 if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
645 return {V, IsKnownNonNegative};
646 auto Result = decompose(Op1, Preconditions, IsSigned, DL);
647 if (!Result.mul(int64_t{1} << CI->getSExtValue()))
648 return Result;
649 return {V, IsKnownNonNegative};
650 }
651
652 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
653 (!CI->isNegative())) {
654 auto Result = decompose(Op1, Preconditions, IsSigned, DL);
655 if (!Result.mul(CI->getSExtValue()))
656 return Result;
657 return {V, IsKnownNonNegative};
658 }
659
660 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
661 auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
662 auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
663 if (!ResA.sub(ResB))
664 return ResA;
665 return {V, IsKnownNonNegative};
666 }
667
668 return {V, IsKnownNonNegative};
669}
670
671ConstraintTy
672ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
673 SmallVectorImpl<Value *> &NewVariables,
674 bool ForceSignedSystem) const {
675 assert(NewVariables.empty() && "NewVariables must be empty when passed in");
676 assert((!ForceSignedSystem || CmpInst::isEquality(Pred)) &&
677 "signed system can only be forced on eq/ne");
678
679 bool IsEq = false;
680 bool IsNe = false;
681
682 // Try to convert Pred to one of ULE/ULT/SLE/SLT.
683 switch (Pred) {
687 case CmpInst::ICMP_SGE: {
688 Pred = CmpInst::getSwappedPredicate(Pred);
689 std::swap(Op0, Op1);
690 break;
691 }
692 case CmpInst::ICMP_EQ:
693 if (!ForceSignedSystem && match(Op1, m_Zero())) {
694 Pred = CmpInst::ICMP_ULE;
695 } else {
696 IsEq = true;
697 Pred = CmpInst::ICMP_ULE;
698 }
699 break;
700 case CmpInst::ICMP_NE:
701 if (!ForceSignedSystem && match(Op1, m_Zero())) {
703 std::swap(Op0, Op1);
704 } else {
705 IsNe = true;
706 Pred = CmpInst::ICMP_ULE;
707 }
708 break;
709 default:
710 break;
711 }
712
713 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
714 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
715 return {};
716
717 SmallVector<ConditionTy, 4> Preconditions;
718 bool IsSigned = ForceSignedSystem || CmpInst::isSigned(Pred);
719 auto &Value2Index = getValue2Index(IsSigned);
721 Preconditions, IsSigned, DL);
723 Preconditions, IsSigned, DL);
724 int64_t Offset1 = ADec.Offset;
725 int64_t Offset2 = BDec.Offset;
726 Offset1 *= -1;
727
728 auto &VariablesA = ADec.Vars;
729 auto &VariablesB = BDec.Vars;
730
731 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
732 // new entry to NewVariables.
734 auto GetOrAddIndex = [&Value2Index, &NewVariables,
735 &NewIndexMap](Value *V) -> unsigned {
736 auto V2I = Value2Index.find(V);
737 if (V2I != Value2Index.end())
738 return V2I->second;
739 auto Insert =
740 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
741 if (Insert.second)
742 NewVariables.push_back(V);
743 return Insert.first->second;
744 };
745
746 // Make sure all variables have entries in Value2Index or NewVariables.
747 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
748 GetOrAddIndex(KV.Variable);
749
750 // Build result constraint, by first adding all coefficients from A and then
751 // subtracting all coefficients from B.
752 ConstraintTy Res(
753 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
754 IsSigned, IsEq, IsNe);
755 // Collect variables that are known to be positive in all uses in the
756 // constraint.
757 SmallDenseMap<Value *, bool> KnownNonNegativeVariables;
758 auto &R = Res.Coefficients;
759 for (const auto &KV : VariablesA) {
760 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
761 auto I =
762 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
763 I.first->second &= KV.IsKnownNonNegative;
764 }
765
766 for (const auto &KV : VariablesB) {
767 auto &Coeff = R[GetOrAddIndex(KV.Variable)];
768 if (SubOverflow(Coeff, KV.Coefficient, Coeff))
769 return {};
770 auto I =
771 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
772 I.first->second &= KV.IsKnownNonNegative;
773 }
774
775 int64_t OffsetSum;
776 if (AddOverflow(Offset1, Offset2, OffsetSum))
777 return {};
778 if (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT)
779 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
780 return {};
781 R[0] = OffsetSum;
782 Res.Preconditions = std::move(Preconditions);
783
784 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
785 // variables.
786 while (!NewVariables.empty()) {
787 int64_t Last = R.back();
788 if (Last != 0)
789 break;
790 R.pop_back();
791 Value *RemovedV = NewVariables.pop_back_val();
792 NewIndexMap.erase(RemovedV);
793 }
794
795 // Add extra constraints for variables that are known positive.
796 for (auto &KV : KnownNonNegativeVariables) {
797 if (!KV.second ||
798 (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
799 continue;
800 auto &C = Res.ExtraInfo.emplace_back(
801 Value2Index.size() + NewVariables.size() + 1, 0);
802 C[GetOrAddIndex(KV.first)] = -1;
803 }
804 return Res;
805}
806
807ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
808 Value *Op0,
809 Value *Op1) const {
810 Constant *NullC = Constant::getNullValue(Op0->getType());
811 // Handle trivially true compares directly to avoid adding V UGE 0 constraints
812 // for all variables in the unsigned system.
813 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
814 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
815 auto &Value2Index = getValue2Index(false);
816 // Return constraint that's trivially true.
817 return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
818 false, false);
819 }
820
821 // If both operands are known to be non-negative, change signed predicates to
822 // unsigned ones. This increases the reasoning effectiveness in combination
823 // with the signed <-> unsigned transfer logic.
824 if (CmpInst::isSigned(Pred) &&
825 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
828
829 SmallVector<Value *> NewVariables;
830 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
831 if (!NewVariables.empty())
832 return {};
833 return R;
834}
835
836bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
837 return Coefficients.size() > 0 &&
838 all_of(Preconditions, [&Info](const ConditionTy &C) {
839 return Info.doesHold(C.Pred, C.Op0, C.Op1);
840 });
841}
842
843std::optional<bool>
844ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
845 bool IsConditionImplied = CS.isConditionImplied(Coefficients);
846
847 if (IsEq || IsNe) {
848 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
849 bool IsNegatedOrEqualImplied =
850 !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
851
852 // In order to check that `%a == %b` is true (equality), both conditions `%a
853 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
854 // is true), we return true if they both hold, false in the other cases.
855 if (IsConditionImplied && IsNegatedOrEqualImplied)
856 return IsEq;
857
858 auto Negated = ConstraintSystem::negate(Coefficients);
859 bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
860
861 auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
862 bool IsStrictLessThanImplied =
863 !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
864
865 // In order to check that `%a != %b` is true (non-equality), either
866 // condition `%a > %b` or `%a < %b` must hold true. When checking for
867 // non-equality (`IsNe` is true), we return true if one of the two holds,
868 // false in the other cases.
869 if (IsNegatedImplied || IsStrictLessThanImplied)
870 return IsNe;
871
872 return std::nullopt;
873 }
874
875 if (IsConditionImplied)
876 return true;
877
878 auto Negated = ConstraintSystem::negate(Coefficients);
879 auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
880 if (IsNegatedImplied)
881 return false;
882
883 // Neither the condition nor its negated holds, did not prove anything.
884 return std::nullopt;
885}
886
887bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
888 Value *B) const {
889 auto R = getConstraintForSolving(Pred, A, B);
890 return R.isValid(*this) &&
891 getCS(R.IsSigned).isConditionImplied(R.Coefficients);
892}
893
894void ConstraintInfo::transferToOtherSystem(
895 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
896 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
897 auto IsKnownNonNegative = [this](Value *V) {
898 return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
900 };
901 // Check if we can combine facts from the signed and unsigned systems to
902 // derive additional facts.
903 if (!A->getType()->isIntegerTy())
904 return;
905 // FIXME: This currently depends on the order we add facts. Ideally we
906 // would first add all known facts and only then try to add additional
907 // facts.
908 switch (Pred) {
909 default:
910 break;
913 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
914 if (IsKnownNonNegative(B)) {
915 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
916 NumOut, DFSInStack);
917 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
918 DFSInStack);
919 }
920 break;
923 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
924 if (IsKnownNonNegative(A)) {
925 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
926 NumOut, DFSInStack);
927 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
928 DFSInStack);
929 }
930 break;
932 if (IsKnownNonNegative(A))
933 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
934 break;
935 case CmpInst::ICMP_SGT: {
936 if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
937 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
938 NumOut, DFSInStack);
939 if (IsKnownNonNegative(B))
940 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
941
942 break;
943 }
945 if (IsKnownNonNegative(B))
946 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
947 break;
948 }
949}
950
951#ifndef NDEBUG
952
954 const DenseMap<Value *, unsigned> &Value2Index) {
955 ConstraintSystem CS(Value2Index);
957 CS.dump();
958}
959#endif
960
961void State::addInfoForInductions(BasicBlock &BB) {
962 auto *L = LI.getLoopFor(&BB);
963 if (!L || L->getHeader() != &BB)
964 return;
965
966 Value *A;
967 Value *B;
968 CmpPredicate Pred;
969
970 if (!match(BB.getTerminator(),
971 m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
972 return;
973 PHINode *PN = dyn_cast<PHINode>(A);
974 if (!PN) {
975 Pred = CmpInst::getSwappedPredicate(Pred);
976 std::swap(A, B);
977 PN = dyn_cast<PHINode>(A);
978 }
979
980 if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
981 !SE.isSCEVable(PN->getType()))
982 return;
983
984 BasicBlock *InLoopSucc = nullptr;
985 if (Pred == CmpInst::ICMP_NE)
986 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
987 else if (Pred == CmpInst::ICMP_EQ)
988 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
989 else
990 return;
991
992 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
993 return;
994
995 auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
996 BasicBlock *LoopPred = L->getLoopPredecessor();
997 if (!AR || AR->getLoop() != L || !LoopPred)
998 return;
999
1000 const SCEV *StartSCEV = AR->getStart();
1001 Value *StartValue = nullptr;
1002 if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
1003 StartValue = C->getValue();
1004 } else {
1005 StartValue = PN->getIncomingValueForBlock(LoopPred);
1006 assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
1007 }
1008
1009 DomTreeNode *DTN = DT.getNode(InLoopSucc);
1010 auto IncUnsigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
1011 auto IncSigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_SGT);
1012 bool MonotonicallyIncreasingUnsigned =
1014 bool MonotonicallyIncreasingSigned =
1016 // If SCEV guarantees that AR does not wrap, PN >= StartValue can be added
1017 // unconditionally.
1018 if (MonotonicallyIncreasingUnsigned)
1019 WorkList.push_back(
1020 FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
1021 if (MonotonicallyIncreasingSigned)
1022 WorkList.push_back(
1023 FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGE, PN, StartValue));
1024
1025 APInt StepOffset;
1026 if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
1027 StepOffset = C->getAPInt();
1028 else
1029 return;
1030
1031 // Make sure the bound B is loop-invariant.
1032 if (!L->isLoopInvariant(B))
1033 return;
1034
1035 // Handle negative steps.
1036 if (StepOffset.isNegative()) {
1037 // TODO: Extend to allow steps > -1.
1038 if (!(-StepOffset).isOne())
1039 return;
1040
1041 // AR may wrap.
1042 // Add StartValue >= PN conditional on B <= StartValue which guarantees that
1043 // the loop exits before wrapping with a step of -1.
1044 WorkList.push_back(FactOrCheck::getConditionFact(
1045 DTN, CmpInst::ICMP_UGE, StartValue, PN,
1046 ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
1047 WorkList.push_back(FactOrCheck::getConditionFact(
1048 DTN, CmpInst::ICMP_SGE, StartValue, PN,
1049 ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
1050 // Add PN > B conditional on B <= StartValue which guarantees that the loop
1051 // exits when reaching B with a step of -1.
1052 WorkList.push_back(FactOrCheck::getConditionFact(
1053 DTN, CmpInst::ICMP_UGT, PN, B,
1054 ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
1055 WorkList.push_back(FactOrCheck::getConditionFact(
1056 DTN, CmpInst::ICMP_SGT, PN, B,
1057 ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
1058 return;
1059 }
1060
1061 // Make sure AR either steps by 1 or that the value we compare against is a
1062 // GEP based on the same start value and all offsets are a multiple of the
1063 // step size, to guarantee that the induction will reach the value.
1064 if (StepOffset.isZero() || StepOffset.isNegative())
1065 return;
1066
1067 if (!StepOffset.isOne()) {
1068 // Check whether B-Start is known to be a multiple of StepOffset.
1069 const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV);
1070 if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1071 !SE.getConstantMultiple(BMinusStart).urem(StepOffset).isZero())
1072 return;
1073 }
1074
1075 // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
1076 // guarantees that the loop exits before wrapping in combination with the
1077 // restrictions on B and the step above.
1078 if (!MonotonicallyIncreasingUnsigned)
1079 WorkList.push_back(FactOrCheck::getConditionFact(
1080 DTN, CmpInst::ICMP_UGE, PN, StartValue,
1081 ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1082 if (!MonotonicallyIncreasingSigned)
1083 WorkList.push_back(FactOrCheck::getConditionFact(
1084 DTN, CmpInst::ICMP_SGE, PN, StartValue,
1085 ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1086
1087 WorkList.push_back(FactOrCheck::getConditionFact(
1088 DTN, CmpInst::ICMP_ULT, PN, B,
1089 ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1090 WorkList.push_back(FactOrCheck::getConditionFact(
1091 DTN, CmpInst::ICMP_SLT, PN, B,
1092 ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1093
1094 // Try to add condition from header to the dedicated exit blocks. When exiting
1095 // either with EQ or NE in the header, we know that the induction value must
1096 // be u<= B, as other exits may only exit earlier.
1097 assert(!StepOffset.isNegative() && "induction must be increasing");
1098 assert((Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) &&
1099 "unsupported predicate");
1100 ConditionTy Precond = {CmpInst::ICMP_ULE, StartValue, B};
1102 L->getExitBlocks(ExitBBs);
1103 for (BasicBlock *EB : ExitBBs) {
1104 // Bail out on non-dedicated exits.
1105 if (DT.dominates(&BB, EB)) {
1106 WorkList.emplace_back(FactOrCheck::getConditionFact(
1107 DT.getNode(EB), CmpInst::ICMP_ULE, A, B, Precond));
1108 }
1109 }
1110}
1111
1112void State::addInfoFor(BasicBlock &BB) {
1113 addInfoForInductions(BB);
1114
1115 // True as long as long as the current instruction is guaranteed to execute.
1116 bool GuaranteedToExecute = true;
1117 // Queue conditions and assumes.
1118 for (Instruction &I : BB) {
1119 if (auto *Cmp = dyn_cast<ICmpInst>(&I)) {
1120 for (Use &U : Cmp->uses()) {
1121 auto *UserI = getContextInstForUse(U);
1122 auto *DTN = DT.getNode(UserI->getParent());
1123 if (!DTN)
1124 continue;
1125 WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1126 }
1127 continue;
1128 }
1129
1130 auto *II = dyn_cast<IntrinsicInst>(&I);
1131 Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1132 switch (ID) {
1133 case Intrinsic::assume: {
1134 Value *A, *B;
1135 CmpPredicate Pred;
1136 if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1137 break;
1138 if (GuaranteedToExecute) {
1139 // The assume is guaranteed to execute when BB is entered, hence Cond
1140 // holds on entry to BB.
1141 WorkList.emplace_back(FactOrCheck::getConditionFact(
1142 DT.getNode(I.getParent()), Pred, A, B));
1143 } else {
1144 WorkList.emplace_back(
1145 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1146 }
1147 break;
1148 }
1149 // Enqueue ssub_with_overflow for simplification.
1150 case Intrinsic::ssub_with_overflow:
1151 case Intrinsic::ucmp:
1152 case Intrinsic::scmp:
1153 WorkList.push_back(
1154 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1155 break;
1156 // Enqueue the intrinsics to add extra info.
1157 case Intrinsic::umin:
1158 case Intrinsic::umax:
1159 case Intrinsic::smin:
1160 case Intrinsic::smax:
1161 // TODO: handle llvm.abs as well
1162 WorkList.push_back(
1163 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1164 [[fallthrough]];
1165 case Intrinsic::uadd_sat:
1166 case Intrinsic::usub_sat:
1167 // TODO: Check if it is possible to instead only added the min/max facts
1168 // when simplifying uses of the min/max intrinsics.
1170 break;
1171 [[fallthrough]];
1172 case Intrinsic::abs:
1173 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1174 break;
1175 }
1176
1177 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1178 }
1179
1180 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1181 for (auto &Case : Switch->cases()) {
1182 BasicBlock *Succ = Case.getCaseSuccessor();
1183 Value *V = Case.getCaseValue();
1184 if (!canAddSuccessor(BB, Succ))
1185 continue;
1186 WorkList.emplace_back(FactOrCheck::getConditionFact(
1187 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1188 }
1189 return;
1190 }
1191
1192 auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1193 if (!Br || !Br->isConditional())
1194 return;
1195
1196 Value *Cond = Br->getCondition();
1197
1198 // If the condition is a chain of ORs/AND and the successor only has the
1199 // current block as predecessor, queue conditions for the successor.
1200 Value *Op0, *Op1;
1201 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1202 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1203 bool IsOr = match(Cond, m_LogicalOr());
1204 bool IsAnd = match(Cond, m_LogicalAnd());
1205 // If there's a select that matches both AND and OR, we need to commit to
1206 // one of the options. Arbitrarily pick OR.
1207 if (IsOr && IsAnd)
1208 IsAnd = false;
1209
1210 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1211 if (canAddSuccessor(BB, Successor)) {
1212 SmallVector<Value *> CondWorkList;
1213 SmallPtrSet<Value *, 8> SeenCond;
1214 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1215 if (SeenCond.insert(V).second)
1216 CondWorkList.push_back(V);
1217 };
1218 QueueValue(Op1);
1219 QueueValue(Op0);
1220 while (!CondWorkList.empty()) {
1221 Value *Cur = CondWorkList.pop_back_val();
1222 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1223 WorkList.emplace_back(FactOrCheck::getConditionFact(
1224 DT.getNode(Successor),
1225 IsOr ? Cmp->getInverseCmpPredicate() : Cmp->getCmpPredicate(),
1226 Cmp->getOperand(0), Cmp->getOperand(1)));
1227 continue;
1228 }
1229 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1230 QueueValue(Op1);
1231 QueueValue(Op0);
1232 continue;
1233 }
1234 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1235 QueueValue(Op1);
1236 QueueValue(Op0);
1237 continue;
1238 }
1239 }
1240 }
1241 return;
1242 }
1243
1244 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1245 if (!CmpI)
1246 return;
1247 if (canAddSuccessor(BB, Br->getSuccessor(0)))
1248 WorkList.emplace_back(FactOrCheck::getConditionFact(
1249 DT.getNode(Br->getSuccessor(0)), CmpI->getCmpPredicate(),
1250 CmpI->getOperand(0), CmpI->getOperand(1)));
1251 if (canAddSuccessor(BB, Br->getSuccessor(1)))
1252 WorkList.emplace_back(FactOrCheck::getConditionFact(
1253 DT.getNode(Br->getSuccessor(1)), CmpI->getInverseCmpPredicate(),
1254 CmpI->getOperand(0), CmpI->getOperand(1)));
1255}
1256
1257#ifndef NDEBUG
1259 Value *LHS, Value *RHS) {
1260 OS << "icmp " << Pred << ' ';
1261 LHS->printAsOperand(OS, /*PrintType=*/true);
1262 OS << ", ";
1263 RHS->printAsOperand(OS, /*PrintType=*/false);
1264}
1265#endif
1266
1267namespace {
1268/// Helper to keep track of a condition and if it should be treated as negated
1269/// for reproducer construction.
1270/// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1271/// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1272struct ReproducerEntry {
1274 Value *LHS;
1275 Value *RHS;
1276
1277 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1278 : Pred(Pred), LHS(LHS), RHS(RHS) {}
1279};
1280} // namespace
1281
1282/// Helper function to generate a reproducer function for simplifying \p Cond.
1283/// The reproducer function contains a series of @llvm.assume calls, one for
1284/// each condition in \p Stack. For each condition, the operand instruction are
1285/// cloned until we reach operands that have an entry in \p Value2Index. Those
1286/// will then be added as function arguments. \p DT is used to order cloned
1287/// instructions. The reproducer function will get added to \p M, if it is
1288/// non-null. Otherwise no reproducer function is generated.
1291 ConstraintInfo &Info, DominatorTree &DT) {
1292 if (!M)
1293 return;
1294
1295 LLVMContext &Ctx = Cond->getContext();
1296
1297 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1298
1299 ValueToValueMapTy Old2New;
1302 // Traverse Cond and its operands recursively until we reach a value that's in
1303 // Value2Index or not an instruction, or not a operation that
1304 // ConstraintElimination can decompose. Such values will be considered as
1305 // external inputs to the reproducer, they are collected and added as function
1306 // arguments later.
1307 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1308 auto &Value2Index = Info.getValue2Index(IsSigned);
1309 SmallVector<Value *, 4> WorkList(Ops);
1310 while (!WorkList.empty()) {
1311 Value *V = WorkList.pop_back_val();
1312 if (!Seen.insert(V).second)
1313 continue;
1314 if (Old2New.find(V) != Old2New.end())
1315 continue;
1316 if (isa<Constant>(V))
1317 continue;
1318
1319 auto *I = dyn_cast<Instruction>(V);
1320 if (Value2Index.contains(V) || !I ||
1321 !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1322 Old2New[V] = V;
1323 Args.push_back(V);
1324 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n");
1325 } else {
1326 append_range(WorkList, I->operands());
1327 }
1328 }
1329 };
1330
1331 for (auto &Entry : Stack)
1332 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1333 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1334 CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1335
1336 SmallVector<Type *> ParamTys;
1337 for (auto *P : Args)
1338 ParamTys.push_back(P->getType());
1339
1340 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1341 /*isVarArg=*/false);
1342 Function *F = Function::Create(FTy, Function::ExternalLinkage,
1343 Cond->getModule()->getName() +
1344 Cond->getFunction()->getName() + "repro",
1345 M);
1346 // Add arguments to the reproducer function for each external value collected.
1347 for (unsigned I = 0; I < Args.size(); ++I) {
1348 F->getArg(I)->setName(Args[I]->getName());
1349 Old2New[Args[I]] = F->getArg(I);
1350 }
1351
1352 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1353 IRBuilder<> Builder(Entry);
1354 Builder.CreateRet(Builder.getTrue());
1355 Builder.SetInsertPoint(Entry->getTerminator());
1356
1357 // Clone instructions in \p Ops and their operands recursively until reaching
1358 // an value in Value2Index (external input to the reproducer). Update Old2New
1359 // mapping for the original and cloned instructions. Sort instructions to
1360 // clone by dominance, then insert the cloned instructions in the function.
1361 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1362 SmallVector<Value *, 4> WorkList(Ops);
1364 auto &Value2Index = Info.getValue2Index(IsSigned);
1365 while (!WorkList.empty()) {
1366 Value *V = WorkList.pop_back_val();
1367 if (Old2New.find(V) != Old2New.end())
1368 continue;
1369
1370 auto *I = dyn_cast<Instruction>(V);
1371 if (!Value2Index.contains(V) && I) {
1372 Old2New[V] = nullptr;
1373 ToClone.push_back(I);
1374 append_range(WorkList, I->operands());
1375 }
1376 }
1377
1378 sort(ToClone,
1379 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1380 for (Instruction *I : ToClone) {
1381 Instruction *Cloned = I->clone();
1382 Old2New[I] = Cloned;
1383 Old2New[I]->setName(I->getName());
1384 Cloned->insertBefore(Builder.GetInsertPoint());
1386 Cloned->setDebugLoc({});
1387 }
1388 };
1389
1390 // Materialize the assumptions for the reproducer using the entries in Stack.
1391 // That is, first clone the operands of the condition recursively until we
1392 // reach an external input to the reproducer and add them to the reproducer
1393 // function. Then add an ICmp for the condition (with the inverse predicate if
1394 // the entry is negated) and an assert using the ICmp.
1395 for (auto &Entry : Stack) {
1396 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1397 continue;
1398
1399 LLVM_DEBUG(dbgs() << " Materializing assumption ";
1400 dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
1401 dbgs() << "\n");
1402 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1403
1404 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1405 Builder.CreateAssumption(Cmp);
1406 }
1407
1408 // Finally, clone the condition to reproduce and remap instruction operands in
1409 // the reproducer using Old2New.
1410 CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1411 Entry->getTerminator()->setOperand(0, Cond);
1412 remapInstructionsInBlocks({Entry}, Old2New);
1413
1414 assert(!verifyFunction(*F, &dbgs()));
1415}
1416
1417static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
1418 Value *B, Instruction *CheckInst,
1419 ConstraintInfo &Info) {
1420 LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1421
1422 auto R = Info.getConstraintForSolving(Pred, A, B);
1423 if (R.empty() || !R.isValid(Info)){
1424 LLVM_DEBUG(dbgs() << " failed to decompose condition\n");
1425 return std::nullopt;
1426 }
1427
1428 auto &CSToUse = Info.getCS(R.IsSigned);
1429
1430 // If there was extra information collected during decomposition, apply
1431 // it now and remove it immediately once we are done with reasoning
1432 // about the constraint.
1433 for (auto &Row : R.ExtraInfo)
1434 CSToUse.addVariableRow(Row);
1435 auto InfoRestorer = make_scope_exit([&]() {
1436 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1437 CSToUse.popLastConstraint();
1438 });
1439
1440 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1441 if (!DebugCounter::shouldExecute(EliminatedCounter))
1442 return std::nullopt;
1443
1444 LLVM_DEBUG({
1445 dbgs() << "Condition ";
1447 dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
1448 A, B);
1449 dbgs() << " implied by dominating constraints\n";
1450 CSToUse.dump();
1451 });
1452 return ImpliedCondition;
1453 }
1454
1455 return std::nullopt;
1456}
1457
1459 ICmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1460 Instruction *ContextInst, Module *ReproducerModule,
1461 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1463 auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1464 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1465 Constant *ConstantC = ConstantInt::getBool(
1466 CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1467 bool Changed = false;
1468 Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut, ContextInst,
1469 &Changed](Use &U) {
1470 auto *UserI = getContextInstForUse(U);
1471 auto *DTN = DT.getNode(UserI->getParent());
1472 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1473 return false;
1474 if (UserI->getParent() == ContextInst->getParent() &&
1475 UserI->comesBefore(ContextInst))
1476 return false;
1477
1478 // Conditions in an assume trivially simplify to true. Skip uses
1479 // in assume calls to not destroy the available information.
1480 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1481 bool ShouldReplace = !II || II->getIntrinsicID() != Intrinsic::assume;
1482 Changed |= ShouldReplace;
1483 return ShouldReplace;
1484 });
1485 NumCondsRemoved++;
1486
1487 // Update the debug value records that satisfy the same condition used
1488 // in replaceUsesWithIf.
1490 findDbgUsers(Cmp, DVRUsers);
1491
1492 for (auto *DVR : DVRUsers) {
1493 auto *DTN = DT.getNode(DVR->getParent());
1494 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1495 continue;
1496
1497 auto *MarkedI = DVR->getInstruction();
1498 if (MarkedI->getParent() == ContextInst->getParent() &&
1499 MarkedI->comesBefore(ContextInst))
1500 continue;
1501
1502 DVR->replaceVariableLocationOp(Cmp, ConstantC);
1503 }
1504
1505 if (Cmp->use_empty())
1506 ToRemove.push_back(Cmp);
1507
1508 return Changed;
1509 };
1510
1511 if (auto ImpliedCondition =
1512 checkCondition(Cmp->getPredicate(), Cmp->getOperand(0),
1513 Cmp->getOperand(1), Cmp, Info))
1514 return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1515
1516 // When the predicate is samesign and unsigned, we can also make use of the
1517 // signed predicate information.
1518 if (Cmp->hasSameSign() && Cmp->isUnsigned())
1519 if (auto ImpliedCondition =
1520 checkCondition(Cmp->getSignedPredicate(), Cmp->getOperand(0),
1521 Cmp->getOperand(1), Cmp, Info))
1522 return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1523
1524 return false;
1525}
1526
1527static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
1529 auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
1530 // TODO: generate reproducer for min/max.
1531 MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
1532 ToRemove.push_back(MinMax);
1533 return true;
1534 };
1535
1536 ICmpInst::Predicate Pred =
1537 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1538 if (auto ImpliedCondition = checkCondition(
1539 Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
1540 return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
1541 if (auto ImpliedCondition = checkCondition(
1542 Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
1543 return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
1544 return false;
1545}
1546
1547static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
1549 Value *LHS = I->getOperand(0);
1550 Value *RHS = I->getOperand(1);
1551 if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1552 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
1553 ToRemove.push_back(I);
1554 return true;
1555 }
1556 if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1557 I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
1558 ToRemove.push_back(I);
1559 return true;
1560 }
1561 if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
1562 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
1563 ToRemove.push_back(I);
1564 return true;
1565 }
1566 return false;
1567}
1568
1569static void
1570removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1571 Module *ReproducerModule,
1572 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1573 SmallVectorImpl<StackEntry> &DFSInStack) {
1574 Info.popLastConstraint(E.IsSigned);
1575 // Remove variables in the system that went out of scope.
1576 auto &Mapping = Info.getValue2Index(E.IsSigned);
1577 for (Value *V : E.ValuesToRelease)
1578 Mapping.erase(V);
1579 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1580 DFSInStack.pop_back();
1581 if (ReproducerModule)
1582 ReproducerCondStack.pop_back();
1583}
1584
1585/// Check if either the first condition of an AND or OR is implied by the
1586/// (negated in case of OR) second condition or vice versa.
1588 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1589 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1590 SmallVectorImpl<StackEntry> &DFSInStack,
1592 Instruction *JoinOp = CB.getContextInst();
1593 if (JoinOp->use_empty())
1594 return false;
1595
1596 CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify());
1597 unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
1598
1599 // Don't try to simplify the first condition of a select by the second, as
1600 // this may make the select more poisonous than the original one.
1601 // TODO: check if the first operand may be poison.
1602 if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
1603 return false;
1604
1605 unsigned OldSize = DFSInStack.size();
1606 auto InfoRestorer = make_scope_exit([&]() {
1607 // Remove entries again.
1608 while (OldSize < DFSInStack.size()) {
1609 StackEntry E = DFSInStack.back();
1610 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1611 DFSInStack);
1612 }
1613 });
1614 bool IsOr = match(JoinOp, m_LogicalOr());
1615 SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
1616 // Do a traversal of the AND/OR tree to add facts from leaf compares.
1617 while (!Worklist.empty()) {
1618 Value *Val = Worklist.pop_back_val();
1619 Value *LHS, *RHS;
1620 CmpPredicate Pred;
1621 if (match(Val, m_ICmp(Pred, m_Value(LHS), m_Value(RHS)))) {
1622 // For OR, check if the negated condition implies CmpToCheck.
1623 if (IsOr)
1624 Pred = CmpInst::getInversePredicate(Pred);
1625 // Optimistically add fact from the other compares in the AND/OR.
1626 Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
1627 continue;
1628 }
1629 if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
1630 : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
1631 Worklist.push_back(LHS);
1632 Worklist.push_back(RHS);
1633 }
1634 }
1635 if (OldSize == DFSInStack.size())
1636 return false;
1637
1638 // Check if the second condition can be simplified now.
1639 if (auto ImpliedCondition =
1640 checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
1641 CmpToCheck->getOperand(1), CmpToCheck, Info)) {
1642 if (IsOr == *ImpliedCondition)
1643 JoinOp->replaceAllUsesWith(
1644 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1645 else
1646 JoinOp->replaceAllUsesWith(JoinOp->getOperand(OtherOpIdx));
1647 ToRemove.push_back(JoinOp);
1648 return true;
1649 }
1650
1651 return false;
1652}
1653
1654void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1655 unsigned NumIn, unsigned NumOut,
1656 SmallVectorImpl<StackEntry> &DFSInStack) {
1657 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, false);
1658 // If the Pred is eq/ne, also add the fact to signed system.
1659 if (CmpInst::isEquality(Pred))
1660 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, true);
1661}
1662
1663void ConstraintInfo::addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B,
1664 unsigned NumIn, unsigned NumOut,
1665 SmallVectorImpl<StackEntry> &DFSInStack,
1666 bool ForceSignedSystem) {
1667 // If the constraint has a pre-condition, skip the constraint if it does not
1668 // hold.
1669 SmallVector<Value *> NewVariables;
1670 auto R = getConstraint(Pred, A, B, NewVariables, ForceSignedSystem);
1671
1672 // TODO: Support non-equality for facts as well.
1673 if (!R.isValid(*this) || R.isNe())
1674 return;
1675
1676 LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
1677 dbgs() << "'\n");
1678 auto &CSToUse = getCS(R.IsSigned);
1679 if (R.Coefficients.empty())
1680 return;
1681
1682 bool Added = CSToUse.addVariableRowFill(R.Coefficients);
1683 if (!Added)
1684 return;
1685
1686 // If R has been added to the system, add the new variables and queue it for
1687 // removal once it goes out-of-scope.
1688 SmallVector<Value *, 2> ValuesToRelease;
1689 auto &Value2Index = getValue2Index(R.IsSigned);
1690 for (Value *V : NewVariables) {
1691 Value2Index.insert({V, Value2Index.size() + 1});
1692 ValuesToRelease.push_back(V);
1693 }
1694
1695 LLVM_DEBUG({
1696 dbgs() << " constraint: ";
1697 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1698 dbgs() << "\n";
1699 });
1700
1701 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1702 std::move(ValuesToRelease));
1703
1704 if (!R.IsSigned) {
1705 for (Value *V : NewVariables) {
1706 ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1707 false, false, false);
1708 VarPos.Coefficients[Value2Index[V]] = -1;
1709 CSToUse.addVariableRow(VarPos.Coefficients);
1710 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1712 }
1713 }
1714
1715 if (R.isEq()) {
1716 // Also add the inverted constraint for equality constraints.
1717 for (auto &Coeff : R.Coefficients)
1718 Coeff *= -1;
1719 CSToUse.addVariableRowFill(R.Coefficients);
1720
1721 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1723 }
1724}
1725
1728 bool Changed = false;
1729 IRBuilder<> Builder(II->getParent(), II->getIterator());
1730 Value *Sub = nullptr;
1731 for (User *U : make_early_inc_range(II->users())) {
1732 if (match(U, m_ExtractValue<0>(m_Value()))) {
1733 if (!Sub)
1734 Sub = Builder.CreateSub(A, B);
1735 U->replaceAllUsesWith(Sub);
1736 Changed = true;
1737 } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1738 U->replaceAllUsesWith(Builder.getFalse());
1739 Changed = true;
1740 } else
1741 continue;
1742
1743 if (U->use_empty()) {
1744 auto *I = cast<Instruction>(U);
1745 ToRemove.push_back(I);
1746 I->setOperand(0, PoisonValue::get(II->getType()));
1747 Changed = true;
1748 }
1749 }
1750
1751 if (II->use_empty()) {
1752 II->eraseFromParent();
1753 Changed = true;
1754 }
1755 return Changed;
1756}
1757
1758static bool
1761 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1762 ConstraintInfo &Info) {
1763 auto R = Info.getConstraintForSolving(Pred, A, B);
1764 if (R.size() < 2 || !R.isValid(Info))
1765 return false;
1766
1767 auto &CSToUse = Info.getCS(R.IsSigned);
1768 return CSToUse.isConditionImplied(R.Coefficients);
1769 };
1770
1771 bool Changed = false;
1772 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1773 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1774 // can be simplified to a regular sub.
1775 Value *A = II->getArgOperand(0);
1776 Value *B = II->getArgOperand(1);
1777 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1778 !DoesConditionHold(CmpInst::ICMP_SGE, B,
1779 ConstantInt::get(A->getType(), 0), Info))
1780 return false;
1781 Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1782 }
1783 return Changed;
1784}
1785
1787 ScalarEvolution &SE,
1789 bool Changed = false;
1790 DT.updateDFSNumbers();
1791 SmallVector<Value *> FunctionArgs(llvm::make_pointer_range(F.args()));
1792 ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
1793 State S(DT, LI, SE);
1794 std::unique_ptr<Module> ReproducerModule(
1795 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1796
1797 // First, collect conditions implied by branches and blocks with their
1798 // Dominator DFS in and out numbers.
1799 for (BasicBlock &BB : F) {
1800 if (!DT.getNode(&BB))
1801 continue;
1802 S.addInfoFor(BB);
1803 }
1804
1805 // Next, sort worklist by dominance, so that dominating conditions to check
1806 // and facts come before conditions and facts dominated by them. If a
1807 // condition to check and a fact have the same numbers, conditional facts come
1808 // first. Assume facts and checks are ordered according to their relative
1809 // order in the containing basic block. Also make sure conditions with
1810 // constant operands come before conditions without constant operands. This
1811 // increases the effectiveness of the current signed <-> unsigned fact
1812 // transfer logic.
1813 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1814 auto HasNoConstOp = [](const FactOrCheck &B) {
1815 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1816 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1817 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1818 };
1819 // If both entries have the same In numbers, conditional facts come first.
1820 // Otherwise use the relative order in the basic block.
1821 if (A.NumIn == B.NumIn) {
1822 if (A.isConditionFact() && B.isConditionFact()) {
1823 bool NoConstOpA = HasNoConstOp(A);
1824 bool NoConstOpB = HasNoConstOp(B);
1825 return NoConstOpA < NoConstOpB;
1826 }
1827 if (A.isConditionFact())
1828 return true;
1829 if (B.isConditionFact())
1830 return false;
1831 auto *InstA = A.getContextInst();
1832 auto *InstB = B.getContextInst();
1833 return InstA->comesBefore(InstB);
1834 }
1835 return A.NumIn < B.NumIn;
1836 });
1837
1839
1840 // Finally, process ordered worklist and eliminate implied conditions.
1841 SmallVector<StackEntry, 16> DFSInStack;
1842 SmallVector<ReproducerEntry> ReproducerCondStack;
1843 for (FactOrCheck &CB : S.WorkList) {
1844 // First, pop entries from the stack that are out-of-scope for CB. Remove
1845 // the corresponding entry from the constraint system.
1846 while (!DFSInStack.empty()) {
1847 auto &E = DFSInStack.back();
1848 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1849 << "\n");
1850 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1851 assert(E.NumIn <= CB.NumIn);
1852 if (CB.NumOut <= E.NumOut)
1853 break;
1854 LLVM_DEBUG({
1855 dbgs() << "Removing ";
1856 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1857 Info.getValue2Index(E.IsSigned));
1858 dbgs() << "\n";
1859 });
1860 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1861 DFSInStack);
1862 }
1863
1864 // For a block, check if any CmpInsts become known based on the current set
1865 // of constraints.
1866 if (CB.isCheck()) {
1867 Instruction *Inst = CB.getInstructionToSimplify();
1868 if (!Inst)
1869 continue;
1870 LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
1871 << "\n");
1872 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1873 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1874 } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1876 Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1877 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1878 if (!Simplified &&
1879 match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
1881 CB, Info, ReproducerModule.get(), ReproducerCondStack, DFSInStack,
1882 ToRemove);
1883 }
1884 Changed |= Simplified;
1885 } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
1886 Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
1887 } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
1888 Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
1889 }
1890 continue;
1891 }
1892
1893 auto AddFact = [&](CmpPredicate Pred, Value *A, Value *B) {
1894 LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
1895 dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1896 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1897 LLVM_DEBUG(
1898 dbgs()
1899 << "Skip adding constraint because system has too many rows.\n");
1900 return;
1901 }
1902
1903 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1904 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1905 ReproducerCondStack.emplace_back(Pred, A, B);
1906
1907 if (ICmpInst::isRelational(Pred)) {
1908 // If samesign is present on the ICmp, simply flip the sign of the
1909 // predicate, transferring the information from the signed system to the
1910 // unsigned system, and viceversa.
1911 if (Pred.hasSameSign())
1913 CB.NumIn, CB.NumOut, DFSInStack);
1914 else
1915 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut,
1916 DFSInStack);
1917 }
1918
1919 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1920 // Add dummy entries to ReproducerCondStack to keep it in sync with
1921 // DFSInStack.
1922 for (unsigned I = 0,
1923 E = (DFSInStack.size() - ReproducerCondStack.size());
1924 I < E; ++I) {
1925 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1926 nullptr, nullptr);
1927 }
1928 }
1929 };
1930
1931 CmpPredicate Pred;
1932 if (!CB.isConditionFact()) {
1933 Value *X;
1934 if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1935 // If is_int_min_poison is true then we may assume llvm.abs >= 0.
1936 if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
1937 AddFact(CmpInst::ICMP_SGE, CB.Inst,
1938 ConstantInt::get(CB.Inst->getType(), 0));
1939 AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1940 continue;
1941 }
1942
1943 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1944 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1945 AddFact(Pred, MinMax, MinMax->getLHS());
1946 AddFact(Pred, MinMax, MinMax->getRHS());
1947 continue;
1948 }
1949 if (auto *USatI = dyn_cast<SaturatingInst>(CB.Inst)) {
1950 switch (USatI->getIntrinsicID()) {
1951 default:
1952 llvm_unreachable("Unexpected intrinsic.");
1953 case Intrinsic::uadd_sat:
1954 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getLHS());
1955 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getRHS());
1956 break;
1957 case Intrinsic::usub_sat:
1958 AddFact(ICmpInst::ICMP_ULE, USatI, USatI->getLHS());
1959 break;
1960 }
1961 continue;
1962 }
1963 }
1964
1965 Value *A = nullptr, *B = nullptr;
1966 if (CB.isConditionFact()) {
1967 Pred = CB.Cond.Pred;
1968 A = CB.Cond.Op0;
1969 B = CB.Cond.Op1;
1970 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1971 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
1972 LLVM_DEBUG({
1973 dbgs() << "Not adding fact ";
1974 dumpUnpackedICmp(dbgs(), Pred, A, B);
1975 dbgs() << " because precondition ";
1976 dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
1977 CB.DoesHold.Op1);
1978 dbgs() << " does not hold.\n";
1979 });
1980 continue;
1981 }
1982 } else {
1983 bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1984 m_ICmp(Pred, m_Value(A), m_Value(B))));
1985 (void)Matched;
1986 assert(Matched && "Must have an assume intrinsic with a icmp operand");
1987 }
1988 AddFact(Pred, A, B);
1989 }
1990
1991 if (ReproducerModule && !ReproducerModule->functions().empty()) {
1992 std::string S;
1993 raw_string_ostream StringS(S);
1994 ReproducerModule->print(StringS, nullptr);
1995 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1996 Rem << ore::NV("module") << S;
1997 ORE.emit(Rem);
1998 }
1999
2000#ifndef NDEBUG
2001 unsigned SignedEntries =
2002 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
2003 assert(Info.getCS(false).size() - FunctionArgs.size() ==
2004 DFSInStack.size() - SignedEntries &&
2005 "updates to CS and DFSInStack are out of sync");
2006 assert(Info.getCS(true).size() == SignedEntries &&
2007 "updates to CS and DFSInStack are out of sync");
2008#endif
2009
2010 for (Instruction *I : ToRemove)
2011 I->eraseFromParent();
2012 return Changed;
2013}
2014
2017 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2018 auto &LI = AM.getResult<LoopAnalysis>(F);
2019 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
2021 if (!eliminateConstraints(F, DT, LI, SE, ORE))
2022 return PreservedAnalyses::all();
2023
2026 PA.preserve<LoopAnalysis>();
2029 return PA;
2030}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
std::pair< ICmpInst *, unsigned > ConditionTy
static int64_t MaxConstraintValue
static int64_t MinSignedConstraintValue
static Instruction * getContextInstForUse(Use &U)
static Decomposition decomposeGEP(GEPOperator &GEP, SmallVectorImpl< ConditionTy > &Preconditions, bool IsSigned, const DataLayout &DL)
static bool canUseSExt(ConstantInt *CI)
static void dumpConstraint(ArrayRef< int64_t > C, const DenseMap< Value *, unsigned > &Value2Index)
static void removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack)
static std::optional< bool > checkCondition(CmpInst::Predicate Pred, Value *A, Value *B, Instruction *CheckInst, ConstraintInfo &Info)
static cl::opt< unsigned > MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, cl::desc("Maximum number of rows to keep in constraint system"))
static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, OptimizationRemarkEmitter &ORE)
static cl::opt< bool > DumpReproducers("constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, cl::desc("Dump IR to reproduce successful transformations."))
static bool checkOrAndOpImpliedByOther(FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack, SmallVectorImpl< Instruction * > &ToRemove)
Check if either the first condition of an AND or OR is implied by the (negated in case of OR) second ...
static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL)
static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static void generateReproducer(CmpInst *Cond, Module *M, ArrayRef< ReproducerEntry > Stack, ConstraintInfo &Info, DominatorTree &DT)
Helper function to generate a reproducer function for simplifying Cond.
static bool checkAndReplaceCondition(ICmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, Instruction *ContextInst, Module *ReproducerModule, ArrayRef< ReproducerEntry > ReproducerCondStack, DominatorTree &DT, SmallVectorImpl< Instruction * > &ToRemove)
static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
static Decomposition decompose(Value *V, SmallVectorImpl< ConditionTy > &Preconditions, bool IsSigned, const DataLayout &DL)
static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, SmallVectorImpl< Instruction * > &ToRemove)
static bool tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
#define DEBUG_TYPE
static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:194
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
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:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1201
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:380
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1666
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:329
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:475
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1130
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:389
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:206
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:233
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:666
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:984
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition: InstrTypes.h:917
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:707
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:708
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:702
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:701
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:705
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:703
@ ICMP_EQ
equal
Definition: InstrTypes.h:699
@ ICMP_NE
not equal
Definition: InstrTypes.h:700
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:706
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:704
bool isSigned() const
Definition: InstrTypes.h:932
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:829
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:791
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:767
This class represents a ucmp/scmp intrinsic.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Definition: CmpPredicate.h:23
bool hasSameSign() const
Query samesign information, for optimizations.
Definition: CmpPredicate.h:43
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
bool isNegative() const
Definition: Constants.h:209
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:131
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:169
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:154
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:882
This is an important base class in LLVM.
Definition: Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:420
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
DenseMap< Value *, unsigned > & getValue2Index()
static SmallVector< int64_t, 8 > negate(SmallVector< int64_t, 8 > R)
LLVM_ABI bool isConditionImplied(SmallVector< int64_t, 8 > R) const
static SmallVector< int64_t, 8 > toStrictLessThan(SmallVector< int64_t, 8 > R)
Converts the given vector to form a strict less than inequality.
bool addVariableRow(ArrayRef< int64_t > R)
static SmallVector< int64_t, 8 > negateOrEqual(SmallVector< int64_t, 8 > R)
Multiplies each coefficient in the given vector by -1.
bool addVariableRowFill(ArrayRef< int64_t > R)
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(unsigned CounterName)
Definition: DebugCounter.h:88
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
bool erase(const KeyT &Val)
Definition: DenseMap.h:319
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:168
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
unsigned getDFSNumOut() const
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:284
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:165
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.
Definition: Dominators.cpp:135
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:166
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
This instruction compares its operands according to the predicate given to the constructor.
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.
LLVM_ABI CallInst * CreateAssumption(Value *Cond, ArrayRef< OperandBundleDef > OpBundles={})
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Definition: IRBuilder.cpp:463
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:502
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:202
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:1172
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1420
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:507
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:207
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2439
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1673
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:510
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:49
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:570
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
size_type size() const
Definition: MapVector.h:56
This class represents min/max intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
The optimization diagnostic interface.
Diagnostic information for applied optimization remarks.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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.
Definition: Constants.cpp:1885
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
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI APInt getConstantMultiple(const SCEV *S)
Returns the max constant multiple of S.
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.
LLVM_ABI const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
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.
Definition: SmallPtrSet.h:401
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:267
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:240
LLVM_ABI unsigned getIntegerBitWidth() const
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
Value * getOperand(unsigned i) const
Definition: User.h:232
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:256
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:5305
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:709
bool use_empty() const
Definition: Value.h:346
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
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, 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.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:612
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::enable_if_t< std::is_signed_v< T >, T > MulOverflow(T X, T Y, T &Result)
Multiply two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:758
void stable_sort(R &&Range)
Definition: STLExtras.h:2077
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:1744
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7502
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
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:663
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:47
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
@ Sub
Subtraction of integers.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:223
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:1886
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:1980
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition: iterator.h:363
std::enable_if_t< std::is_signed_v< T >, T > AddOverflow(T X, T Y, T &Result)
Add two signed integers, computing the two's complement truncated result, returning true if overflow ...
Definition: MathExtras.h:706
std::enable_if_t< std::is_signed_v< T >, T > SubOverflow(T X, T Y, T &Result)
Subtract two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:732
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.
Definition: DebugInfo.cpp:129
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:858
#define N
A MapVector that performs no allocations if smaller than a certain size.
Definition: MapVector.h:249