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/ValueTracking.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/PatternMatch.h" 29 #include "llvm/InitializePasses.h" 30 #include "llvm/Pass.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/DebugCounter.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Transforms/Scalar.h" 35 36 #include <cmath> 37 #include <string> 38 39 using namespace llvm; 40 using namespace PatternMatch; 41 42 #define DEBUG_TYPE "constraint-elimination" 43 44 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 45 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 46 "Controls which conditions are eliminated"); 47 48 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 49 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 50 51 // A helper to multiply 2 signed integers where overflowing is allowed. 52 static int64_t multiplyWithOverflow(int64_t A, int64_t B) { 53 int64_t Result; 54 MulOverflow(A, B, Result); 55 return Result; 56 } 57 58 // A helper to add 2 signed integers where overflowing is allowed. 59 static int64_t addWithOverflow(int64_t A, int64_t B) { 60 int64_t Result; 61 AddOverflow(A, B, Result); 62 return Result; 63 } 64 65 namespace { 66 67 class ConstraintInfo; 68 69 struct StackEntry { 70 unsigned NumIn; 71 unsigned NumOut; 72 bool IsSigned = false; 73 /// Variables that can be removed from the system once the stack entry gets 74 /// removed. 75 SmallVector<Value *, 2> ValuesToRelease; 76 77 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned, 78 SmallVector<Value *, 2> ValuesToRelease) 79 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned), 80 ValuesToRelease(ValuesToRelease) {} 81 }; 82 83 /// Struct to express a pre-condition of the form %Op0 Pred %Op1. 84 struct PreconditionTy { 85 CmpInst::Predicate Pred; 86 Value *Op0; 87 Value *Op1; 88 89 PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 90 : Pred(Pred), Op0(Op0), Op1(Op1) {} 91 }; 92 93 struct ConstraintTy { 94 SmallVector<int64_t, 8> Coefficients; 95 SmallVector<PreconditionTy, 2> Preconditions; 96 97 SmallVector<SmallVector<int64_t, 8>> ExtraInfo; 98 99 bool IsSigned = false; 100 bool IsEq = false; 101 102 ConstraintTy() = default; 103 104 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned) 105 : Coefficients(Coefficients), IsSigned(IsSigned) {} 106 107 unsigned size() const { return Coefficients.size(); } 108 109 unsigned empty() const { return Coefficients.empty(); } 110 111 /// Returns true if all preconditions for this list of constraints are 112 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 113 bool isValid(const ConstraintInfo &Info) const; 114 }; 115 116 /// Wrapper encapsulating separate constraint systems and corresponding value 117 /// mappings for both unsigned and signed information. Facts are added to and 118 /// conditions are checked against the corresponding system depending on the 119 /// signed-ness of their predicates. While the information is kept separate 120 /// based on signed-ness, certain conditions can be transferred between the two 121 /// systems. 122 class ConstraintInfo { 123 DenseMap<Value *, unsigned> UnsignedValue2Index; 124 DenseMap<Value *, unsigned> SignedValue2Index; 125 126 ConstraintSystem UnsignedCS; 127 ConstraintSystem SignedCS; 128 129 const DataLayout &DL; 130 131 public: 132 ConstraintInfo(const DataLayout &DL) : DL(DL) {} 133 134 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 135 return Signed ? SignedValue2Index : UnsignedValue2Index; 136 } 137 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 138 return Signed ? SignedValue2Index : UnsignedValue2Index; 139 } 140 141 ConstraintSystem &getCS(bool Signed) { 142 return Signed ? SignedCS : UnsignedCS; 143 } 144 const ConstraintSystem &getCS(bool Signed) const { 145 return Signed ? SignedCS : UnsignedCS; 146 } 147 148 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 149 void popLastNVariables(bool Signed, unsigned N) { 150 getCS(Signed).popLastNVariables(N); 151 } 152 153 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 154 155 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 156 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 157 158 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 159 /// constraints, using indices from the corresponding constraint system. 160 /// New variables that need to be added to the system are collected in 161 /// \p NewVariables. 162 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 163 SmallVectorImpl<Value *> &NewVariables) const; 164 165 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 166 /// constraints using getConstraint. Returns an empty constraint if the result 167 /// cannot be used to query the existing constraint system, e.g. because it 168 /// would require adding new variables. Also tries to convert signed 169 /// predicates to unsigned ones if possible to allow using the unsigned system 170 /// which increases the effectiveness of the signed <-> unsigned transfer 171 /// logic. 172 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0, 173 Value *Op1) const; 174 175 /// Try to add information from \p A \p Pred \p B to the unsigned/signed 176 /// system if \p Pred is signed/unsigned. 177 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B, 178 unsigned NumIn, unsigned NumOut, 179 SmallVectorImpl<StackEntry> &DFSInStack); 180 }; 181 182 /// Represents a (Coefficient * Variable) entry after IR decomposition. 183 struct DecompEntry { 184 int64_t Coefficient; 185 Value *Variable; 186 /// True if the variable is known positive in the current constraint. 187 bool IsKnownPositive; 188 189 DecompEntry(int64_t Coefficient, Value *Variable, 190 bool IsKnownPositive = false) 191 : Coefficient(Coefficient), Variable(Variable), 192 IsKnownPositive(IsKnownPositive) {} 193 }; 194 195 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition. 196 struct Decomposition { 197 int64_t Offset = 0; 198 SmallVector<DecompEntry, 3> Vars; 199 200 Decomposition(int64_t Offset) : Offset(Offset) {} 201 Decomposition(Value *V, bool IsKnownPositive = false) { 202 Vars.emplace_back(1, V, IsKnownPositive); 203 } 204 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars) 205 : Offset(Offset), Vars(Vars) {} 206 207 void add(int64_t OtherOffset) { 208 Offset = addWithOverflow(Offset, OtherOffset); 209 } 210 211 void add(const Decomposition &Other) { 212 add(Other.Offset); 213 append_range(Vars, Other.Vars); 214 } 215 216 void mul(int64_t Factor) { 217 Offset = multiplyWithOverflow(Offset, Factor); 218 for (auto &Var : Vars) 219 Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor); 220 } 221 }; 222 223 } // namespace 224 225 static Decomposition decompose(Value *V, 226 SmallVectorImpl<PreconditionTy> &Preconditions, 227 bool IsSigned, const DataLayout &DL); 228 229 static bool canUseSExt(ConstantInt *CI) { 230 const APInt &Val = CI->getValue(); 231 return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 232 } 233 234 static Decomposition 235 decomposeGEP(GetElementPtrInst &GEP, 236 SmallVectorImpl<PreconditionTy> &Preconditions, bool IsSigned, 237 const DataLayout &DL) { 238 // Do not reason about pointers where the index size is larger than 64 bits, 239 // as the coefficients used to encode constraints are 64 bit integers. 240 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64) 241 return &GEP; 242 243 if (!GEP.isInBounds()) 244 return &GEP; 245 246 Type *PtrTy = GEP.getType()->getScalarType(); 247 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy); 248 MapVector<Value *, APInt> VariableOffsets; 249 APInt ConstantOffset(BitWidth, 0); 250 if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) 251 return &GEP; 252 253 // Handle the (gep (gep ....), C) case by incrementing the constant 254 // coefficient of the inner GEP, if C is a constant. 255 auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand()); 256 if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) { 257 auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL); 258 Result.add(ConstantOffset.getSExtValue()); 259 260 if (ConstantOffset.isNegative()) { 261 unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType()); 262 int64_t ConstantOffsetI = ConstantOffset.getSExtValue(); 263 if (ConstantOffsetI % Scale != 0) 264 return &GEP; 265 // Add pre-condition ensuring the GEP is increasing monotonically and 266 // can be de-composed. 267 // Both sides are normalized by being divided by Scale. 268 Preconditions.emplace_back( 269 CmpInst::ICMP_SGE, InnerGEP->getOperand(1), 270 ConstantInt::get(InnerGEP->getOperand(1)->getType(), 271 -1 * (ConstantOffsetI / Scale))); 272 } 273 return Result; 274 } 275 276 Decomposition Result(ConstantOffset.getSExtValue(), 277 DecompEntry(1, GEP.getPointerOperand())); 278 for (auto [Index, Scale] : VariableOffsets) { 279 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL); 280 IdxResult.mul(Scale.getSExtValue()); 281 Result.add(IdxResult); 282 283 // If Op0 is signed non-negative, the GEP is increasing monotonically and 284 // can be de-composed. 285 if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 286 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index, 287 ConstantInt::get(Index->getType(), 0)); 288 } 289 return Result; 290 } 291 292 // Decomposes \p V into a vector of entries of the form { Coefficient, Variable 293 // } where Coefficient * Variable. The sum of the pairs equals \p V. The first 294 // pair is the constant-factor and X must be nullptr. If the expression cannot 295 // be decomposed, returns an empty vector. 296 static Decomposition decompose(Value *V, 297 SmallVectorImpl<PreconditionTy> &Preconditions, 298 bool IsSigned, const DataLayout &DL) { 299 300 auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B, 301 bool IsSignedB) { 302 auto ResA = decompose(A, Preconditions, IsSigned, DL); 303 auto ResB = decompose(B, Preconditions, IsSignedB, DL); 304 ResA.add(ResB); 305 return ResA; 306 }; 307 308 // Decompose \p V used with a signed predicate. 309 if (IsSigned) { 310 if (auto *CI = dyn_cast<ConstantInt>(V)) { 311 if (canUseSExt(CI)) 312 return CI->getSExtValue(); 313 } 314 Value *Op0; 315 Value *Op1; 316 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) 317 return MergeResults(Op0, Op1, IsSigned); 318 319 return V; 320 } 321 322 if (auto *CI = dyn_cast<ConstantInt>(V)) { 323 if (CI->uge(MaxConstraintValue)) 324 return V; 325 return int64_t(CI->getZExtValue()); 326 } 327 328 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) 329 return decomposeGEP(*GEP, Preconditions, IsSigned, DL); 330 331 Value *Op0; 332 bool IsKnownPositive = false; 333 if (match(V, m_ZExt(m_Value(Op0)))) { 334 IsKnownPositive = true; 335 V = Op0; 336 } 337 338 Value *Op1; 339 ConstantInt *CI; 340 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) { 341 return MergeResults(Op0, Op1, IsSigned); 342 } 343 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) { 344 if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 345 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 346 ConstantInt::get(Op0->getType(), 0)); 347 if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 348 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1, 349 ConstantInt::get(Op1->getType(), 0)); 350 351 return MergeResults(Op0, Op1, IsSigned); 352 } 353 354 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 355 canUseSExt(CI)) { 356 Preconditions.emplace_back( 357 CmpInst::ICMP_UGE, Op0, 358 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 359 return MergeResults(Op0, CI, true); 360 } 361 362 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) { 363 int64_t Mult = int64_t(std::pow(int64_t(2), CI->getSExtValue())); 364 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 365 Result.mul(Mult); 366 return Result; 367 } 368 369 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) && 370 (!CI->isNegative())) { 371 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 372 Result.mul(CI->getSExtValue()); 373 return Result; 374 } 375 376 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) 377 return {-1 * CI->getSExtValue(), {{1, Op0}}}; 378 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 379 return {0, {{1, Op0}, {-1, Op1}}}; 380 381 return {V, IsKnownPositive}; 382 } 383 384 ConstraintTy 385 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 386 SmallVectorImpl<Value *> &NewVariables) const { 387 assert(NewVariables.empty() && "NewVariables must be empty when passed in"); 388 bool IsEq = false; 389 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 390 switch (Pred) { 391 case CmpInst::ICMP_UGT: 392 case CmpInst::ICMP_UGE: 393 case CmpInst::ICMP_SGT: 394 case CmpInst::ICMP_SGE: { 395 Pred = CmpInst::getSwappedPredicate(Pred); 396 std::swap(Op0, Op1); 397 break; 398 } 399 case CmpInst::ICMP_EQ: 400 if (match(Op1, m_Zero())) { 401 Pred = CmpInst::ICMP_ULE; 402 } else { 403 IsEq = true; 404 Pred = CmpInst::ICMP_ULE; 405 } 406 break; 407 case CmpInst::ICMP_NE: 408 if (!match(Op1, m_Zero())) 409 return {}; 410 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 411 std::swap(Op0, Op1); 412 break; 413 default: 414 break; 415 } 416 417 // Only ULE and ULT predicates are supported at the moment. 418 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 419 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 420 return {}; 421 422 SmallVector<PreconditionTy, 4> Preconditions; 423 bool IsSigned = CmpInst::isSigned(Pred); 424 auto &Value2Index = getValue2Index(IsSigned); 425 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 426 Preconditions, IsSigned, DL); 427 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 428 Preconditions, IsSigned, DL); 429 int64_t Offset1 = ADec.Offset; 430 int64_t Offset2 = BDec.Offset; 431 Offset1 *= -1; 432 433 auto &VariablesA = ADec.Vars; 434 auto &VariablesB = BDec.Vars; 435 436 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a 437 // new entry to NewVariables. 438 DenseMap<Value *, unsigned> NewIndexMap; 439 auto GetOrAddIndex = [&Value2Index, &NewVariables, 440 &NewIndexMap](Value *V) -> unsigned { 441 auto V2I = Value2Index.find(V); 442 if (V2I != Value2Index.end()) 443 return V2I->second; 444 auto Insert = 445 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1}); 446 if (Insert.second) 447 NewVariables.push_back(V); 448 return Insert.first->second; 449 }; 450 451 // Make sure all variables have entries in Value2Index or NewVariables. 452 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB)) 453 GetOrAddIndex(KV.Variable); 454 455 // Build result constraint, by first adding all coefficients from A and then 456 // subtracting all coefficients from B. 457 ConstraintTy Res( 458 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0), 459 IsSigned); 460 // Collect variables that are known to be positive in all uses in the 461 // constraint. 462 DenseMap<Value *, bool> KnownPositiveVariables; 463 Res.IsEq = IsEq; 464 auto &R = Res.Coefficients; 465 for (const auto &KV : VariablesA) { 466 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient; 467 auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive}); 468 I.first->second &= KV.IsKnownPositive; 469 } 470 471 for (const auto &KV : VariablesB) { 472 R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient; 473 auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive}); 474 I.first->second &= KV.IsKnownPositive; 475 } 476 477 int64_t OffsetSum; 478 if (AddOverflow(Offset1, Offset2, OffsetSum)) 479 return {}; 480 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 481 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 482 return {}; 483 R[0] = OffsetSum; 484 Res.Preconditions = std::move(Preconditions); 485 486 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new 487 // variables. 488 while (!NewVariables.empty()) { 489 int64_t Last = R.back(); 490 if (Last != 0) 491 break; 492 R.pop_back(); 493 Value *RemovedV = NewVariables.pop_back_val(); 494 NewIndexMap.erase(RemovedV); 495 } 496 497 // Add extra constraints for variables that are known positive. 498 for (auto &KV : KnownPositiveVariables) { 499 if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() && 500 NewIndexMap.find(KV.first) == NewIndexMap.end())) 501 continue; 502 SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0); 503 C[GetOrAddIndex(KV.first)] = -1; 504 Res.ExtraInfo.push_back(C); 505 } 506 return Res; 507 } 508 509 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred, 510 Value *Op0, 511 Value *Op1) const { 512 // If both operands are known to be non-negative, change signed predicates to 513 // unsigned ones. This increases the reasoning effectiveness in combination 514 // with the signed <-> unsigned transfer logic. 515 if (CmpInst::isSigned(Pred) && 516 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) && 517 isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 518 Pred = CmpInst::getUnsignedPredicate(Pred); 519 520 SmallVector<Value *> NewVariables; 521 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables); 522 if (R.IsEq || !NewVariables.empty()) 523 return {}; 524 return R; 525 } 526 527 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 528 return Coefficients.size() > 0 && 529 all_of(Preconditions, [&Info](const PreconditionTy &C) { 530 return Info.doesHold(C.Pred, C.Op0, C.Op1); 531 }); 532 } 533 534 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 535 Value *B) const { 536 auto R = getConstraintForSolving(Pred, A, B); 537 return R.Preconditions.empty() && !R.empty() && 538 getCS(R.IsSigned).isConditionImplied(R.Coefficients); 539 } 540 541 void ConstraintInfo::transferToOtherSystem( 542 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 543 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) { 544 // Check if we can combine facts from the signed and unsigned systems to 545 // derive additional facts. 546 if (!A->getType()->isIntegerTy()) 547 return; 548 // FIXME: This currently depends on the order we add facts. Ideally we 549 // would first add all known facts and only then try to add additional 550 // facts. 551 switch (Pred) { 552 default: 553 break; 554 case CmpInst::ICMP_ULT: 555 // If B is a signed positive constant, A >=s 0 and A <s B. 556 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 557 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn, 558 NumOut, DFSInStack); 559 addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack); 560 } 561 break; 562 case CmpInst::ICMP_SLT: 563 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) 564 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack); 565 break; 566 case CmpInst::ICMP_SGT: 567 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 568 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn, 569 NumOut, DFSInStack); 570 break; 571 case CmpInst::ICMP_SGE: 572 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 573 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack); 574 } 575 break; 576 } 577 } 578 579 namespace { 580 /// Represents either a condition that holds on entry to a block or a basic 581 /// block, with their respective Dominator DFS in and out numbers. 582 struct ConstraintOrBlock { 583 unsigned NumIn; 584 unsigned NumOut; 585 bool IsBlock; 586 bool Not; 587 union { 588 BasicBlock *BB; 589 CmpInst *Condition; 590 }; 591 592 ConstraintOrBlock(DomTreeNode *DTN) 593 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 594 BB(DTN->getBlock()) {} 595 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 596 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 597 Not(Not), Condition(Condition) {} 598 }; 599 600 /// Keep state required to build worklist. 601 struct State { 602 DominatorTree &DT; 603 SmallVector<ConstraintOrBlock, 64> WorkList; 604 605 State(DominatorTree &DT) : DT(DT) {} 606 607 /// Process block \p BB and add known facts to work-list. 608 void addInfoFor(BasicBlock &BB); 609 610 /// Returns true if we can add a known condition from BB to its successor 611 /// block Succ. Each predecessor of Succ can either be BB or be dominated 612 /// by Succ (e.g. the case when adding a condition from a pre-header to a 613 /// loop header). 614 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 615 if (BB.getSingleSuccessor()) { 616 assert(BB.getSingleSuccessor() == Succ); 617 return DT.properlyDominates(&BB, Succ); 618 } 619 return any_of(successors(&BB), 620 [Succ](const BasicBlock *S) { return S != Succ; }) && 621 all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) { 622 return Pred == &BB || DT.dominates(Succ, Pred); 623 }); 624 } 625 }; 626 627 } // namespace 628 629 #ifndef NDEBUG 630 static void dumpWithNames(const ConstraintSystem &CS, 631 DenseMap<Value *, unsigned> &Value2Index) { 632 SmallVector<std::string> Names(Value2Index.size(), ""); 633 for (auto &KV : Value2Index) { 634 Names[KV.second - 1] = std::string("%") + KV.first->getName().str(); 635 } 636 CS.dump(Names); 637 } 638 639 static void dumpWithNames(ArrayRef<int64_t> C, 640 DenseMap<Value *, unsigned> &Value2Index) { 641 ConstraintSystem CS; 642 CS.addVariableRowFill(C); 643 dumpWithNames(CS, Value2Index); 644 } 645 #endif 646 647 void State::addInfoFor(BasicBlock &BB) { 648 WorkList.emplace_back(DT.getNode(&BB)); 649 650 // True as long as long as the current instruction is guaranteed to execute. 651 bool GuaranteedToExecute = true; 652 // Scan BB for assume calls. 653 // TODO: also use this scan to queue conditions to simplify, so we can 654 // interleave facts from assumes and conditions to simplify in a single 655 // basic block. And to skip another traversal of each basic block when 656 // simplifying. 657 for (Instruction &I : BB) { 658 Value *Cond; 659 // For now, just handle assumes with a single compare as condition. 660 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 661 isa<ICmpInst>(Cond)) { 662 if (GuaranteedToExecute) { 663 // The assume is guaranteed to execute when BB is entered, hence Cond 664 // holds on entry to BB. 665 WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false); 666 } else { 667 // Otherwise the condition only holds in the successors. 668 for (BasicBlock *Succ : successors(&BB)) { 669 if (!canAddSuccessor(BB, Succ)) 670 continue; 671 WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false); 672 } 673 } 674 } 675 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 676 } 677 678 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 679 if (!Br || !Br->isConditional()) 680 return; 681 682 Value *Cond = Br->getCondition(); 683 684 // If the condition is a chain of ORs/AND and the successor only has the 685 // current block as predecessor, queue conditions for the successor. 686 Value *Op0, *Op1; 687 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 688 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 689 bool IsOr = match(Cond, m_LogicalOr()); 690 bool IsAnd = match(Cond, m_LogicalAnd()); 691 // If there's a select that matches both AND and OR, we need to commit to 692 // one of the options. Arbitrarily pick OR. 693 if (IsOr && IsAnd) 694 IsAnd = false; 695 696 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0); 697 if (canAddSuccessor(BB, Successor)) { 698 SmallVector<Value *> CondWorkList; 699 SmallPtrSet<Value *, 8> SeenCond; 700 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) { 701 if (SeenCond.insert(V).second) 702 CondWorkList.push_back(V); 703 }; 704 QueueValue(Op1); 705 QueueValue(Op0); 706 while (!CondWorkList.empty()) { 707 Value *Cur = CondWorkList.pop_back_val(); 708 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) { 709 WorkList.emplace_back(DT.getNode(Successor), Cmp, IsOr); 710 continue; 711 } 712 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 713 QueueValue(Op1); 714 QueueValue(Op0); 715 continue; 716 } 717 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 718 QueueValue(Op1); 719 QueueValue(Op0); 720 continue; 721 } 722 } 723 } 724 return; 725 } 726 727 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 728 if (!CmpI) 729 return; 730 if (canAddSuccessor(BB, Br->getSuccessor(0))) 731 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 732 if (canAddSuccessor(BB, Br->getSuccessor(1))) 733 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 734 } 735 736 static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info) { 737 LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n"); 738 739 CmpInst::Predicate Pred = Cmp->getPredicate(); 740 Value *A = Cmp->getOperand(0); 741 Value *B = Cmp->getOperand(1); 742 743 auto R = Info.getConstraintForSolving(Pred, A, B); 744 if (R.empty() || !R.isValid(Info)){ 745 LLVM_DEBUG(dbgs() << " failed to decompose condition\n"); 746 return false; 747 } 748 749 auto &CSToUse = Info.getCS(R.IsSigned); 750 751 // If there was extra information collected during decomposition, apply 752 // it now and remove it immediately once we are done with reasoning 753 // about the constraint. 754 for (auto &Row : R.ExtraInfo) 755 CSToUse.addVariableRow(Row); 756 auto InfoRestorer = make_scope_exit([&]() { 757 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I) 758 CSToUse.popLastConstraint(); 759 }); 760 761 bool Changed = false; 762 if (CSToUse.isConditionImplied(R.Coefficients)) { 763 if (!DebugCounter::shouldExecute(EliminatedCounter)) 764 return false; 765 766 LLVM_DEBUG({ 767 dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n"; 768 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 769 }); 770 Constant *TrueC = 771 ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType())); 772 Cmp->replaceUsesWithIf(TrueC, [](Use &U) { 773 // Conditions in an assume trivially simplify to true. Skip uses 774 // in assume calls to not destroy the available information. 775 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 776 return !II || II->getIntrinsicID() != Intrinsic::assume; 777 }); 778 NumCondsRemoved++; 779 Changed = true; 780 } 781 if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) { 782 if (!DebugCounter::shouldExecute(EliminatedCounter)) 783 return false; 784 785 LLVM_DEBUG({ 786 dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n"; 787 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 788 }); 789 Constant *FalseC = 790 ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType())); 791 Cmp->replaceAllUsesWith(FalseC); 792 NumCondsRemoved++; 793 Changed = true; 794 } 795 return Changed; 796 } 797 798 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 799 unsigned NumIn, unsigned NumOut, 800 SmallVectorImpl<StackEntry> &DFSInStack) { 801 // If the constraint has a pre-condition, skip the constraint if it does not 802 // hold. 803 SmallVector<Value *> NewVariables; 804 auto R = getConstraint(Pred, A, B, NewVariables); 805 if (!R.isValid(*this)) 806 return; 807 808 LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " "; 809 A->printAsOperand(dbgs(), false); dbgs() << ", "; 810 B->printAsOperand(dbgs(), false); dbgs() << "'\n"); 811 bool Added = false; 812 auto &CSToUse = getCS(R.IsSigned); 813 if (R.Coefficients.empty()) 814 return; 815 816 Added |= CSToUse.addVariableRowFill(R.Coefficients); 817 818 // If R has been added to the system, add the new variables and queue it for 819 // removal once it goes out-of-scope. 820 if (Added) { 821 SmallVector<Value *, 2> ValuesToRelease; 822 auto &Value2Index = getValue2Index(R.IsSigned); 823 for (Value *V : NewVariables) { 824 Value2Index.insert({V, Value2Index.size() + 1}); 825 ValuesToRelease.push_back(V); 826 } 827 828 LLVM_DEBUG({ 829 dbgs() << " constraint: "; 830 dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned)); 831 dbgs() << "\n"; 832 }); 833 834 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease); 835 836 if (R.IsEq) { 837 // Also add the inverted constraint for equality constraints. 838 for (auto &Coeff : R.Coefficients) 839 Coeff *= -1; 840 CSToUse.addVariableRowFill(R.Coefficients); 841 842 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 843 SmallVector<Value *, 2>()); 844 } 845 } 846 } 847 848 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, 849 SmallVectorImpl<Instruction *> &ToRemove) { 850 bool Changed = false; 851 IRBuilder<> Builder(II->getParent(), II->getIterator()); 852 Value *Sub = nullptr; 853 for (User *U : make_early_inc_range(II->users())) { 854 if (match(U, m_ExtractValue<0>(m_Value()))) { 855 if (!Sub) 856 Sub = Builder.CreateSub(A, B); 857 U->replaceAllUsesWith(Sub); 858 Changed = true; 859 } else if (match(U, m_ExtractValue<1>(m_Value()))) { 860 U->replaceAllUsesWith(Builder.getFalse()); 861 Changed = true; 862 } else 863 continue; 864 865 if (U->use_empty()) { 866 auto *I = cast<Instruction>(U); 867 ToRemove.push_back(I); 868 I->setOperand(0, PoisonValue::get(II->getType())); 869 Changed = true; 870 } 871 } 872 873 if (II->use_empty()) { 874 II->eraseFromParent(); 875 Changed = true; 876 } 877 return Changed; 878 } 879 880 static bool 881 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 882 SmallVectorImpl<Instruction *> &ToRemove) { 883 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 884 ConstraintInfo &Info) { 885 auto R = Info.getConstraintForSolving(Pred, A, B); 886 if (R.size() < 2 || !R.isValid(Info)) 887 return false; 888 889 auto &CSToUse = Info.getCS(R.IsSigned); 890 return CSToUse.isConditionImplied(R.Coefficients); 891 }; 892 893 bool Changed = false; 894 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 895 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 896 // can be simplified to a regular sub. 897 Value *A = II->getArgOperand(0); 898 Value *B = II->getArgOperand(1); 899 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 900 !DoesConditionHold(CmpInst::ICMP_SGE, B, 901 ConstantInt::get(A->getType(), 0), Info)) 902 return false; 903 Changed = replaceSubOverflowUses(II, A, B, ToRemove); 904 } 905 return Changed; 906 } 907 908 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 909 bool Changed = false; 910 DT.updateDFSNumbers(); 911 912 ConstraintInfo Info(F.getParent()->getDataLayout()); 913 State S(DT); 914 915 // First, collect conditions implied by branches and blocks with their 916 // Dominator DFS in and out numbers. 917 for (BasicBlock &BB : F) { 918 if (!DT.getNode(&BB)) 919 continue; 920 S.addInfoFor(BB); 921 } 922 923 // Next, sort worklist by dominance, so that dominating blocks and conditions 924 // come before blocks and conditions dominated by them. If a block and a 925 // condition have the same numbers, the condition comes before the block, as 926 // it holds on entry to the block. Also make sure conditions with constant 927 // operands come before conditions without constant operands. This increases 928 // the effectiveness of the current signed <-> unsigned fact transfer logic. 929 stable_sort( 930 S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 931 auto HasNoConstOp = [](const ConstraintOrBlock &B) { 932 return !B.IsBlock && !isa<ConstantInt>(B.Condition->getOperand(0)) && 933 !isa<ConstantInt>(B.Condition->getOperand(1)); 934 }; 935 bool NoConstOpA = HasNoConstOp(A); 936 bool NoConstOpB = HasNoConstOp(B); 937 return std::tie(A.NumIn, A.IsBlock, NoConstOpA) < 938 std::tie(B.NumIn, B.IsBlock, NoConstOpB); 939 }); 940 941 SmallVector<Instruction *> ToRemove; 942 943 // Finally, process ordered worklist and eliminate implied conditions. 944 SmallVector<StackEntry, 16> DFSInStack; 945 for (ConstraintOrBlock &CB : S.WorkList) { 946 // First, pop entries from the stack that are out-of-scope for CB. Remove 947 // the corresponding entry from the constraint system. 948 while (!DFSInStack.empty()) { 949 auto &E = DFSInStack.back(); 950 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 951 << "\n"); 952 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 953 assert(E.NumIn <= CB.NumIn); 954 if (CB.NumOut <= E.NumOut) 955 break; 956 LLVM_DEBUG({ 957 dbgs() << "Removing "; 958 dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(), 959 Info.getValue2Index(E.IsSigned)); 960 dbgs() << "\n"; 961 }); 962 963 Info.popLastConstraint(E.IsSigned); 964 // Remove variables in the system that went out of scope. 965 auto &Mapping = Info.getValue2Index(E.IsSigned); 966 for (Value *V : E.ValuesToRelease) 967 Mapping.erase(V); 968 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 969 DFSInStack.pop_back(); 970 } 971 972 LLVM_DEBUG({ 973 dbgs() << "Processing "; 974 if (CB.IsBlock) 975 dbgs() << *CB.BB; 976 else 977 dbgs() << *CB.Condition; 978 dbgs() << "\n"; 979 }); 980 981 // For a block, check if any CmpInsts become known based on the current set 982 // of constraints. 983 if (CB.IsBlock) { 984 for (Instruction &I : make_early_inc_range(*CB.BB)) { 985 if (auto *II = dyn_cast<WithOverflowInst>(&I)) { 986 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove); 987 continue; 988 } 989 auto *Cmp = dyn_cast<ICmpInst>(&I); 990 if (!Cmp) 991 continue; 992 993 Changed |= checkAndReplaceCondition(Cmp, Info); 994 } 995 continue; 996 } 997 998 ICmpInst::Predicate Pred; 999 Value *A, *B; 1000 if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) { 1001 // Use the inverse predicate if required. 1002 if (CB.Not) 1003 Pred = CmpInst::getInversePredicate(Pred); 1004 1005 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1006 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1007 } 1008 } 1009 1010 #ifndef NDEBUG 1011 unsigned SignedEntries = 1012 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 1013 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 1014 "updates to CS and DFSInStack are out of sync"); 1015 assert(Info.getCS(true).size() == SignedEntries && 1016 "updates to CS and DFSInStack are out of sync"); 1017 #endif 1018 1019 for (Instruction *I : ToRemove) 1020 I->eraseFromParent(); 1021 return Changed; 1022 } 1023 1024 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 1025 FunctionAnalysisManager &AM) { 1026 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1027 if (!eliminateConstraints(F, DT)) 1028 return PreservedAnalyses::all(); 1029 1030 PreservedAnalyses PA; 1031 PA.preserve<DominatorTreeAnalysis>(); 1032 PA.preserveSet<CFGAnalyses>(); 1033 return PA; 1034 } 1035 1036 namespace { 1037 1038 class ConstraintElimination : public FunctionPass { 1039 public: 1040 static char ID; 1041 1042 ConstraintElimination() : FunctionPass(ID) { 1043 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 1044 } 1045 1046 bool runOnFunction(Function &F) override { 1047 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1048 return eliminateConstraints(F, DT); 1049 } 1050 1051 void getAnalysisUsage(AnalysisUsage &AU) const override { 1052 AU.setPreservesCFG(); 1053 AU.addRequired<DominatorTreeWrapperPass>(); 1054 AU.addPreserved<GlobalsAAWrapperPass>(); 1055 AU.addPreserved<DominatorTreeWrapperPass>(); 1056 } 1057 }; 1058 1059 } // end anonymous namespace 1060 1061 char ConstraintElimination::ID = 0; 1062 1063 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 1064 "Constraint Elimination", false, false) 1065 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1066 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 1067 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 1068 "Constraint Elimination", false, false) 1069 1070 FunctionPass *llvm::createConstraintEliminationPass() { 1071 return new ConstraintElimination(); 1072 } 1073