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