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