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/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/GetElementPtrTypeIterator.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/PatternMatch.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/DebugCounter.h" 35 #include "llvm/Support/KnownBits.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Transforms/Utils/Cloning.h" 38 #include "llvm/Transforms/Utils/ValueMapper.h" 39 40 #include <cmath> 41 #include <optional> 42 #include <string> 43 44 using namespace llvm; 45 using namespace PatternMatch; 46 47 #define DEBUG_TYPE "constraint-elimination" 48 49 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 50 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 51 "Controls which conditions are eliminated"); 52 53 static cl::opt<unsigned> 54 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, 55 cl::desc("Maximum number of rows to keep in constraint system")); 56 57 static cl::opt<bool> DumpReproducers( 58 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, 59 cl::desc("Dump IR to reproduce successful transformations.")); 60 61 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 62 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 63 64 // A helper to multiply 2 signed integers where overflowing is allowed. 65 static int64_t multiplyWithOverflow(int64_t A, int64_t B) { 66 int64_t Result; 67 MulOverflow(A, B, Result); 68 return Result; 69 } 70 71 // A helper to add 2 signed integers where overflowing is allowed. 72 static int64_t addWithOverflow(int64_t A, int64_t B) { 73 int64_t Result; 74 AddOverflow(A, B, Result); 75 return Result; 76 } 77 78 static Instruction *getContextInstForUse(Use &U) { 79 Instruction *UserI = cast<Instruction>(U.getUser()); 80 if (auto *Phi = dyn_cast<PHINode>(UserI)) 81 UserI = Phi->getIncomingBlock(U)->getTerminator(); 82 return UserI; 83 } 84 85 namespace { 86 /// Struct to express a condition of the form %Op0 Pred %Op1. 87 struct ConditionTy { 88 CmpInst::Predicate Pred; 89 Value *Op0; 90 Value *Op1; 91 92 ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 93 : Pred(Pred), Op0(Op0), Op1(Op1) {} 94 }; 95 96 /// Represents either 97 /// * a condition that holds on entry to a block (=condition fact) 98 /// * an assume (=assume fact) 99 /// * a use of a compare instruction to simplify. 100 /// It also tracks the Dominator DFS in and out numbers for each entry. 101 struct FactOrCheck { 102 enum class EntryTy { 103 ConditionFact, /// A condition that holds on entry to a block. 104 InstFact, /// A fact that holds after Inst executed (e.g. an assume or 105 /// min/mix intrinsic. 106 InstCheck, /// An instruction to simplify (e.g. an overflow math 107 /// intrinsics). 108 UseCheck /// An use of a compare instruction to simplify. 109 }; 110 111 union { 112 Instruction *Inst; 113 Use *U; 114 ConditionTy Cond; 115 }; 116 117 unsigned NumIn; 118 unsigned NumOut; 119 EntryTy Ty; 120 121 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst) 122 : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 123 Ty(Ty) {} 124 125 FactOrCheck(DomTreeNode *DTN, Use *U) 126 : U(U), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 127 Ty(EntryTy::UseCheck) {} 128 129 FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1) 130 : Cond(Pred, Op0, Op1), NumIn(DTN->getDFSNumIn()), 131 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {} 132 133 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred, 134 Value *Op0, Value *Op1) { 135 return FactOrCheck(DTN, Pred, Op0, Op1); 136 } 137 138 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) { 139 return FactOrCheck(EntryTy::InstFact, DTN, Inst); 140 } 141 142 static FactOrCheck getFact(DomTreeNode *DTN, CmpInst::Predicate Pred, 143 Value *Op0, Value *Op1) { 144 return FactOrCheck(DTN, Pred, Op0, Op1); 145 } 146 147 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) { 148 return FactOrCheck(DTN, U); 149 } 150 151 static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) { 152 return FactOrCheck(EntryTy::InstCheck, DTN, CI); 153 } 154 155 bool isCheck() const { 156 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck; 157 } 158 159 Instruction *getContextInst() const { 160 if (Ty == EntryTy::UseCheck) 161 return getContextInstForUse(*U); 162 return Inst; 163 } 164 165 Instruction *getInstructionToSimplify() const { 166 assert(isCheck()); 167 if (Ty == EntryTy::InstCheck) 168 return Inst; 169 // The use may have been simplified to a constant already. 170 return dyn_cast<Instruction>(*U); 171 } 172 173 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; } 174 }; 175 176 /// Keep state required to build worklist. 177 struct State { 178 DominatorTree &DT; 179 SmallVector<FactOrCheck, 64> WorkList; 180 181 State(DominatorTree &DT) : DT(DT) {} 182 183 /// Process block \p BB and add known facts to work-list. 184 void addInfoFor(BasicBlock &BB); 185 186 /// Returns true if we can add a known condition from BB to its successor 187 /// block Succ. 188 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 189 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ); 190 } 191 }; 192 193 class ConstraintInfo; 194 195 struct StackEntry { 196 unsigned NumIn; 197 unsigned NumOut; 198 bool IsSigned = false; 199 /// Variables that can be removed from the system once the stack entry gets 200 /// removed. 201 SmallVector<Value *, 2> ValuesToRelease; 202 203 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned, 204 SmallVector<Value *, 2> ValuesToRelease) 205 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned), 206 ValuesToRelease(ValuesToRelease) {} 207 }; 208 209 struct ConstraintTy { 210 SmallVector<int64_t, 8> Coefficients; 211 SmallVector<ConditionTy, 2> Preconditions; 212 213 SmallVector<SmallVector<int64_t, 8>> ExtraInfo; 214 215 bool IsSigned = false; 216 217 ConstraintTy() = default; 218 219 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq, 220 bool IsNe) 221 : Coefficients(Coefficients), IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) { 222 } 223 224 unsigned size() const { return Coefficients.size(); } 225 226 unsigned empty() const { return Coefficients.empty(); } 227 228 /// Returns true if all preconditions for this list of constraints are 229 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 230 bool isValid(const ConstraintInfo &Info) const; 231 232 bool isEq() const { return IsEq; } 233 234 bool isNe() const { return IsNe; } 235 236 /// Check if the current constraint is implied by the given ConstraintSystem. 237 /// 238 /// \return true or false if the constraint is proven to be respectively true, 239 /// or false. When the constraint cannot be proven to be either true or false, 240 /// std::nullopt is returned. 241 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const; 242 243 private: 244 bool IsEq = false; 245 bool IsNe = false; 246 }; 247 248 /// Wrapper encapsulating separate constraint systems and corresponding value 249 /// mappings for both unsigned and signed information. Facts are added to and 250 /// conditions are checked against the corresponding system depending on the 251 /// signed-ness of their predicates. While the information is kept separate 252 /// based on signed-ness, certain conditions can be transferred between the two 253 /// systems. 254 class ConstraintInfo { 255 256 ConstraintSystem UnsignedCS; 257 ConstraintSystem SignedCS; 258 259 const DataLayout &DL; 260 261 public: 262 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs) 263 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {} 264 265 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 266 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 267 } 268 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 269 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 270 } 271 272 ConstraintSystem &getCS(bool Signed) { 273 return Signed ? SignedCS : UnsignedCS; 274 } 275 const ConstraintSystem &getCS(bool Signed) const { 276 return Signed ? SignedCS : UnsignedCS; 277 } 278 279 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 280 void popLastNVariables(bool Signed, unsigned N) { 281 getCS(Signed).popLastNVariables(N); 282 } 283 284 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 285 286 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 287 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 288 289 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 290 /// constraints, using indices from the corresponding constraint system. 291 /// New variables that need to be added to the system are collected in 292 /// \p NewVariables. 293 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 294 SmallVectorImpl<Value *> &NewVariables) const; 295 296 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 297 /// constraints using getConstraint. Returns an empty constraint if the result 298 /// cannot be used to query the existing constraint system, e.g. because it 299 /// would require adding new variables. Also tries to convert signed 300 /// predicates to unsigned ones if possible to allow using the unsigned system 301 /// which increases the effectiveness of the signed <-> unsigned transfer 302 /// logic. 303 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0, 304 Value *Op1) const; 305 306 /// Try to add information from \p A \p Pred \p B to the unsigned/signed 307 /// system if \p Pred is signed/unsigned. 308 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B, 309 unsigned NumIn, unsigned NumOut, 310 SmallVectorImpl<StackEntry> &DFSInStack); 311 }; 312 313 /// Represents a (Coefficient * Variable) entry after IR decomposition. 314 struct DecompEntry { 315 int64_t Coefficient; 316 Value *Variable; 317 /// True if the variable is known positive in the current constraint. 318 bool IsKnownNonNegative; 319 320 DecompEntry(int64_t Coefficient, Value *Variable, 321 bool IsKnownNonNegative = false) 322 : Coefficient(Coefficient), Variable(Variable), 323 IsKnownNonNegative(IsKnownNonNegative) {} 324 }; 325 326 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition. 327 struct Decomposition { 328 int64_t Offset = 0; 329 SmallVector<DecompEntry, 3> Vars; 330 331 Decomposition(int64_t Offset) : Offset(Offset) {} 332 Decomposition(Value *V, bool IsKnownNonNegative = false) { 333 Vars.emplace_back(1, V, IsKnownNonNegative); 334 } 335 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars) 336 : Offset(Offset), Vars(Vars) {} 337 338 void add(int64_t OtherOffset) { 339 Offset = addWithOverflow(Offset, OtherOffset); 340 } 341 342 void add(const Decomposition &Other) { 343 add(Other.Offset); 344 append_range(Vars, Other.Vars); 345 } 346 347 void mul(int64_t Factor) { 348 Offset = multiplyWithOverflow(Offset, Factor); 349 for (auto &Var : Vars) 350 Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor); 351 } 352 }; 353 354 } // namespace 355 356 static Decomposition decompose(Value *V, 357 SmallVectorImpl<ConditionTy> &Preconditions, 358 bool IsSigned, const DataLayout &DL); 359 360 static bool canUseSExt(ConstantInt *CI) { 361 const APInt &Val = CI->getValue(); 362 return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 363 } 364 365 static Decomposition decomposeGEP(GEPOperator &GEP, 366 SmallVectorImpl<ConditionTy> &Preconditions, 367 bool IsSigned, const DataLayout &DL) { 368 // Do not reason about pointers where the index size is larger than 64 bits, 369 // as the coefficients used to encode constraints are 64 bit integers. 370 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64) 371 return &GEP; 372 373 if (!GEP.isInBounds()) 374 return &GEP; 375 376 assert(!IsSigned && "The logic below only supports decomposition for " 377 "unsinged predicates at the moment."); 378 Type *PtrTy = GEP.getType()->getScalarType(); 379 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy); 380 MapVector<Value *, APInt> VariableOffsets; 381 APInt ConstantOffset(BitWidth, 0); 382 if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) 383 return &GEP; 384 385 // Handle the (gep (gep ....), C) case by incrementing the constant 386 // coefficient of the inner GEP, if C is a constant. 387 auto *InnerGEP = dyn_cast<GEPOperator>(GEP.getPointerOperand()); 388 if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) { 389 auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL); 390 Result.add(ConstantOffset.getSExtValue()); 391 392 if (ConstantOffset.isNegative()) { 393 unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType()); 394 int64_t ConstantOffsetI = ConstantOffset.getSExtValue(); 395 if (ConstantOffsetI % Scale != 0) 396 return &GEP; 397 // Add pre-condition ensuring the GEP is increasing monotonically and 398 // can be de-composed. 399 // Both sides are normalized by being divided by Scale. 400 Preconditions.emplace_back( 401 CmpInst::ICMP_SGE, InnerGEP->getOperand(1), 402 ConstantInt::get(InnerGEP->getOperand(1)->getType(), 403 -1 * (ConstantOffsetI / Scale))); 404 } 405 return Result; 406 } 407 408 Decomposition Result(ConstantOffset.getSExtValue(), 409 DecompEntry(1, GEP.getPointerOperand())); 410 for (auto [Index, Scale] : VariableOffsets) { 411 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL); 412 IdxResult.mul(Scale.getSExtValue()); 413 Result.add(IdxResult); 414 415 // If Op0 is signed non-negative, the GEP is increasing monotonically and 416 // can be de-composed. 417 if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 418 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index, 419 ConstantInt::get(Index->getType(), 0)); 420 } 421 return Result; 422 } 423 424 // Decomposes \p V into a constant offset + list of pairs { Coefficient, 425 // Variable } where Coefficient * Variable. The sum of the constant offset and 426 // pairs equals \p V. 427 static Decomposition decompose(Value *V, 428 SmallVectorImpl<ConditionTy> &Preconditions, 429 bool IsSigned, const DataLayout &DL) { 430 431 auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B, 432 bool IsSignedB) { 433 auto ResA = decompose(A, Preconditions, IsSigned, DL); 434 auto ResB = decompose(B, Preconditions, IsSignedB, DL); 435 ResA.add(ResB); 436 return ResA; 437 }; 438 439 // Decompose \p V used with a signed predicate. 440 if (IsSigned) { 441 if (auto *CI = dyn_cast<ConstantInt>(V)) { 442 if (canUseSExt(CI)) 443 return CI->getSExtValue(); 444 } 445 Value *Op0; 446 Value *Op1; 447 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) 448 return MergeResults(Op0, Op1, IsSigned); 449 450 ConstantInt *CI; 451 if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) { 452 auto Result = decompose(Op0, Preconditions, IsSigned, DL); 453 Result.mul(CI->getSExtValue()); 454 return Result; 455 } 456 457 return V; 458 } 459 460 if (auto *CI = dyn_cast<ConstantInt>(V)) { 461 if (CI->uge(MaxConstraintValue)) 462 return V; 463 return int64_t(CI->getZExtValue()); 464 } 465 466 if (auto *GEP = dyn_cast<GEPOperator>(V)) 467 return decomposeGEP(*GEP, Preconditions, IsSigned, DL); 468 469 Value *Op0; 470 bool IsKnownNonNegative = false; 471 if (match(V, m_ZExt(m_Value(Op0)))) { 472 IsKnownNonNegative = true; 473 V = Op0; 474 } 475 476 Value *Op1; 477 ConstantInt *CI; 478 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) { 479 return MergeResults(Op0, Op1, IsSigned); 480 } 481 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) { 482 if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 483 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 484 ConstantInt::get(Op0->getType(), 0)); 485 if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 486 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1, 487 ConstantInt::get(Op1->getType(), 0)); 488 489 return MergeResults(Op0, Op1, IsSigned); 490 } 491 492 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 493 canUseSExt(CI)) { 494 Preconditions.emplace_back( 495 CmpInst::ICMP_UGE, Op0, 496 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 497 return MergeResults(Op0, CI, true); 498 } 499 500 // Decompose or as an add if there are no common bits between the operands. 501 if (match(V, m_Or(m_Value(Op0), m_ConstantInt(CI))) && 502 haveNoCommonBitsSet(Op0, CI, DL)) { 503 return MergeResults(Op0, CI, IsSigned); 504 } 505 506 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) { 507 if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64) 508 return {V, IsKnownNonNegative}; 509 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 510 Result.mul(int64_t{1} << CI->getSExtValue()); 511 return Result; 512 } 513 514 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) && 515 (!CI->isNegative())) { 516 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 517 Result.mul(CI->getSExtValue()); 518 return Result; 519 } 520 521 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) 522 return {-1 * CI->getSExtValue(), {{1, Op0}}}; 523 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 524 return {0, {{1, Op0}, {-1, Op1}}}; 525 526 return {V, IsKnownNonNegative}; 527 } 528 529 ConstraintTy 530 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 531 SmallVectorImpl<Value *> &NewVariables) const { 532 assert(NewVariables.empty() && "NewVariables must be empty when passed in"); 533 bool IsEq = false; 534 bool IsNe = false; 535 536 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 537 switch (Pred) { 538 case CmpInst::ICMP_UGT: 539 case CmpInst::ICMP_UGE: 540 case CmpInst::ICMP_SGT: 541 case CmpInst::ICMP_SGE: { 542 Pred = CmpInst::getSwappedPredicate(Pred); 543 std::swap(Op0, Op1); 544 break; 545 } 546 case CmpInst::ICMP_EQ: 547 if (match(Op1, m_Zero())) { 548 Pred = CmpInst::ICMP_ULE; 549 } else { 550 IsEq = true; 551 Pred = CmpInst::ICMP_ULE; 552 } 553 break; 554 case CmpInst::ICMP_NE: 555 if (match(Op1, m_Zero())) { 556 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 557 std::swap(Op0, Op1); 558 } else { 559 IsNe = true; 560 Pred = CmpInst::ICMP_ULE; 561 } 562 break; 563 default: 564 break; 565 } 566 567 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 568 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 569 return {}; 570 571 SmallVector<ConditionTy, 4> Preconditions; 572 bool IsSigned = CmpInst::isSigned(Pred); 573 auto &Value2Index = getValue2Index(IsSigned); 574 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 575 Preconditions, IsSigned, DL); 576 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 577 Preconditions, IsSigned, DL); 578 int64_t Offset1 = ADec.Offset; 579 int64_t Offset2 = BDec.Offset; 580 Offset1 *= -1; 581 582 auto &VariablesA = ADec.Vars; 583 auto &VariablesB = BDec.Vars; 584 585 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a 586 // new entry to NewVariables. 587 DenseMap<Value *, unsigned> NewIndexMap; 588 auto GetOrAddIndex = [&Value2Index, &NewVariables, 589 &NewIndexMap](Value *V) -> unsigned { 590 auto V2I = Value2Index.find(V); 591 if (V2I != Value2Index.end()) 592 return V2I->second; 593 auto Insert = 594 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1}); 595 if (Insert.second) 596 NewVariables.push_back(V); 597 return Insert.first->second; 598 }; 599 600 // Make sure all variables have entries in Value2Index or NewVariables. 601 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB)) 602 GetOrAddIndex(KV.Variable); 603 604 // Build result constraint, by first adding all coefficients from A and then 605 // subtracting all coefficients from B. 606 ConstraintTy Res( 607 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0), 608 IsSigned, IsEq, IsNe); 609 // Collect variables that are known to be positive in all uses in the 610 // constraint. 611 DenseMap<Value *, bool> KnownNonNegativeVariables; 612 auto &R = Res.Coefficients; 613 for (const auto &KV : VariablesA) { 614 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient; 615 auto I = 616 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 617 I.first->second &= KV.IsKnownNonNegative; 618 } 619 620 for (const auto &KV : VariablesB) { 621 if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient, 622 R[GetOrAddIndex(KV.Variable)])) 623 return {}; 624 auto I = 625 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 626 I.first->second &= KV.IsKnownNonNegative; 627 } 628 629 int64_t OffsetSum; 630 if (AddOverflow(Offset1, Offset2, OffsetSum)) 631 return {}; 632 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 633 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 634 return {}; 635 R[0] = OffsetSum; 636 Res.Preconditions = std::move(Preconditions); 637 638 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new 639 // variables. 640 while (!NewVariables.empty()) { 641 int64_t Last = R.back(); 642 if (Last != 0) 643 break; 644 R.pop_back(); 645 Value *RemovedV = NewVariables.pop_back_val(); 646 NewIndexMap.erase(RemovedV); 647 } 648 649 // Add extra constraints for variables that are known positive. 650 for (auto &KV : KnownNonNegativeVariables) { 651 if (!KV.second || 652 (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first))) 653 continue; 654 SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0); 655 C[GetOrAddIndex(KV.first)] = -1; 656 Res.ExtraInfo.push_back(C); 657 } 658 return Res; 659 } 660 661 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred, 662 Value *Op0, 663 Value *Op1) const { 664 // If both operands are known to be non-negative, change signed predicates to 665 // unsigned ones. This increases the reasoning effectiveness in combination 666 // with the signed <-> unsigned transfer logic. 667 if (CmpInst::isSigned(Pred) && 668 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) && 669 isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 670 Pred = CmpInst::getUnsignedPredicate(Pred); 671 672 SmallVector<Value *> NewVariables; 673 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables); 674 if (!NewVariables.empty()) 675 return {}; 676 return R; 677 } 678 679 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 680 return Coefficients.size() > 0 && 681 all_of(Preconditions, [&Info](const ConditionTy &C) { 682 return Info.doesHold(C.Pred, C.Op0, C.Op1); 683 }); 684 } 685 686 std::optional<bool> 687 ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const { 688 bool IsConditionImplied = CS.isConditionImplied(Coefficients); 689 690 if (IsEq || IsNe) { 691 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients); 692 bool IsNegatedOrEqualImplied = 693 !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual); 694 695 // In order to check that `%a == %b` is true (equality), both conditions `%a 696 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq` 697 // is true), we return true if they both hold, false in the other cases. 698 if (IsConditionImplied && IsNegatedOrEqualImplied) 699 return IsEq; 700 701 auto Negated = ConstraintSystem::negate(Coefficients); 702 bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 703 704 auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients); 705 bool IsStrictLessThanImplied = 706 !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan); 707 708 // In order to check that `%a != %b` is true (non-equality), either 709 // condition `%a > %b` or `%a < %b` must hold true. When checking for 710 // non-equality (`IsNe` is true), we return true if one of the two holds, 711 // false in the other cases. 712 if (IsNegatedImplied || IsStrictLessThanImplied) 713 return IsNe; 714 715 return std::nullopt; 716 } 717 718 if (IsConditionImplied) 719 return true; 720 721 auto Negated = ConstraintSystem::negate(Coefficients); 722 auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 723 if (IsNegatedImplied) 724 return false; 725 726 // Neither the condition nor its negated holds, did not prove anything. 727 return std::nullopt; 728 } 729 730 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 731 Value *B) const { 732 auto R = getConstraintForSolving(Pred, A, B); 733 return R.isValid(*this) && 734 getCS(R.IsSigned).isConditionImplied(R.Coefficients); 735 } 736 737 void ConstraintInfo::transferToOtherSystem( 738 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 739 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) { 740 // Check if we can combine facts from the signed and unsigned systems to 741 // derive additional facts. 742 if (!A->getType()->isIntegerTy()) 743 return; 744 // FIXME: This currently depends on the order we add facts. Ideally we 745 // would first add all known facts and only then try to add additional 746 // facts. 747 switch (Pred) { 748 default: 749 break; 750 case CmpInst::ICMP_ULT: 751 // If B is a signed positive constant, A >=s 0 and A <s B. 752 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 753 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn, 754 NumOut, DFSInStack); 755 addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack); 756 } 757 break; 758 case CmpInst::ICMP_SLT: 759 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) 760 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack); 761 break; 762 case CmpInst::ICMP_SGT: { 763 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 764 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn, 765 NumOut, DFSInStack); 766 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) 767 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack); 768 769 break; 770 } 771 case CmpInst::ICMP_SGE: 772 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 773 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack); 774 } 775 break; 776 } 777 } 778 779 #ifndef NDEBUG 780 781 static void dumpConstraint(ArrayRef<int64_t> C, 782 const DenseMap<Value *, unsigned> &Value2Index) { 783 ConstraintSystem CS(Value2Index); 784 CS.addVariableRowFill(C); 785 CS.dump(); 786 } 787 #endif 788 789 void State::addInfoFor(BasicBlock &BB) { 790 // True as long as long as the current instruction is guaranteed to execute. 791 bool GuaranteedToExecute = true; 792 // Queue conditions and assumes. 793 for (Instruction &I : BB) { 794 if (auto Cmp = dyn_cast<ICmpInst>(&I)) { 795 for (Use &U : Cmp->uses()) { 796 auto *UserI = getContextInstForUse(U); 797 auto *DTN = DT.getNode(UserI->getParent()); 798 if (!DTN) 799 continue; 800 WorkList.push_back(FactOrCheck::getCheck(DTN, &U)); 801 } 802 continue; 803 } 804 805 if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) { 806 WorkList.push_back( 807 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I))); 808 continue; 809 } 810 811 if (isa<MinMaxIntrinsic>(&I)) { 812 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I)); 813 continue; 814 } 815 816 Value *A, *B; 817 CmpInst::Predicate Pred; 818 // For now, just handle assumes with a single compare as condition. 819 if (match(&I, m_Intrinsic<Intrinsic::assume>( 820 m_ICmp(Pred, m_Value(A), m_Value(B))))) { 821 if (GuaranteedToExecute) { 822 // The assume is guaranteed to execute when BB is entered, hence Cond 823 // holds on entry to BB. 824 WorkList.emplace_back(FactOrCheck::getConditionFact( 825 DT.getNode(I.getParent()), Pred, A, B)); 826 } else { 827 WorkList.emplace_back( 828 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I)); 829 } 830 } 831 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 832 } 833 834 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 835 if (!Br || !Br->isConditional()) 836 return; 837 838 Value *Cond = Br->getCondition(); 839 840 // If the condition is a chain of ORs/AND and the successor only has the 841 // current block as predecessor, queue conditions for the successor. 842 Value *Op0, *Op1; 843 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 844 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 845 bool IsOr = match(Cond, m_LogicalOr()); 846 bool IsAnd = match(Cond, m_LogicalAnd()); 847 // If there's a select that matches both AND and OR, we need to commit to 848 // one of the options. Arbitrarily pick OR. 849 if (IsOr && IsAnd) 850 IsAnd = false; 851 852 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0); 853 if (canAddSuccessor(BB, Successor)) { 854 SmallVector<Value *> CondWorkList; 855 SmallPtrSet<Value *, 8> SeenCond; 856 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) { 857 if (SeenCond.insert(V).second) 858 CondWorkList.push_back(V); 859 }; 860 QueueValue(Op1); 861 QueueValue(Op0); 862 while (!CondWorkList.empty()) { 863 Value *Cur = CondWorkList.pop_back_val(); 864 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) { 865 WorkList.emplace_back(FactOrCheck::getConditionFact( 866 DT.getNode(Successor), 867 IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate()) 868 : Cmp->getPredicate(), 869 Cmp->getOperand(0), Cmp->getOperand(1))); 870 continue; 871 } 872 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 873 QueueValue(Op1); 874 QueueValue(Op0); 875 continue; 876 } 877 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 878 QueueValue(Op1); 879 QueueValue(Op0); 880 continue; 881 } 882 } 883 } 884 return; 885 } 886 887 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 888 if (!CmpI) 889 return; 890 if (canAddSuccessor(BB, Br->getSuccessor(0))) 891 WorkList.emplace_back(FactOrCheck::getConditionFact( 892 DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(), 893 CmpI->getOperand(0), CmpI->getOperand(1))); 894 if (canAddSuccessor(BB, Br->getSuccessor(1))) 895 WorkList.emplace_back(FactOrCheck::getConditionFact( 896 DT.getNode(Br->getSuccessor(1)), 897 CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0), 898 CmpI->getOperand(1))); 899 } 900 901 namespace { 902 /// Helper to keep track of a condition and if it should be treated as negated 903 /// for reproducer construction. 904 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a 905 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack. 906 struct ReproducerEntry { 907 ICmpInst::Predicate Pred; 908 Value *LHS; 909 Value *RHS; 910 911 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS) 912 : Pred(Pred), LHS(LHS), RHS(RHS) {} 913 }; 914 } // namespace 915 916 /// Helper function to generate a reproducer function for simplifying \p Cond. 917 /// The reproducer function contains a series of @llvm.assume calls, one for 918 /// each condition in \p Stack. For each condition, the operand instruction are 919 /// cloned until we reach operands that have an entry in \p Value2Index. Those 920 /// will then be added as function arguments. \p DT is used to order cloned 921 /// instructions. The reproducer function will get added to \p M, if it is 922 /// non-null. Otherwise no reproducer function is generated. 923 static void generateReproducer(CmpInst *Cond, Module *M, 924 ArrayRef<ReproducerEntry> Stack, 925 ConstraintInfo &Info, DominatorTree &DT) { 926 if (!M) 927 return; 928 929 LLVMContext &Ctx = Cond->getContext(); 930 931 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n"); 932 933 ValueToValueMapTy Old2New; 934 SmallVector<Value *> Args; 935 SmallPtrSet<Value *, 8> Seen; 936 // Traverse Cond and its operands recursively until we reach a value that's in 937 // Value2Index or not an instruction, or not a operation that 938 // ConstraintElimination can decompose. Such values will be considered as 939 // external inputs to the reproducer, they are collected and added as function 940 // arguments later. 941 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) { 942 auto &Value2Index = Info.getValue2Index(IsSigned); 943 SmallVector<Value *, 4> WorkList(Ops); 944 while (!WorkList.empty()) { 945 Value *V = WorkList.pop_back_val(); 946 if (!Seen.insert(V).second) 947 continue; 948 if (Old2New.find(V) != Old2New.end()) 949 continue; 950 if (isa<Constant>(V)) 951 continue; 952 953 auto *I = dyn_cast<Instruction>(V); 954 if (Value2Index.contains(V) || !I || 955 !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) { 956 Old2New[V] = V; 957 Args.push_back(V); 958 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n"); 959 } else { 960 append_range(WorkList, I->operands()); 961 } 962 } 963 }; 964 965 for (auto &Entry : Stack) 966 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE) 967 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred)); 968 CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate())); 969 970 SmallVector<Type *> ParamTys; 971 for (auto *P : Args) 972 ParamTys.push_back(P->getType()); 973 974 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys, 975 /*isVarArg=*/false); 976 Function *F = Function::Create(FTy, Function::ExternalLinkage, 977 Cond->getModule()->getName() + 978 Cond->getFunction()->getName() + "repro", 979 M); 980 // Add arguments to the reproducer function for each external value collected. 981 for (unsigned I = 0; I < Args.size(); ++I) { 982 F->getArg(I)->setName(Args[I]->getName()); 983 Old2New[Args[I]] = F->getArg(I); 984 } 985 986 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F); 987 IRBuilder<> Builder(Entry); 988 Builder.CreateRet(Builder.getTrue()); 989 Builder.SetInsertPoint(Entry->getTerminator()); 990 991 // Clone instructions in \p Ops and their operands recursively until reaching 992 // an value in Value2Index (external input to the reproducer). Update Old2New 993 // mapping for the original and cloned instructions. Sort instructions to 994 // clone by dominance, then insert the cloned instructions in the function. 995 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) { 996 SmallVector<Value *, 4> WorkList(Ops); 997 SmallVector<Instruction *> ToClone; 998 auto &Value2Index = Info.getValue2Index(IsSigned); 999 while (!WorkList.empty()) { 1000 Value *V = WorkList.pop_back_val(); 1001 if (Old2New.find(V) != Old2New.end()) 1002 continue; 1003 1004 auto *I = dyn_cast<Instruction>(V); 1005 if (!Value2Index.contains(V) && I) { 1006 Old2New[V] = nullptr; 1007 ToClone.push_back(I); 1008 append_range(WorkList, I->operands()); 1009 } 1010 } 1011 1012 sort(ToClone, 1013 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); }); 1014 for (Instruction *I : ToClone) { 1015 Instruction *Cloned = I->clone(); 1016 Old2New[I] = Cloned; 1017 Old2New[I]->setName(I->getName()); 1018 Cloned->insertBefore(&*Builder.GetInsertPoint()); 1019 Cloned->dropUnknownNonDebugMetadata(); 1020 Cloned->setDebugLoc({}); 1021 } 1022 }; 1023 1024 // Materialize the assumptions for the reproducer using the entries in Stack. 1025 // That is, first clone the operands of the condition recursively until we 1026 // reach an external input to the reproducer and add them to the reproducer 1027 // function. Then add an ICmp for the condition (with the inverse predicate if 1028 // the entry is negated) and an assert using the ICmp. 1029 for (auto &Entry : Stack) { 1030 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE) 1031 continue; 1032 1033 LLVM_DEBUG( 1034 dbgs() << " Materializing assumption icmp " << Entry.Pred << ' '; 1035 Entry.LHS->printAsOperand(dbgs(), /*PrintType=*/true); dbgs() << ", "; 1036 Entry.RHS->printAsOperand(dbgs(), /*PrintType=*/false); dbgs() << "\n"); 1037 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred)); 1038 1039 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS); 1040 Builder.CreateAssumption(Cmp); 1041 } 1042 1043 // Finally, clone the condition to reproduce and remap instruction operands in 1044 // the reproducer using Old2New. 1045 CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate())); 1046 Entry->getTerminator()->setOperand(0, Cond); 1047 remapInstructionsInBlocks({Entry}, Old2New); 1048 1049 assert(!verifyFunction(*F, &dbgs())); 1050 } 1051 1052 static std::optional<bool> checkCondition(CmpInst *Cmp, ConstraintInfo &Info, 1053 unsigned NumIn, unsigned NumOut, 1054 Instruction *ContextInst) { 1055 LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n"); 1056 1057 CmpInst::Predicate Pred = Cmp->getPredicate(); 1058 Value *A = Cmp->getOperand(0); 1059 Value *B = Cmp->getOperand(1); 1060 1061 auto R = Info.getConstraintForSolving(Pred, A, B); 1062 if (R.empty() || !R.isValid(Info)){ 1063 LLVM_DEBUG(dbgs() << " failed to decompose condition\n"); 1064 return std::nullopt; 1065 } 1066 1067 auto &CSToUse = Info.getCS(R.IsSigned); 1068 1069 // If there was extra information collected during decomposition, apply 1070 // it now and remove it immediately once we are done with reasoning 1071 // about the constraint. 1072 for (auto &Row : R.ExtraInfo) 1073 CSToUse.addVariableRow(Row); 1074 auto InfoRestorer = make_scope_exit([&]() { 1075 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I) 1076 CSToUse.popLastConstraint(); 1077 }); 1078 1079 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) { 1080 if (!DebugCounter::shouldExecute(EliminatedCounter)) 1081 return std::nullopt; 1082 1083 LLVM_DEBUG({ 1084 if (*ImpliedCondition) { 1085 dbgs() << "Condition " << *Cmp; 1086 } else { 1087 auto InversePred = Cmp->getInversePredicate(); 1088 dbgs() << "Condition " << CmpInst::getPredicateName(InversePred) << " " 1089 << *A << ", " << *B; 1090 } 1091 dbgs() << " implied by dominating constraints\n"; 1092 CSToUse.dump(); 1093 }); 1094 return ImpliedCondition; 1095 } 1096 1097 return std::nullopt; 1098 } 1099 1100 static bool checkAndReplaceCondition( 1101 CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, 1102 Instruction *ContextInst, Module *ReproducerModule, 1103 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT, 1104 SmallVectorImpl<Instruction *> &ToRemove) { 1105 auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) { 1106 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT); 1107 Constant *ConstantC = ConstantInt::getBool( 1108 CmpInst::makeCmpResultType(Cmp->getType()), IsTrue); 1109 Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut, 1110 ContextInst](Use &U) { 1111 auto *UserI = getContextInstForUse(U); 1112 auto *DTN = DT.getNode(UserI->getParent()); 1113 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut) 1114 return false; 1115 if (UserI->getParent() == ContextInst->getParent() && 1116 UserI->comesBefore(ContextInst)) 1117 return false; 1118 1119 // Conditions in an assume trivially simplify to true. Skip uses 1120 // in assume calls to not destroy the available information. 1121 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 1122 return !II || II->getIntrinsicID() != Intrinsic::assume; 1123 }); 1124 NumCondsRemoved++; 1125 if (Cmp->use_empty()) 1126 ToRemove.push_back(Cmp); 1127 return true; 1128 }; 1129 1130 if (auto ImpliedCondition = 1131 checkCondition(Cmp, Info, NumIn, NumOut, ContextInst)) 1132 return ReplaceCmpWithConstant(Cmp, *ImpliedCondition); 1133 return false; 1134 } 1135 1136 static void 1137 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, 1138 Module *ReproducerModule, 1139 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 1140 SmallVectorImpl<StackEntry> &DFSInStack) { 1141 Info.popLastConstraint(E.IsSigned); 1142 // Remove variables in the system that went out of scope. 1143 auto &Mapping = Info.getValue2Index(E.IsSigned); 1144 for (Value *V : E.ValuesToRelease) 1145 Mapping.erase(V); 1146 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 1147 DFSInStack.pop_back(); 1148 if (ReproducerModule) 1149 ReproducerCondStack.pop_back(); 1150 } 1151 1152 /// Check if the first condition for an AND implies the second. 1153 static bool checkAndSecondOpImpliedByFirst( 1154 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, 1155 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 1156 SmallVectorImpl<StackEntry> &DFSInStack) { 1157 CmpInst::Predicate Pred; 1158 Value *A, *B; 1159 Instruction *And = CB.getContextInst(); 1160 if (!match(And->getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B)))) 1161 return false; 1162 1163 // Optimistically add fact from first condition. 1164 unsigned OldSize = DFSInStack.size(); 1165 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1166 if (OldSize == DFSInStack.size()) 1167 return false; 1168 1169 bool Changed = false; 1170 // Check if the second condition can be simplified now. 1171 if (auto ImpliedCondition = 1172 checkCondition(cast<ICmpInst>(And->getOperand(1)), Info, CB.NumIn, 1173 CB.NumOut, CB.getContextInst())) { 1174 And->setOperand(1, ConstantInt::getBool(And->getType(), *ImpliedCondition)); 1175 Changed = true; 1176 } 1177 1178 // Remove entries again. 1179 while (OldSize < DFSInStack.size()) { 1180 StackEntry E = DFSInStack.back(); 1181 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack, 1182 DFSInStack); 1183 } 1184 return Changed; 1185 } 1186 1187 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 1188 unsigned NumIn, unsigned NumOut, 1189 SmallVectorImpl<StackEntry> &DFSInStack) { 1190 // If the constraint has a pre-condition, skip the constraint if it does not 1191 // hold. 1192 SmallVector<Value *> NewVariables; 1193 auto R = getConstraint(Pred, A, B, NewVariables); 1194 1195 // TODO: Support non-equality for facts as well. 1196 if (!R.isValid(*this) || R.isNe()) 1197 return; 1198 1199 LLVM_DEBUG(dbgs() << "Adding '" << Pred << " "; 1200 A->printAsOperand(dbgs(), false); dbgs() << ", "; 1201 B->printAsOperand(dbgs(), false); dbgs() << "'\n"); 1202 bool Added = false; 1203 auto &CSToUse = getCS(R.IsSigned); 1204 if (R.Coefficients.empty()) 1205 return; 1206 1207 Added |= CSToUse.addVariableRowFill(R.Coefficients); 1208 1209 // If R has been added to the system, add the new variables and queue it for 1210 // removal once it goes out-of-scope. 1211 if (Added) { 1212 SmallVector<Value *, 2> ValuesToRelease; 1213 auto &Value2Index = getValue2Index(R.IsSigned); 1214 for (Value *V : NewVariables) { 1215 Value2Index.insert({V, Value2Index.size() + 1}); 1216 ValuesToRelease.push_back(V); 1217 } 1218 1219 LLVM_DEBUG({ 1220 dbgs() << " constraint: "; 1221 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned)); 1222 dbgs() << "\n"; 1223 }); 1224 1225 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1226 std::move(ValuesToRelease)); 1227 1228 if (R.isEq()) { 1229 // Also add the inverted constraint for equality constraints. 1230 for (auto &Coeff : R.Coefficients) 1231 Coeff *= -1; 1232 CSToUse.addVariableRowFill(R.Coefficients); 1233 1234 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1235 SmallVector<Value *, 2>()); 1236 } 1237 } 1238 } 1239 1240 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, 1241 SmallVectorImpl<Instruction *> &ToRemove) { 1242 bool Changed = false; 1243 IRBuilder<> Builder(II->getParent(), II->getIterator()); 1244 Value *Sub = nullptr; 1245 for (User *U : make_early_inc_range(II->users())) { 1246 if (match(U, m_ExtractValue<0>(m_Value()))) { 1247 if (!Sub) 1248 Sub = Builder.CreateSub(A, B); 1249 U->replaceAllUsesWith(Sub); 1250 Changed = true; 1251 } else if (match(U, m_ExtractValue<1>(m_Value()))) { 1252 U->replaceAllUsesWith(Builder.getFalse()); 1253 Changed = true; 1254 } else 1255 continue; 1256 1257 if (U->use_empty()) { 1258 auto *I = cast<Instruction>(U); 1259 ToRemove.push_back(I); 1260 I->setOperand(0, PoisonValue::get(II->getType())); 1261 Changed = true; 1262 } 1263 } 1264 1265 if (II->use_empty()) { 1266 II->eraseFromParent(); 1267 Changed = true; 1268 } 1269 return Changed; 1270 } 1271 1272 static bool 1273 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 1274 SmallVectorImpl<Instruction *> &ToRemove) { 1275 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 1276 ConstraintInfo &Info) { 1277 auto R = Info.getConstraintForSolving(Pred, A, B); 1278 if (R.size() < 2 || !R.isValid(Info)) 1279 return false; 1280 1281 auto &CSToUse = Info.getCS(R.IsSigned); 1282 return CSToUse.isConditionImplied(R.Coefficients); 1283 }; 1284 1285 bool Changed = false; 1286 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 1287 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 1288 // can be simplified to a regular sub. 1289 Value *A = II->getArgOperand(0); 1290 Value *B = II->getArgOperand(1); 1291 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 1292 !DoesConditionHold(CmpInst::ICMP_SGE, B, 1293 ConstantInt::get(A->getType(), 0), Info)) 1294 return false; 1295 Changed = replaceSubOverflowUses(II, A, B, ToRemove); 1296 } 1297 return Changed; 1298 } 1299 1300 static bool eliminateConstraints(Function &F, DominatorTree &DT, 1301 OptimizationRemarkEmitter &ORE) { 1302 bool Changed = false; 1303 DT.updateDFSNumbers(); 1304 SmallVector<Value *> FunctionArgs; 1305 for (Value &Arg : F.args()) 1306 FunctionArgs.push_back(&Arg); 1307 ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs); 1308 State S(DT); 1309 std::unique_ptr<Module> ReproducerModule( 1310 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr); 1311 1312 // First, collect conditions implied by branches and blocks with their 1313 // Dominator DFS in and out numbers. 1314 for (BasicBlock &BB : F) { 1315 if (!DT.getNode(&BB)) 1316 continue; 1317 S.addInfoFor(BB); 1318 } 1319 1320 // Next, sort worklist by dominance, so that dominating conditions to check 1321 // and facts come before conditions and facts dominated by them. If a 1322 // condition to check and a fact have the same numbers, conditional facts come 1323 // first. Assume facts and checks are ordered according to their relative 1324 // order in the containing basic block. Also make sure conditions with 1325 // constant operands come before conditions without constant operands. This 1326 // increases the effectiveness of the current signed <-> unsigned fact 1327 // transfer logic. 1328 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) { 1329 auto HasNoConstOp = [](const FactOrCheck &B) { 1330 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0); 1331 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1); 1332 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1); 1333 }; 1334 // If both entries have the same In numbers, conditional facts come first. 1335 // Otherwise use the relative order in the basic block. 1336 if (A.NumIn == B.NumIn) { 1337 if (A.isConditionFact() && B.isConditionFact()) { 1338 bool NoConstOpA = HasNoConstOp(A); 1339 bool NoConstOpB = HasNoConstOp(B); 1340 return NoConstOpA < NoConstOpB; 1341 } 1342 if (A.isConditionFact()) 1343 return true; 1344 if (B.isConditionFact()) 1345 return false; 1346 auto *InstA = A.getContextInst(); 1347 auto *InstB = B.getContextInst(); 1348 return InstA->comesBefore(InstB); 1349 } 1350 return A.NumIn < B.NumIn; 1351 }); 1352 1353 SmallVector<Instruction *> ToRemove; 1354 1355 // Finally, process ordered worklist and eliminate implied conditions. 1356 SmallVector<StackEntry, 16> DFSInStack; 1357 SmallVector<ReproducerEntry> ReproducerCondStack; 1358 for (FactOrCheck &CB : S.WorkList) { 1359 // First, pop entries from the stack that are out-of-scope for CB. Remove 1360 // the corresponding entry from the constraint system. 1361 while (!DFSInStack.empty()) { 1362 auto &E = DFSInStack.back(); 1363 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 1364 << "\n"); 1365 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 1366 assert(E.NumIn <= CB.NumIn); 1367 if (CB.NumOut <= E.NumOut) 1368 break; 1369 LLVM_DEBUG({ 1370 dbgs() << "Removing "; 1371 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(), 1372 Info.getValue2Index(E.IsSigned)); 1373 dbgs() << "\n"; 1374 }); 1375 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack, 1376 DFSInStack); 1377 } 1378 1379 LLVM_DEBUG(dbgs() << "Processing "); 1380 1381 // For a block, check if any CmpInsts become known based on the current set 1382 // of constraints. 1383 if (CB.isCheck()) { 1384 Instruction *Inst = CB.getInstructionToSimplify(); 1385 if (!Inst) 1386 continue; 1387 LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n"); 1388 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) { 1389 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove); 1390 } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) { 1391 bool Simplified = checkAndReplaceCondition( 1392 Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(), 1393 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove); 1394 if (!Simplified && match(CB.getContextInst(), 1395 m_LogicalAnd(m_Value(), m_Specific(Inst)))) { 1396 Simplified = 1397 checkAndSecondOpImpliedByFirst(CB, Info, ReproducerModule.get(), 1398 ReproducerCondStack, DFSInStack); 1399 } 1400 Changed |= Simplified; 1401 } 1402 continue; 1403 } 1404 1405 auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) { 1406 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) { 1407 LLVM_DEBUG( 1408 dbgs() 1409 << "Skip adding constraint because system has too many rows.\n"); 1410 return; 1411 } 1412 1413 LLVM_DEBUG({ 1414 dbgs() << "Processing fact to add to the system: " << Pred << " "; 1415 A->printAsOperand(dbgs()); 1416 dbgs() << ", "; 1417 B->printAsOperand(dbgs(), false); 1418 dbgs() << "\n"; 1419 }); 1420 1421 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1422 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) 1423 ReproducerCondStack.emplace_back(Pred, A, B); 1424 1425 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1426 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) { 1427 // Add dummy entries to ReproducerCondStack to keep it in sync with 1428 // DFSInStack. 1429 for (unsigned I = 0, 1430 E = (DFSInStack.size() - ReproducerCondStack.size()); 1431 I < E; ++I) { 1432 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE, 1433 nullptr, nullptr); 1434 } 1435 } 1436 }; 1437 1438 ICmpInst::Predicate Pred; 1439 if (!CB.isConditionFact()) { 1440 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) { 1441 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate()); 1442 AddFact(Pred, MinMax, MinMax->getLHS()); 1443 AddFact(Pred, MinMax, MinMax->getRHS()); 1444 continue; 1445 } 1446 } 1447 1448 Value *A = nullptr, *B = nullptr; 1449 if (CB.isConditionFact()) { 1450 Pred = CB.Cond.Pred; 1451 A = CB.Cond.Op0; 1452 B = CB.Cond.Op1; 1453 } else { 1454 bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>( 1455 m_ICmp(Pred, m_Value(A), m_Value(B)))); 1456 (void)Matched; 1457 assert(Matched && "Must have an assume intrinsic with a icmp operand"); 1458 } 1459 AddFact(Pred, A, B); 1460 } 1461 1462 if (ReproducerModule && !ReproducerModule->functions().empty()) { 1463 std::string S; 1464 raw_string_ostream StringS(S); 1465 ReproducerModule->print(StringS, nullptr); 1466 StringS.flush(); 1467 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F); 1468 Rem << ore::NV("module") << S; 1469 ORE.emit(Rem); 1470 } 1471 1472 #ifndef NDEBUG 1473 unsigned SignedEntries = 1474 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 1475 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 1476 "updates to CS and DFSInStack are out of sync"); 1477 assert(Info.getCS(true).size() == SignedEntries && 1478 "updates to CS and DFSInStack are out of sync"); 1479 #endif 1480 1481 for (Instruction *I : ToRemove) 1482 I->eraseFromParent(); 1483 return Changed; 1484 } 1485 1486 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 1487 FunctionAnalysisManager &AM) { 1488 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1489 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1490 if (!eliminateConstraints(F, DT, ORE)) 1491 return PreservedAnalyses::all(); 1492 1493 PreservedAnalyses PA; 1494 PA.preserve<DominatorTreeAnalysis>(); 1495 PA.preserveSet<CFGAnalyses>(); 1496 return PA; 1497 } 1498