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