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/Instructions.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/DebugCounter.h" 31 #include "llvm/Transforms/Scalar.h" 32 33 #include <string> 34 35 using namespace llvm; 36 using namespace PatternMatch; 37 38 #define DEBUG_TYPE "constraint-elimination" 39 40 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 41 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 42 "Controls which conditions are eliminated"); 43 44 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 45 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 46 47 namespace { 48 49 /// Wrapper encapsulating separate constraint systems and corresponding value 50 /// mappings for both unsigned and signed information. Facts are added to and 51 /// conditions are checked against the corresponding system depending on the 52 /// signed-ness of their predicates. While the information is kept separate 53 /// based on signed-ness, certain conditions can be transferred between the two 54 /// systems. 55 class ConstraintInfo { 56 DenseMap<Value *, unsigned> UnsignedValue2Index; 57 DenseMap<Value *, unsigned> SignedValue2Index; 58 59 ConstraintSystem UnsignedCS; 60 ConstraintSystem SignedCS; 61 62 public: 63 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 64 return Signed ? SignedValue2Index : UnsignedValue2Index; 65 } 66 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 67 return Signed ? SignedValue2Index : UnsignedValue2Index; 68 } 69 70 ConstraintSystem &getCS(bool Signed) { 71 return Signed ? SignedCS : UnsignedCS; 72 } 73 const ConstraintSystem &getCS(bool Signed) const { 74 return Signed ? SignedCS : UnsignedCS; 75 } 76 77 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 78 }; 79 80 /// Struct to express a pre-condition of the form %Op0 Pred %Op1. 81 struct PreconditionTy { 82 CmpInst::Predicate Pred; 83 Value *Op0; 84 Value *Op1; 85 86 PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 87 : Pred(Pred), Op0(Op0), Op1(Op1) {} 88 }; 89 90 struct ConstraintTy { 91 SmallVector<int64_t, 8> Coefficients; 92 SmallVector<PreconditionTy, 2> Preconditions; 93 94 bool IsSigned = false; 95 bool IsEq = false; 96 97 ConstraintTy() = default; 98 99 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned) 100 : Coefficients(Coefficients), IsSigned(IsSigned) {} 101 102 unsigned size() const { return Coefficients.size(); } 103 104 unsigned empty() const { return Coefficients.empty(); } 105 106 /// Returns true if any constraint has a non-zero coefficient for any of the 107 /// newly added indices. Zero coefficients for new indices are removed. If it 108 /// returns true, no new variable need to be added to the system. 109 bool needsNewIndices(const DenseMap<Value *, unsigned> &NewIndices) { 110 for (unsigned I = 0; I < NewIndices.size(); ++I) { 111 int64_t Last = Coefficients.pop_back_val(); 112 if (Last != 0) 113 return true; 114 } 115 return false; 116 } 117 118 /// Returns true if all preconditions for this list of constraints are 119 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 120 bool isValid(const ConstraintInfo &Info) const; 121 122 /// Returns true if there is exactly one constraint in the list and isValid is 123 /// also true. 124 bool isValidSingle(const ConstraintInfo &Info) const { 125 if (size() != 1) 126 return false; 127 return isValid(Info); 128 } 129 }; 130 131 } // namespace 132 133 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The 134 // sum of the pairs equals \p V. The first pair is the constant-factor and X 135 // must be nullptr. If the expression cannot be decomposed, returns an empty 136 // vector. 137 static SmallVector<std::pair<int64_t, Value *>, 4> 138 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions, 139 bool IsSigned) { 140 141 // Decompose \p V used with a signed predicate. 142 if (IsSigned) { 143 if (auto *CI = dyn_cast<ConstantInt>(V)) { 144 const APInt &Val = CI->getValue(); 145 if (Val.sle(MinSignedConstraintValue) || Val.sge(MaxConstraintValue)) 146 return {}; 147 return {{CI->getSExtValue(), nullptr}}; 148 } 149 150 return {{0, nullptr}, {1, V}}; 151 } 152 153 if (auto *CI = dyn_cast<ConstantInt>(V)) { 154 if (CI->isNegative() || CI->uge(MaxConstraintValue)) 155 return {}; 156 return {{CI->getSExtValue(), nullptr}}; 157 } 158 auto *GEP = dyn_cast<GetElementPtrInst>(V); 159 if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) { 160 Value *Op0, *Op1; 161 ConstantInt *CI; 162 163 // If the index is zero-extended, it is guaranteed to be positive. 164 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 165 m_ZExt(m_Value(Op0)))) { 166 if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI)))) 167 return {{0, nullptr}, 168 {1, GEP->getPointerOperand()}, 169 {std::pow(int64_t(2), CI->getSExtValue()), Op1}}; 170 if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI)))) 171 return {{CI->getSExtValue(), nullptr}, 172 {1, GEP->getPointerOperand()}, 173 {1, Op1}}; 174 return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 175 } 176 177 if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) && 178 !CI->isNegative()) 179 return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}}; 180 181 SmallVector<std::pair<int64_t, Value *>, 4> Result; 182 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 183 m_NUWShl(m_Value(Op0), m_ConstantInt(CI)))) 184 Result = {{0, nullptr}, 185 {1, GEP->getPointerOperand()}, 186 {std::pow(int64_t(2), CI->getSExtValue()), Op0}}; 187 else if (match(GEP->getOperand(GEP->getNumOperands() - 1), 188 m_NSWAdd(m_Value(Op0), m_ConstantInt(CI)))) 189 Result = {{CI->getSExtValue(), nullptr}, 190 {1, GEP->getPointerOperand()}, 191 {1, Op0}}; 192 else { 193 Op0 = GEP->getOperand(GEP->getNumOperands() - 1); 194 Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 195 } 196 // If Op0 is signed non-negative, the GEP is increasing monotonically and 197 // can be de-composed. 198 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 199 ConstantInt::get(Op0->getType(), 0)); 200 return Result; 201 } 202 203 Value *Op0; 204 if (match(V, m_ZExt(m_Value(Op0)))) 205 V = Op0; 206 207 Value *Op1; 208 ConstantInt *CI; 209 if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI)))) 210 return {{CI->getSExtValue(), nullptr}, {1, Op0}}; 211 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative()) { 212 Preconditions.emplace_back( 213 CmpInst::ICMP_UGE, Op0, 214 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 215 return {{CI->getSExtValue(), nullptr}, {1, Op0}}; 216 } 217 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) 218 return {{0, nullptr}, {1, Op0}, {1, Op1}}; 219 220 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI)))) 221 return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}}; 222 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 223 return {{0, nullptr}, {1, Op0}, {-1, Op1}}; 224 225 return {{0, nullptr}, {1, V}}; 226 } 227 228 /// Turn a condition \p CmpI into a vector of constraints, using indices from \p 229 /// Value2Index. Additional indices for newly discovered values are added to \p 230 /// NewIndices. 231 static ConstraintTy 232 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 233 const DenseMap<Value *, unsigned> &Value2Index, 234 DenseMap<Value *, unsigned> &NewIndices) { 235 bool IsEq = false; 236 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 237 switch (Pred) { 238 case CmpInst::ICMP_UGT: 239 case CmpInst::ICMP_UGE: 240 case CmpInst::ICMP_SGT: 241 case CmpInst::ICMP_SGE: { 242 Pred = CmpInst::getSwappedPredicate(Pred); 243 std::swap(Op0, Op1); 244 break; 245 } 246 case CmpInst::ICMP_EQ: 247 if (match(Op1, m_Zero())) { 248 Pred = CmpInst::ICMP_ULE; 249 } else { 250 IsEq = true; 251 Pred = CmpInst::ICMP_ULE; 252 } 253 break; 254 case CmpInst::ICMP_NE: 255 if (!match(Op1, m_Zero())) 256 return {}; 257 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 258 std::swap(Op0, Op1); 259 break; 260 default: 261 break; 262 } 263 264 // Only ULE and ULT predicates are supported at the moment. 265 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 266 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 267 return {}; 268 269 SmallVector<PreconditionTy, 4> Preconditions; 270 bool IsSigned = CmpInst::isSigned(Pred); 271 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 272 Preconditions, IsSigned); 273 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 274 Preconditions, IsSigned); 275 // Skip if decomposing either of the values failed. 276 if (ADec.empty() || BDec.empty()) 277 return {}; 278 279 // Skip trivial constraints without any variables. 280 if (ADec.size() == 1 && BDec.size() == 1) 281 return {}; 282 283 int64_t Offset1 = ADec[0].first; 284 int64_t Offset2 = BDec[0].first; 285 Offset1 *= -1; 286 287 // Create iterator ranges that skip the constant-factor. 288 auto VariablesA = llvm::drop_begin(ADec); 289 auto VariablesB = llvm::drop_begin(BDec); 290 291 // First try to look up \p V in Value2Index and NewIndices. Otherwise add a 292 // new entry to NewIndices. 293 auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned { 294 auto V2I = Value2Index.find(V); 295 if (V2I != Value2Index.end()) 296 return V2I->second; 297 auto Insert = 298 NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1}); 299 return Insert.first->second; 300 }; 301 302 // Make sure all variables have entries in Value2Index or NewIndices. 303 for (const auto &KV : 304 concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB)) 305 GetOrAddIndex(KV.second); 306 307 // Build result constraint, by first adding all coefficients from A and then 308 // subtracting all coefficients from B. 309 ConstraintTy Res( 310 SmallVector<int64_t, 8>(Value2Index.size() + NewIndices.size() + 1, 0), 311 IsSigned); 312 Res.IsEq = IsEq; 313 auto &R = Res.Coefficients; 314 for (const auto &KV : VariablesA) 315 R[GetOrAddIndex(KV.second)] += KV.first; 316 317 for (const auto &KV : VariablesB) 318 R[GetOrAddIndex(KV.second)] -= KV.first; 319 320 R[0] = Offset1 + Offset2 + 321 (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT) ? -1 : 0); 322 Res.Preconditions = std::move(Preconditions); 323 return Res; 324 } 325 326 static ConstraintTy getConstraint(CmpInst *Cmp, ConstraintInfo &Info, 327 DenseMap<Value *, unsigned> &NewIndices) { 328 return getConstraint( 329 Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1), 330 Info.getValue2Index(CmpInst::isSigned(Cmp->getPredicate())), NewIndices); 331 } 332 333 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 334 return Coefficients.size() > 0 && 335 all_of(Preconditions, [&Info](const PreconditionTy &C) { 336 DenseMap<Value *, unsigned> NewIndices; 337 auto R = getConstraint( 338 C.Pred, C.Op0, C.Op1, 339 Info.getValue2Index(CmpInst::isSigned(C.Pred)), NewIndices); 340 // TODO: properly check NewIndices. 341 return NewIndices.empty() && R.Preconditions.empty() && !R.IsEq && 342 R.size() >= 2 && 343 Info.getCS(CmpInst::isSigned(C.Pred)) 344 .isConditionImplied(R.Coefficients); 345 }); 346 } 347 348 namespace { 349 /// Represents either a condition that holds on entry to a block or a basic 350 /// block, with their respective Dominator DFS in and out numbers. 351 struct ConstraintOrBlock { 352 unsigned NumIn; 353 unsigned NumOut; 354 bool IsBlock; 355 bool Not; 356 union { 357 BasicBlock *BB; 358 CmpInst *Condition; 359 }; 360 361 ConstraintOrBlock(DomTreeNode *DTN) 362 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 363 BB(DTN->getBlock()) {} 364 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 365 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 366 Not(Not), Condition(Condition) {} 367 }; 368 369 struct StackEntry { 370 unsigned NumIn; 371 unsigned NumOut; 372 Instruction *Condition; 373 bool IsNot; 374 bool IsSigned = false; 375 376 StackEntry(unsigned NumIn, unsigned NumOut, Instruction *Condition, 377 bool IsNot, bool IsSigned) 378 : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot), 379 IsSigned(IsSigned) {} 380 }; 381 } // namespace 382 383 #ifndef NDEBUG 384 static void dumpWithNames(ConstraintTy &C, 385 DenseMap<Value *, unsigned> &Value2Index) { 386 SmallVector<std::string> Names(Value2Index.size(), ""); 387 for (auto &KV : Value2Index) { 388 Names[KV.second - 1] = std::string("%") + KV.first->getName().str(); 389 } 390 ConstraintSystem CS; 391 CS.addVariableRowFill(C.Coefficients); 392 CS.dump(Names); 393 } 394 #endif 395 396 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 397 bool Changed = false; 398 DT.updateDFSNumbers(); 399 400 ConstraintInfo Info; 401 402 SmallVector<ConstraintOrBlock, 64> WorkList; 403 404 // First, collect conditions implied by branches and blocks with their 405 // Dominator DFS in and out numbers. 406 for (BasicBlock &BB : F) { 407 if (!DT.getNode(&BB)) 408 continue; 409 WorkList.emplace_back(DT.getNode(&BB)); 410 411 // True as long as long as the current instruction is guaranteed to execute. 412 bool GuaranteedToExecute = true; 413 // Scan BB for assume calls. 414 // TODO: also use this scan to queue conditions to simplify, so we can 415 // interleave facts from assumes and conditions to simplify in a single 416 // basic block. And to skip another traversal of each basic block when 417 // simplifying. 418 for (Instruction &I : BB) { 419 Value *Cond; 420 // For now, just handle assumes with a single compare as condition. 421 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 422 isa<ICmpInst>(Cond)) { 423 if (GuaranteedToExecute) { 424 // The assume is guaranteed to execute when BB is entered, hence Cond 425 // holds on entry to BB. 426 WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false); 427 } else { 428 // Otherwise the condition only holds in the successors. 429 for (BasicBlock *Succ : successors(&BB)) 430 WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), 431 false); 432 } 433 } 434 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 435 } 436 437 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 438 if (!Br || !Br->isConditional()) 439 continue; 440 441 // Returns true if we can add a known condition from BB to its successor 442 // block Succ. Each predecessor of Succ can either be BB or be dominated by 443 // Succ (e.g. the case when adding a condition from a pre-header to a loop 444 // header). 445 auto CanAdd = [&BB, &DT](BasicBlock *Succ) { 446 assert(isa<BranchInst>(BB.getTerminator())); 447 return any_of(successors(&BB), 448 [Succ](const BasicBlock *S) { return S != Succ; }) && 449 all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) { 450 return Pred == &BB || DT.dominates(Succ, Pred); 451 }); 452 }; 453 // If the condition is an OR of 2 compares and the false successor only has 454 // the current block as predecessor, queue both negated conditions for the 455 // false successor. 456 Value *Op0, *Op1; 457 if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) && 458 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 459 BasicBlock *FalseSuccessor = Br->getSuccessor(1); 460 if (CanAdd(FalseSuccessor)) { 461 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0), 462 true); 463 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1), 464 true); 465 } 466 continue; 467 } 468 469 // If the condition is an AND of 2 compares and the true successor only has 470 // the current block as predecessor, queue both conditions for the true 471 // successor. 472 if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) && 473 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 474 BasicBlock *TrueSuccessor = Br->getSuccessor(0); 475 if (CanAdd(TrueSuccessor)) { 476 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0), 477 false); 478 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1), 479 false); 480 } 481 continue; 482 } 483 484 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 485 if (!CmpI) 486 continue; 487 if (CanAdd(Br->getSuccessor(0))) 488 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 489 if (CanAdd(Br->getSuccessor(1))) 490 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 491 } 492 493 // Next, sort worklist by dominance, so that dominating blocks and conditions 494 // come before blocks and conditions dominated by them. If a block and a 495 // condition have the same numbers, the condition comes before the block, as 496 // it holds on entry to the block. 497 sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 498 return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock); 499 }); 500 501 // Finally, process ordered worklist and eliminate implied conditions. 502 SmallVector<StackEntry, 16> DFSInStack; 503 for (ConstraintOrBlock &CB : WorkList) { 504 // First, pop entries from the stack that are out-of-scope for CB. Remove 505 // the corresponding entry from the constraint system. 506 while (!DFSInStack.empty()) { 507 auto &E = DFSInStack.back(); 508 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 509 << "\n"); 510 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 511 assert(E.NumIn <= CB.NumIn); 512 if (CB.NumOut <= E.NumOut) 513 break; 514 LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot 515 << "\n"); 516 DFSInStack.pop_back(); 517 Info.popLastConstraint(E.IsSigned); 518 } 519 520 LLVM_DEBUG({ 521 dbgs() << "Processing "; 522 if (CB.IsBlock) 523 dbgs() << *CB.BB; 524 else 525 dbgs() << *CB.Condition; 526 dbgs() << "\n"; 527 }); 528 529 // For a block, check if any CmpInsts become known based on the current set 530 // of constraints. 531 if (CB.IsBlock) { 532 for (Instruction &I : *CB.BB) { 533 auto *Cmp = dyn_cast<ICmpInst>(&I); 534 if (!Cmp) 535 continue; 536 537 DenseMap<Value *, unsigned> NewIndices; 538 auto R = getConstraint(Cmp, Info, NewIndices); 539 if (R.IsEq || R.size() < 2 || R.needsNewIndices(NewIndices) || 540 !R.isValid(Info)) 541 continue; 542 543 auto &CSToUse = Info.getCS(R.IsSigned); 544 if (CSToUse.isConditionImplied(R.Coefficients)) { 545 if (!DebugCounter::shouldExecute(EliminatedCounter)) 546 continue; 547 548 LLVM_DEBUG(dbgs() << "Condition " << *Cmp 549 << " implied by dominating constraints\n"); 550 LLVM_DEBUG({ 551 for (auto &E : reverse(DFSInStack)) 552 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 553 }); 554 Cmp->replaceUsesWithIf( 555 ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) { 556 // Conditions in an assume trivially simplify to true. Skip uses 557 // in assume calls to not destroy the available information. 558 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 559 return !II || II->getIntrinsicID() != Intrinsic::assume; 560 }); 561 NumCondsRemoved++; 562 Changed = true; 563 } 564 if (CSToUse.isConditionImplied( 565 ConstraintSystem::negate(R.Coefficients))) { 566 if (!DebugCounter::shouldExecute(EliminatedCounter)) 567 continue; 568 569 LLVM_DEBUG(dbgs() << "Condition !" << *Cmp 570 << " implied by dominating constraints\n"); 571 LLVM_DEBUG({ 572 for (auto &E : reverse(DFSInStack)) 573 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 574 }); 575 Cmp->replaceAllUsesWith( 576 ConstantInt::getFalse(F.getParent()->getContext())); 577 NumCondsRemoved++; 578 Changed = true; 579 } 580 } 581 continue; 582 } 583 584 // Set up a function to restore the predicate at the end of the scope if it 585 // has been negated. Negate the predicate in-place, if required. 586 auto *CI = dyn_cast<ICmpInst>(CB.Condition); 587 auto PredicateRestorer = make_scope_exit([CI, &CB]() { 588 if (CB.Not && CI) 589 CI->setPredicate(CI->getInversePredicate()); 590 }); 591 if (CB.Not) { 592 if (CI) { 593 CI->setPredicate(CI->getInversePredicate()); 594 } else { 595 LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n"); 596 continue; 597 } 598 } 599 600 // Otherwise, add the condition to the system and stack, if we can transform 601 // it into a constraint. 602 DenseMap<Value *, unsigned> NewIndices; 603 auto R = getConstraint(CB.Condition, Info, NewIndices); 604 if (!R.isValid(Info)) 605 continue; 606 607 for (auto &KV : NewIndices) 608 Info.getValue2Index(CmpInst::isSigned(CB.Condition->getPredicate())) 609 .insert(KV); 610 611 LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n"); 612 bool Added = false; 613 assert(CmpInst::isSigned(CB.Condition->getPredicate()) == R.IsSigned && 614 "condition and constraint signs must match"); 615 auto &CSToUse = Info.getCS(R.IsSigned); 616 if (R.Coefficients.empty()) 617 continue; 618 619 Added |= CSToUse.addVariableRowFill(R.Coefficients); 620 621 // If R has been added to the system, queue it for removal once it goes 622 // out-of-scope. 623 if (Added) { 624 for (auto &KV : NewIndices) 625 Info.getValue2Index(R.IsSigned).insert(KV); 626 627 LLVM_DEBUG({ 628 dbgs() << " constraint: "; 629 dumpWithNames(R, Info.getValue2Index(R.IsSigned)); 630 }); 631 632 DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not, 633 R.IsSigned); 634 635 if (R.IsEq) { 636 // Also add the inverted constraint for equality constraints. 637 for (auto &Coeff : R.Coefficients) 638 Coeff *= -1; 639 CSToUse.addVariableRowFill(R.Coefficients); 640 641 DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not, 642 R.IsSigned); 643 } 644 } 645 } 646 647 #ifndef NDEBUG 648 unsigned SignedEntries = 649 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 650 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 651 "updates to CS and DFSInStack are out of sync"); 652 assert(Info.getCS(true).size() == SignedEntries && 653 "updates to CS and DFSInStack are out of sync"); 654 #endif 655 656 return Changed; 657 } 658 659 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 660 FunctionAnalysisManager &AM) { 661 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 662 if (!eliminateConstraints(F, DT)) 663 return PreservedAnalyses::all(); 664 665 PreservedAnalyses PA; 666 PA.preserve<DominatorTreeAnalysis>(); 667 PA.preserveSet<CFGAnalyses>(); 668 return PA; 669 } 670 671 namespace { 672 673 class ConstraintElimination : public FunctionPass { 674 public: 675 static char ID; 676 677 ConstraintElimination() : FunctionPass(ID) { 678 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 679 } 680 681 bool runOnFunction(Function &F) override { 682 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 683 return eliminateConstraints(F, DT); 684 } 685 686 void getAnalysisUsage(AnalysisUsage &AU) const override { 687 AU.setPreservesCFG(); 688 AU.addRequired<DominatorTreeWrapperPass>(); 689 AU.addPreserved<GlobalsAAWrapperPass>(); 690 AU.addPreserved<DominatorTreeWrapperPass>(); 691 } 692 }; 693 694 } // end anonymous namespace 695 696 char ConstraintElimination::ID = 0; 697 698 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 699 "Constraint Elimination", false, false) 700 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 701 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 702 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 703 "Constraint Elimination", false, false) 704 705 FunctionPass *llvm::createConstraintEliminationPass() { 706 return new ConstraintElimination(); 707 } 708