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