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