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