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