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