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