1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===// 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 // This transformation analyzes and transforms the induction variables (and 10 // computations derived from them) into forms suitable for efficient execution 11 // on the target. 12 // 13 // This pass performs a strength reduction on array references inside loops that 14 // have as one or more of their components the loop induction variable, it 15 // rewrites expressions to take advantage of scaled-index addressing modes 16 // available on the target, and it performs a variety of other optimizations 17 // related to loop induction variables. 18 // 19 // Terminology note: this code has a lot of handling for "post-increment" or 20 // "post-inc" users. This is not talking about post-increment addressing modes; 21 // it is instead talking about code like this: 22 // 23 // %i = phi [ 0, %entry ], [ %i.next, %latch ] 24 // ... 25 // %i.next = add %i, 1 26 // %c = icmp eq %i.next, %n 27 // 28 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however 29 // it's useful to think about these as the same register, with some uses using 30 // the value of the register before the add and some using it after. In this 31 // example, the icmp is a post-increment user, since it uses %i.next, which is 32 // the value of the induction variable after the increment. The other common 33 // case of post-increment users is users outside the loop. 34 // 35 // TODO: More sophistication in the way Formulae are generated and filtered. 36 // 37 // TODO: Handle multiple loops at a time. 38 // 39 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead 40 // of a GlobalValue? 41 // 42 // TODO: When truncation is free, truncate ICmp users' operands to make it a 43 // smaller encoding (on x86 at least). 44 // 45 // TODO: When a negated register is used by an add (such as in a list of 46 // multiple base registers, or as the increment expression in an addrec), 47 // we may not actually need both reg and (-1 * reg) in registers; the 48 // negation can be implemented by using a sub instead of an add. The 49 // lack of support for taking this into consideration when making 50 // register pressure decisions is partly worked around by the "Special" 51 // use kind. 52 // 53 //===----------------------------------------------------------------------===// 54 55 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 56 #include "llvm/ADT/APInt.h" 57 #include "llvm/ADT/DenseMap.h" 58 #include "llvm/ADT/DenseSet.h" 59 #include "llvm/ADT/Hashing.h" 60 #include "llvm/ADT/PointerIntPair.h" 61 #include "llvm/ADT/STLExtras.h" 62 #include "llvm/ADT/SetVector.h" 63 #include "llvm/ADT/SmallBitVector.h" 64 #include "llvm/ADT/SmallPtrSet.h" 65 #include "llvm/ADT/SmallSet.h" 66 #include "llvm/ADT/SmallVector.h" 67 #include "llvm/ADT/iterator_range.h" 68 #include "llvm/Analysis/AssumptionCache.h" 69 #include "llvm/Analysis/IVUsers.h" 70 #include "llvm/Analysis/LoopAnalysisManager.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/LoopPass.h" 73 #include "llvm/Analysis/MemorySSA.h" 74 #include "llvm/Analysis/MemorySSAUpdater.h" 75 #include "llvm/Analysis/ScalarEvolution.h" 76 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 77 #include "llvm/Analysis/ScalarEvolutionNormalization.h" 78 #include "llvm/Analysis/TargetLibraryInfo.h" 79 #include "llvm/Analysis/TargetTransformInfo.h" 80 #include "llvm/Analysis/ValueTracking.h" 81 #include "llvm/BinaryFormat/Dwarf.h" 82 #include "llvm/Config/llvm-config.h" 83 #include "llvm/IR/BasicBlock.h" 84 #include "llvm/IR/Constant.h" 85 #include "llvm/IR/Constants.h" 86 #include "llvm/IR/DebugInfoMetadata.h" 87 #include "llvm/IR/DerivedTypes.h" 88 #include "llvm/IR/Dominators.h" 89 #include "llvm/IR/GlobalValue.h" 90 #include "llvm/IR/IRBuilder.h" 91 #include "llvm/IR/InstrTypes.h" 92 #include "llvm/IR/Instruction.h" 93 #include "llvm/IR/Instructions.h" 94 #include "llvm/IR/IntrinsicInst.h" 95 #include "llvm/IR/Module.h" 96 #include "llvm/IR/Operator.h" 97 #include "llvm/IR/PassManager.h" 98 #include "llvm/IR/Type.h" 99 #include "llvm/IR/Use.h" 100 #include "llvm/IR/User.h" 101 #include "llvm/IR/Value.h" 102 #include "llvm/IR/ValueHandle.h" 103 #include "llvm/InitializePasses.h" 104 #include "llvm/Pass.h" 105 #include "llvm/Support/Casting.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MathExtras.h" 111 #include "llvm/Support/raw_ostream.h" 112 #include "llvm/Transforms/Scalar.h" 113 #include "llvm/Transforms/Utils.h" 114 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 115 #include "llvm/Transforms/Utils/Local.h" 116 #include "llvm/Transforms/Utils/LoopUtils.h" 117 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 118 #include <algorithm> 119 #include <cassert> 120 #include <cstddef> 121 #include <cstdint> 122 #include <iterator> 123 #include <limits> 124 #include <map> 125 #include <numeric> 126 #include <utility> 127 128 using namespace llvm; 129 130 #define DEBUG_TYPE "loop-reduce" 131 132 /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for 133 /// bail out. This threshold is far beyond the number of users that LSR can 134 /// conceivably solve, so it should not affect generated code, but catches the 135 /// worst cases before LSR burns too much compile time and stack space. 136 static const unsigned MaxIVUsers = 200; 137 138 /// Limit the size of expression that SCEV-based salvaging will attempt to 139 /// translate into a DIExpression. 140 /// Choose a maximum size such that debuginfo is not excessively increased and 141 /// the salvaging is not too expensive for the compiler. 142 static const unsigned MaxSCEVSalvageExpressionSize = 64; 143 144 // Cleanup congruent phis after LSR phi expansion. 145 static cl::opt<bool> EnablePhiElim( 146 "enable-lsr-phielim", cl::Hidden, cl::init(true), 147 cl::desc("Enable LSR phi elimination")); 148 149 // The flag adds instruction count to solutions cost comparision. 150 static cl::opt<bool> InsnsCost( 151 "lsr-insns-cost", cl::Hidden, cl::init(true), 152 cl::desc("Add instruction count to a LSR cost model")); 153 154 // Flag to choose how to narrow complex lsr solution 155 static cl::opt<bool> LSRExpNarrow( 156 "lsr-exp-narrow", cl::Hidden, cl::init(false), 157 cl::desc("Narrow LSR complex solution using" 158 " expectation of registers number")); 159 160 // Flag to narrow search space by filtering non-optimal formulae with 161 // the same ScaledReg and Scale. 162 static cl::opt<bool> FilterSameScaledReg( 163 "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true), 164 cl::desc("Narrow LSR search space by filtering non-optimal formulae" 165 " with the same ScaledReg and Scale")); 166 167 static cl::opt<TTI::AddressingModeKind> PreferredAddresingMode( 168 "lsr-preferred-addressing-mode", cl::Hidden, cl::init(TTI::AMK_None), 169 cl::desc("A flag that overrides the target's preferred addressing mode."), 170 cl::values(clEnumValN(TTI::AMK_None, 171 "none", 172 "Don't prefer any addressing mode"), 173 clEnumValN(TTI::AMK_PreIndexed, 174 "preindexed", 175 "Prefer pre-indexed addressing mode"), 176 clEnumValN(TTI::AMK_PostIndexed, 177 "postindexed", 178 "Prefer post-indexed addressing mode"))); 179 180 static cl::opt<unsigned> ComplexityLimit( 181 "lsr-complexity-limit", cl::Hidden, 182 cl::init(std::numeric_limits<uint16_t>::max()), 183 cl::desc("LSR search space complexity limit")); 184 185 static cl::opt<unsigned> SetupCostDepthLimit( 186 "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7), 187 cl::desc("The limit on recursion depth for LSRs setup cost")); 188 189 #ifndef NDEBUG 190 // Stress test IV chain generation. 191 static cl::opt<bool> StressIVChain( 192 "stress-ivchain", cl::Hidden, cl::init(false), 193 cl::desc("Stress test LSR IV chains")); 194 #else 195 static bool StressIVChain = false; 196 #endif 197 198 namespace { 199 200 struct MemAccessTy { 201 /// Used in situations where the accessed memory type is unknown. 202 static const unsigned UnknownAddressSpace = 203 std::numeric_limits<unsigned>::max(); 204 205 Type *MemTy = nullptr; 206 unsigned AddrSpace = UnknownAddressSpace; 207 208 MemAccessTy() = default; 209 MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {} 210 211 bool operator==(MemAccessTy Other) const { 212 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace; 213 } 214 215 bool operator!=(MemAccessTy Other) const { return !(*this == Other); } 216 217 static MemAccessTy getUnknown(LLVMContext &Ctx, 218 unsigned AS = UnknownAddressSpace) { 219 return MemAccessTy(Type::getVoidTy(Ctx), AS); 220 } 221 222 Type *getType() { return MemTy; } 223 }; 224 225 /// This class holds data which is used to order reuse candidates. 226 class RegSortData { 227 public: 228 /// This represents the set of LSRUse indices which reference 229 /// a particular register. 230 SmallBitVector UsedByIndices; 231 232 void print(raw_ostream &OS) const; 233 void dump() const; 234 }; 235 236 } // end anonymous namespace 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 void RegSortData::print(raw_ostream &OS) const { 240 OS << "[NumUses=" << UsedByIndices.count() << ']'; 241 } 242 243 LLVM_DUMP_METHOD void RegSortData::dump() const { 244 print(errs()); errs() << '\n'; 245 } 246 #endif 247 248 namespace { 249 250 /// Map register candidates to information about how they are used. 251 class RegUseTracker { 252 using RegUsesTy = DenseMap<const SCEV *, RegSortData>; 253 254 RegUsesTy RegUsesMap; 255 SmallVector<const SCEV *, 16> RegSequence; 256 257 public: 258 void countRegister(const SCEV *Reg, size_t LUIdx); 259 void dropRegister(const SCEV *Reg, size_t LUIdx); 260 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx); 261 262 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const; 263 264 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const; 265 266 void clear(); 267 268 using iterator = SmallVectorImpl<const SCEV *>::iterator; 269 using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator; 270 271 iterator begin() { return RegSequence.begin(); } 272 iterator end() { return RegSequence.end(); } 273 const_iterator begin() const { return RegSequence.begin(); } 274 const_iterator end() const { return RegSequence.end(); } 275 }; 276 277 } // end anonymous namespace 278 279 void 280 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) { 281 std::pair<RegUsesTy::iterator, bool> Pair = 282 RegUsesMap.insert(std::make_pair(Reg, RegSortData())); 283 RegSortData &RSD = Pair.first->second; 284 if (Pair.second) 285 RegSequence.push_back(Reg); 286 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1)); 287 RSD.UsedByIndices.set(LUIdx); 288 } 289 290 void 291 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) { 292 RegUsesTy::iterator It = RegUsesMap.find(Reg); 293 assert(It != RegUsesMap.end()); 294 RegSortData &RSD = It->second; 295 assert(RSD.UsedByIndices.size() > LUIdx); 296 RSD.UsedByIndices.reset(LUIdx); 297 } 298 299 void 300 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) { 301 assert(LUIdx <= LastLUIdx); 302 303 // Update RegUses. The data structure is not optimized for this purpose; 304 // we must iterate through it and update each of the bit vectors. 305 for (auto &Pair : RegUsesMap) { 306 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices; 307 if (LUIdx < UsedByIndices.size()) 308 UsedByIndices[LUIdx] = 309 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false; 310 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx)); 311 } 312 } 313 314 bool 315 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const { 316 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 317 if (I == RegUsesMap.end()) 318 return false; 319 const SmallBitVector &UsedByIndices = I->second.UsedByIndices; 320 int i = UsedByIndices.find_first(); 321 if (i == -1) return false; 322 if ((size_t)i != LUIdx) return true; 323 return UsedByIndices.find_next(i) != -1; 324 } 325 326 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const { 327 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 328 assert(I != RegUsesMap.end() && "Unknown register!"); 329 return I->second.UsedByIndices; 330 } 331 332 void RegUseTracker::clear() { 333 RegUsesMap.clear(); 334 RegSequence.clear(); 335 } 336 337 namespace { 338 339 /// This class holds information that describes a formula for computing 340 /// satisfying a use. It may include broken-out immediates and scaled registers. 341 struct Formula { 342 /// Global base address used for complex addressing. 343 GlobalValue *BaseGV = nullptr; 344 345 /// Base offset for complex addressing. 346 int64_t BaseOffset = 0; 347 348 /// Whether any complex addressing has a base register. 349 bool HasBaseReg = false; 350 351 /// The scale of any complex addressing. 352 int64_t Scale = 0; 353 354 /// The list of "base" registers for this use. When this is non-empty. The 355 /// canonical representation of a formula is 356 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and 357 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty(). 358 /// 3. The reg containing recurrent expr related with currect loop in the 359 /// formula should be put in the ScaledReg. 360 /// #1 enforces that the scaled register is always used when at least two 361 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2. 362 /// #2 enforces that 1 * reg is reg. 363 /// #3 ensures invariant regs with respect to current loop can be combined 364 /// together in LSR codegen. 365 /// This invariant can be temporarily broken while building a formula. 366 /// However, every formula inserted into the LSRInstance must be in canonical 367 /// form. 368 SmallVector<const SCEV *, 4> BaseRegs; 369 370 /// The 'scaled' register for this use. This should be non-null when Scale is 371 /// not zero. 372 const SCEV *ScaledReg = nullptr; 373 374 /// An additional constant offset which added near the use. This requires a 375 /// temporary register, but the offset itself can live in an add immediate 376 /// field rather than a register. 377 int64_t UnfoldedOffset = 0; 378 379 Formula() = default; 380 381 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE); 382 383 bool isCanonical(const Loop &L) const; 384 385 void canonicalize(const Loop &L); 386 387 bool unscale(); 388 389 bool hasZeroEnd() const; 390 391 size_t getNumRegs() const; 392 Type *getType() const; 393 394 void deleteBaseReg(const SCEV *&S); 395 396 bool referencesReg(const SCEV *S) const; 397 bool hasRegsUsedByUsesOtherThan(size_t LUIdx, 398 const RegUseTracker &RegUses) const; 399 400 void print(raw_ostream &OS) const; 401 void dump() const; 402 }; 403 404 } // end anonymous namespace 405 406 /// Recursion helper for initialMatch. 407 static void DoInitialMatch(const SCEV *S, Loop *L, 408 SmallVectorImpl<const SCEV *> &Good, 409 SmallVectorImpl<const SCEV *> &Bad, 410 ScalarEvolution &SE) { 411 // Collect expressions which properly dominate the loop header. 412 if (SE.properlyDominates(S, L->getHeader())) { 413 Good.push_back(S); 414 return; 415 } 416 417 // Look at add operands. 418 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 419 for (const SCEV *S : Add->operands()) 420 DoInitialMatch(S, L, Good, Bad, SE); 421 return; 422 } 423 424 // Look at addrec operands. 425 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 426 if (!AR->getStart()->isZero() && AR->isAffine()) { 427 DoInitialMatch(AR->getStart(), L, Good, Bad, SE); 428 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0), 429 AR->getStepRecurrence(SE), 430 // FIXME: AR->getNoWrapFlags() 431 AR->getLoop(), SCEV::FlagAnyWrap), 432 L, Good, Bad, SE); 433 return; 434 } 435 436 // Handle a multiplication by -1 (negation) if it didn't fold. 437 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) 438 if (Mul->getOperand(0)->isAllOnesValue()) { 439 SmallVector<const SCEV *, 4> Ops(drop_begin(Mul->operands())); 440 const SCEV *NewMul = SE.getMulExpr(Ops); 441 442 SmallVector<const SCEV *, 4> MyGood; 443 SmallVector<const SCEV *, 4> MyBad; 444 DoInitialMatch(NewMul, L, MyGood, MyBad, SE); 445 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue( 446 SE.getEffectiveSCEVType(NewMul->getType()))); 447 for (const SCEV *S : MyGood) 448 Good.push_back(SE.getMulExpr(NegOne, S)); 449 for (const SCEV *S : MyBad) 450 Bad.push_back(SE.getMulExpr(NegOne, S)); 451 return; 452 } 453 454 // Ok, we can't do anything interesting. Just stuff the whole thing into a 455 // register and hope for the best. 456 Bad.push_back(S); 457 } 458 459 /// Incorporate loop-variant parts of S into this Formula, attempting to keep 460 /// all loop-invariant and loop-computable values in a single base register. 461 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) { 462 SmallVector<const SCEV *, 4> Good; 463 SmallVector<const SCEV *, 4> Bad; 464 DoInitialMatch(S, L, Good, Bad, SE); 465 if (!Good.empty()) { 466 const SCEV *Sum = SE.getAddExpr(Good); 467 if (!Sum->isZero()) 468 BaseRegs.push_back(Sum); 469 HasBaseReg = true; 470 } 471 if (!Bad.empty()) { 472 const SCEV *Sum = SE.getAddExpr(Bad); 473 if (!Sum->isZero()) 474 BaseRegs.push_back(Sum); 475 HasBaseReg = true; 476 } 477 canonicalize(*L); 478 } 479 480 static bool containsAddRecDependentOnLoop(const SCEV *S, const Loop &L) { 481 return SCEVExprContains(S, [&L](const SCEV *S) { 482 return isa<SCEVAddRecExpr>(S) && (cast<SCEVAddRecExpr>(S)->getLoop() == &L); 483 }); 484 } 485 486 /// Check whether or not this formula satisfies the canonical 487 /// representation. 488 /// \see Formula::BaseRegs. 489 bool Formula::isCanonical(const Loop &L) const { 490 if (!ScaledReg) 491 return BaseRegs.size() <= 1; 492 493 if (Scale != 1) 494 return true; 495 496 if (Scale == 1 && BaseRegs.empty()) 497 return false; 498 499 if (containsAddRecDependentOnLoop(ScaledReg, L)) 500 return true; 501 502 // If ScaledReg is not a recurrent expr, or it is but its loop is not current 503 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current 504 // loop, we want to swap the reg in BaseRegs with ScaledReg. 505 return none_of(BaseRegs, [&L](const SCEV *S) { 506 return containsAddRecDependentOnLoop(S, L); 507 }); 508 } 509 510 /// Helper method to morph a formula into its canonical representation. 511 /// \see Formula::BaseRegs. 512 /// Every formula having more than one base register, must use the ScaledReg 513 /// field. Otherwise, we would have to do special cases everywhere in LSR 514 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ... 515 /// On the other hand, 1*reg should be canonicalized into reg. 516 void Formula::canonicalize(const Loop &L) { 517 if (isCanonical(L)) 518 return; 519 520 if (BaseRegs.empty()) { 521 // No base reg? Use scale reg with scale = 1 as such. 522 assert(ScaledReg && "Expected 1*reg => reg"); 523 assert(Scale == 1 && "Expected 1*reg => reg"); 524 BaseRegs.push_back(ScaledReg); 525 Scale = 0; 526 ScaledReg = nullptr; 527 return; 528 } 529 530 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg. 531 if (!ScaledReg) { 532 ScaledReg = BaseRegs.pop_back_val(); 533 Scale = 1; 534 } 535 536 // If ScaledReg is an invariant with respect to L, find the reg from 537 // BaseRegs containing the recurrent expr related with Loop L. Swap the 538 // reg with ScaledReg. 539 if (!containsAddRecDependentOnLoop(ScaledReg, L)) { 540 auto I = find_if(BaseRegs, [&L](const SCEV *S) { 541 return containsAddRecDependentOnLoop(S, L); 542 }); 543 if (I != BaseRegs.end()) 544 std::swap(ScaledReg, *I); 545 } 546 assert(isCanonical(L) && "Failed to canonicalize?"); 547 } 548 549 /// Get rid of the scale in the formula. 550 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2. 551 /// \return true if it was possible to get rid of the scale, false otherwise. 552 /// \note After this operation the formula may not be in the canonical form. 553 bool Formula::unscale() { 554 if (Scale != 1) 555 return false; 556 Scale = 0; 557 BaseRegs.push_back(ScaledReg); 558 ScaledReg = nullptr; 559 return true; 560 } 561 562 bool Formula::hasZeroEnd() const { 563 if (UnfoldedOffset || BaseOffset) 564 return false; 565 if (BaseRegs.size() != 1 || ScaledReg) 566 return false; 567 return true; 568 } 569 570 /// Return the total number of register operands used by this formula. This does 571 /// not include register uses implied by non-constant addrec strides. 572 size_t Formula::getNumRegs() const { 573 return !!ScaledReg + BaseRegs.size(); 574 } 575 576 /// Return the type of this formula, if it has one, or null otherwise. This type 577 /// is meaningless except for the bit size. 578 Type *Formula::getType() const { 579 return !BaseRegs.empty() ? BaseRegs.front()->getType() : 580 ScaledReg ? ScaledReg->getType() : 581 BaseGV ? BaseGV->getType() : 582 nullptr; 583 } 584 585 /// Delete the given base reg from the BaseRegs list. 586 void Formula::deleteBaseReg(const SCEV *&S) { 587 if (&S != &BaseRegs.back()) 588 std::swap(S, BaseRegs.back()); 589 BaseRegs.pop_back(); 590 } 591 592 /// Test if this formula references the given register. 593 bool Formula::referencesReg(const SCEV *S) const { 594 return S == ScaledReg || is_contained(BaseRegs, S); 595 } 596 597 /// Test whether this formula uses registers which are used by uses other than 598 /// the use with the given index. 599 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx, 600 const RegUseTracker &RegUses) const { 601 if (ScaledReg) 602 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx)) 603 return true; 604 for (const SCEV *BaseReg : BaseRegs) 605 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx)) 606 return true; 607 return false; 608 } 609 610 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 611 void Formula::print(raw_ostream &OS) const { 612 bool First = true; 613 if (BaseGV) { 614 if (!First) OS << " + "; else First = false; 615 BaseGV->printAsOperand(OS, /*PrintType=*/false); 616 } 617 if (BaseOffset != 0) { 618 if (!First) OS << " + "; else First = false; 619 OS << BaseOffset; 620 } 621 for (const SCEV *BaseReg : BaseRegs) { 622 if (!First) OS << " + "; else First = false; 623 OS << "reg(" << *BaseReg << ')'; 624 } 625 if (HasBaseReg && BaseRegs.empty()) { 626 if (!First) OS << " + "; else First = false; 627 OS << "**error: HasBaseReg**"; 628 } else if (!HasBaseReg && !BaseRegs.empty()) { 629 if (!First) OS << " + "; else First = false; 630 OS << "**error: !HasBaseReg**"; 631 } 632 if (Scale != 0) { 633 if (!First) OS << " + "; else First = false; 634 OS << Scale << "*reg("; 635 if (ScaledReg) 636 OS << *ScaledReg; 637 else 638 OS << "<unknown>"; 639 OS << ')'; 640 } 641 if (UnfoldedOffset != 0) { 642 if (!First) OS << " + "; 643 OS << "imm(" << UnfoldedOffset << ')'; 644 } 645 } 646 647 LLVM_DUMP_METHOD void Formula::dump() const { 648 print(errs()); errs() << '\n'; 649 } 650 #endif 651 652 /// Return true if the given addrec can be sign-extended without changing its 653 /// value. 654 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 655 Type *WideTy = 656 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1); 657 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 658 } 659 660 /// Return true if the given add can be sign-extended without changing its 661 /// value. 662 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) { 663 Type *WideTy = 664 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1); 665 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy)); 666 } 667 668 /// Return true if the given mul can be sign-extended without changing its 669 /// value. 670 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) { 671 Type *WideTy = 672 IntegerType::get(SE.getContext(), 673 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands()); 674 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy)); 675 } 676 677 /// Return an expression for LHS /s RHS, if it can be determined and if the 678 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits 679 /// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that 680 /// the multiplication may overflow, which is useful when the result will be 681 /// used in a context where the most significant bits are ignored. 682 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS, 683 ScalarEvolution &SE, 684 bool IgnoreSignificantBits = false) { 685 // Handle the trivial case, which works for any SCEV type. 686 if (LHS == RHS) 687 return SE.getConstant(LHS->getType(), 1); 688 689 // Handle a few RHS special cases. 690 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS); 691 if (RC) { 692 const APInt &RA = RC->getAPInt(); 693 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do 694 // some folding. 695 if (RA.isAllOnes()) { 696 if (LHS->getType()->isPointerTy()) 697 return nullptr; 698 return SE.getMulExpr(LHS, RC); 699 } 700 // Handle x /s 1 as x. 701 if (RA == 1) 702 return LHS; 703 } 704 705 // Check for a division of a constant by a constant. 706 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) { 707 if (!RC) 708 return nullptr; 709 const APInt &LA = C->getAPInt(); 710 const APInt &RA = RC->getAPInt(); 711 if (LA.srem(RA) != 0) 712 return nullptr; 713 return SE.getConstant(LA.sdiv(RA)); 714 } 715 716 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow. 717 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) { 718 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) { 719 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE, 720 IgnoreSignificantBits); 721 if (!Step) return nullptr; 722 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE, 723 IgnoreSignificantBits); 724 if (!Start) return nullptr; 725 // FlagNW is independent of the start value, step direction, and is 726 // preserved with smaller magnitude steps. 727 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 728 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap); 729 } 730 return nullptr; 731 } 732 733 // Distribute the sdiv over add operands, if the add doesn't overflow. 734 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) { 735 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) { 736 SmallVector<const SCEV *, 8> Ops; 737 for (const SCEV *S : Add->operands()) { 738 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits); 739 if (!Op) return nullptr; 740 Ops.push_back(Op); 741 } 742 return SE.getAddExpr(Ops); 743 } 744 return nullptr; 745 } 746 747 // Check for a multiply operand that we can pull RHS out of. 748 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) { 749 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) { 750 // Handle special case C1*X*Y /s C2*X*Y. 751 if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(RHS)) { 752 if (IgnoreSignificantBits || isMulSExtable(MulRHS, SE)) { 753 const SCEVConstant *LC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 754 const SCEVConstant *RC = 755 dyn_cast<SCEVConstant>(MulRHS->getOperand(0)); 756 if (LC && RC) { 757 SmallVector<const SCEV *, 4> LOps(drop_begin(Mul->operands())); 758 SmallVector<const SCEV *, 4> ROps(drop_begin(MulRHS->operands())); 759 if (LOps == ROps) 760 return getExactSDiv(LC, RC, SE, IgnoreSignificantBits); 761 } 762 } 763 } 764 765 SmallVector<const SCEV *, 4> Ops; 766 bool Found = false; 767 for (const SCEV *S : Mul->operands()) { 768 if (!Found) 769 if (const SCEV *Q = getExactSDiv(S, RHS, SE, 770 IgnoreSignificantBits)) { 771 S = Q; 772 Found = true; 773 } 774 Ops.push_back(S); 775 } 776 return Found ? SE.getMulExpr(Ops) : nullptr; 777 } 778 return nullptr; 779 } 780 781 // Otherwise we don't know. 782 return nullptr; 783 } 784 785 /// If S involves the addition of a constant integer value, return that integer 786 /// value, and mutate S to point to a new SCEV with that value excluded. 787 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) { 788 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 789 if (C->getAPInt().getMinSignedBits() <= 64) { 790 S = SE.getConstant(C->getType(), 0); 791 return C->getValue()->getSExtValue(); 792 } 793 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 794 SmallVector<const SCEV *, 8> NewOps(Add->operands()); 795 int64_t Result = ExtractImmediate(NewOps.front(), SE); 796 if (Result != 0) 797 S = SE.getAddExpr(NewOps); 798 return Result; 799 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 800 SmallVector<const SCEV *, 8> NewOps(AR->operands()); 801 int64_t Result = ExtractImmediate(NewOps.front(), SE); 802 if (Result != 0) 803 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 804 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 805 SCEV::FlagAnyWrap); 806 return Result; 807 } 808 return 0; 809 } 810 811 /// If S involves the addition of a GlobalValue address, return that symbol, and 812 /// mutate S to point to a new SCEV with that value excluded. 813 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) { 814 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 815 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) { 816 S = SE.getConstant(GV->getType(), 0); 817 return GV; 818 } 819 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 820 SmallVector<const SCEV *, 8> NewOps(Add->operands()); 821 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE); 822 if (Result) 823 S = SE.getAddExpr(NewOps); 824 return Result; 825 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 826 SmallVector<const SCEV *, 8> NewOps(AR->operands()); 827 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE); 828 if (Result) 829 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 830 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 831 SCEV::FlagAnyWrap); 832 return Result; 833 } 834 return nullptr; 835 } 836 837 /// Returns true if the specified instruction is using the specified value as an 838 /// address. 839 static bool isAddressUse(const TargetTransformInfo &TTI, 840 Instruction *Inst, Value *OperandVal) { 841 bool isAddress = isa<LoadInst>(Inst); 842 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 843 if (SI->getPointerOperand() == OperandVal) 844 isAddress = true; 845 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 846 // Addressing modes can also be folded into prefetches and a variety 847 // of intrinsics. 848 switch (II->getIntrinsicID()) { 849 case Intrinsic::memset: 850 case Intrinsic::prefetch: 851 case Intrinsic::masked_load: 852 if (II->getArgOperand(0) == OperandVal) 853 isAddress = true; 854 break; 855 case Intrinsic::masked_store: 856 if (II->getArgOperand(1) == OperandVal) 857 isAddress = true; 858 break; 859 case Intrinsic::memmove: 860 case Intrinsic::memcpy: 861 if (II->getArgOperand(0) == OperandVal || 862 II->getArgOperand(1) == OperandVal) 863 isAddress = true; 864 break; 865 default: { 866 MemIntrinsicInfo IntrInfo; 867 if (TTI.getTgtMemIntrinsic(II, IntrInfo)) { 868 if (IntrInfo.PtrVal == OperandVal) 869 isAddress = true; 870 } 871 } 872 } 873 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 874 if (RMW->getPointerOperand() == OperandVal) 875 isAddress = true; 876 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 877 if (CmpX->getPointerOperand() == OperandVal) 878 isAddress = true; 879 } 880 return isAddress; 881 } 882 883 /// Return the type of the memory being accessed. 884 static MemAccessTy getAccessType(const TargetTransformInfo &TTI, 885 Instruction *Inst, Value *OperandVal) { 886 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace); 887 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 888 AccessTy.MemTy = SI->getOperand(0)->getType(); 889 AccessTy.AddrSpace = SI->getPointerAddressSpace(); 890 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 891 AccessTy.AddrSpace = LI->getPointerAddressSpace(); 892 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 893 AccessTy.AddrSpace = RMW->getPointerAddressSpace(); 894 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 895 AccessTy.AddrSpace = CmpX->getPointerAddressSpace(); 896 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 897 switch (II->getIntrinsicID()) { 898 case Intrinsic::prefetch: 899 case Intrinsic::memset: 900 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace(); 901 AccessTy.MemTy = OperandVal->getType(); 902 break; 903 case Intrinsic::memmove: 904 case Intrinsic::memcpy: 905 AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace(); 906 AccessTy.MemTy = OperandVal->getType(); 907 break; 908 case Intrinsic::masked_load: 909 AccessTy.AddrSpace = 910 II->getArgOperand(0)->getType()->getPointerAddressSpace(); 911 break; 912 case Intrinsic::masked_store: 913 AccessTy.MemTy = II->getOperand(0)->getType(); 914 AccessTy.AddrSpace = 915 II->getArgOperand(1)->getType()->getPointerAddressSpace(); 916 break; 917 default: { 918 MemIntrinsicInfo IntrInfo; 919 if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) { 920 AccessTy.AddrSpace 921 = IntrInfo.PtrVal->getType()->getPointerAddressSpace(); 922 } 923 924 break; 925 } 926 } 927 } 928 929 // All pointers have the same requirements, so canonicalize them to an 930 // arbitrary pointer type to minimize variation. 931 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy)) 932 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1), 933 PTy->getAddressSpace()); 934 935 return AccessTy; 936 } 937 938 /// Return true if this AddRec is already a phi in its loop. 939 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 940 for (PHINode &PN : AR->getLoop()->getHeader()->phis()) { 941 if (SE.isSCEVable(PN.getType()) && 942 (SE.getEffectiveSCEVType(PN.getType()) == 943 SE.getEffectiveSCEVType(AR->getType())) && 944 SE.getSCEV(&PN) == AR) 945 return true; 946 } 947 return false; 948 } 949 950 /// Check if expanding this expression is likely to incur significant cost. This 951 /// is tricky because SCEV doesn't track which expressions are actually computed 952 /// by the current IR. 953 /// 954 /// We currently allow expansion of IV increments that involve adds, 955 /// multiplication by constants, and AddRecs from existing phis. 956 /// 957 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an 958 /// obvious multiple of the UDivExpr. 959 static bool isHighCostExpansion(const SCEV *S, 960 SmallPtrSetImpl<const SCEV*> &Processed, 961 ScalarEvolution &SE) { 962 // Zero/One operand expressions 963 switch (S->getSCEVType()) { 964 case scUnknown: 965 case scConstant: 966 return false; 967 case scTruncate: 968 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(), 969 Processed, SE); 970 case scZeroExtend: 971 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(), 972 Processed, SE); 973 case scSignExtend: 974 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(), 975 Processed, SE); 976 default: 977 break; 978 } 979 980 if (!Processed.insert(S).second) 981 return false; 982 983 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 984 for (const SCEV *S : Add->operands()) { 985 if (isHighCostExpansion(S, Processed, SE)) 986 return true; 987 } 988 return false; 989 } 990 991 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 992 if (Mul->getNumOperands() == 2) { 993 // Multiplication by a constant is ok 994 if (isa<SCEVConstant>(Mul->getOperand(0))) 995 return isHighCostExpansion(Mul->getOperand(1), Processed, SE); 996 997 // If we have the value of one operand, check if an existing 998 // multiplication already generates this expression. 999 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) { 1000 Value *UVal = U->getValue(); 1001 for (User *UR : UVal->users()) { 1002 // If U is a constant, it may be used by a ConstantExpr. 1003 Instruction *UI = dyn_cast<Instruction>(UR); 1004 if (UI && UI->getOpcode() == Instruction::Mul && 1005 SE.isSCEVable(UI->getType())) { 1006 return SE.getSCEV(UI) == Mul; 1007 } 1008 } 1009 } 1010 } 1011 } 1012 1013 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 1014 if (isExistingPhi(AR, SE)) 1015 return false; 1016 } 1017 1018 // Fow now, consider any other type of expression (div/mul/min/max) high cost. 1019 return true; 1020 } 1021 1022 namespace { 1023 1024 class LSRUse; 1025 1026 } // end anonymous namespace 1027 1028 /// Check if the addressing mode defined by \p F is completely 1029 /// folded in \p LU at isel time. 1030 /// This includes address-mode folding and special icmp tricks. 1031 /// This function returns true if \p LU can accommodate what \p F 1032 /// defines and up to 1 base + 1 scaled + offset. 1033 /// In other words, if \p F has several base registers, this function may 1034 /// still return true. Therefore, users still need to account for 1035 /// additional base registers and/or unfolded offsets to derive an 1036 /// accurate cost model. 1037 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1038 const LSRUse &LU, const Formula &F); 1039 1040 // Get the cost of the scaling factor used in F for LU. 1041 static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI, 1042 const LSRUse &LU, const Formula &F, 1043 const Loop &L); 1044 1045 namespace { 1046 1047 /// This class is used to measure and compare candidate formulae. 1048 class Cost { 1049 const Loop *L = nullptr; 1050 ScalarEvolution *SE = nullptr; 1051 const TargetTransformInfo *TTI = nullptr; 1052 TargetTransformInfo::LSRCost C; 1053 TTI::AddressingModeKind AMK = TTI::AMK_None; 1054 1055 public: 1056 Cost() = delete; 1057 Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 1058 TTI::AddressingModeKind AMK) : 1059 L(L), SE(&SE), TTI(&TTI), AMK(AMK) { 1060 C.Insns = 0; 1061 C.NumRegs = 0; 1062 C.AddRecCost = 0; 1063 C.NumIVMuls = 0; 1064 C.NumBaseAdds = 0; 1065 C.ImmCost = 0; 1066 C.SetupCost = 0; 1067 C.ScaleCost = 0; 1068 } 1069 1070 bool isLess(const Cost &Other); 1071 1072 void Lose(); 1073 1074 #ifndef NDEBUG 1075 // Once any of the metrics loses, they must all remain losers. 1076 bool isValid() { 1077 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds 1078 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u) 1079 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds 1080 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u); 1081 } 1082 #endif 1083 1084 bool isLoser() { 1085 assert(isValid() && "invalid cost"); 1086 return C.NumRegs == ~0u; 1087 } 1088 1089 void RateFormula(const Formula &F, 1090 SmallPtrSetImpl<const SCEV *> &Regs, 1091 const DenseSet<const SCEV *> &VisitedRegs, 1092 const LSRUse &LU, 1093 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr); 1094 1095 void print(raw_ostream &OS) const; 1096 void dump() const; 1097 1098 private: 1099 void RateRegister(const Formula &F, const SCEV *Reg, 1100 SmallPtrSetImpl<const SCEV *> &Regs); 1101 void RatePrimaryRegister(const Formula &F, const SCEV *Reg, 1102 SmallPtrSetImpl<const SCEV *> &Regs, 1103 SmallPtrSetImpl<const SCEV *> *LoserRegs); 1104 }; 1105 1106 /// An operand value in an instruction which is to be replaced with some 1107 /// equivalent, possibly strength-reduced, replacement. 1108 struct LSRFixup { 1109 /// The instruction which will be updated. 1110 Instruction *UserInst = nullptr; 1111 1112 /// The operand of the instruction which will be replaced. The operand may be 1113 /// used more than once; every instance will be replaced. 1114 Value *OperandValToReplace = nullptr; 1115 1116 /// If this user is to use the post-incremented value of an induction 1117 /// variable, this set is non-empty and holds the loops associated with the 1118 /// induction variable. 1119 PostIncLoopSet PostIncLoops; 1120 1121 /// A constant offset to be added to the LSRUse expression. This allows 1122 /// multiple fixups to share the same LSRUse with different offsets, for 1123 /// example in an unrolled loop. 1124 int64_t Offset = 0; 1125 1126 LSRFixup() = default; 1127 1128 bool isUseFullyOutsideLoop(const Loop *L) const; 1129 1130 void print(raw_ostream &OS) const; 1131 void dump() const; 1132 }; 1133 1134 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted 1135 /// SmallVectors of const SCEV*. 1136 struct UniquifierDenseMapInfo { 1137 static SmallVector<const SCEV *, 4> getEmptyKey() { 1138 SmallVector<const SCEV *, 4> V; 1139 V.push_back(reinterpret_cast<const SCEV *>(-1)); 1140 return V; 1141 } 1142 1143 static SmallVector<const SCEV *, 4> getTombstoneKey() { 1144 SmallVector<const SCEV *, 4> V; 1145 V.push_back(reinterpret_cast<const SCEV *>(-2)); 1146 return V; 1147 } 1148 1149 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) { 1150 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 1151 } 1152 1153 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS, 1154 const SmallVector<const SCEV *, 4> &RHS) { 1155 return LHS == RHS; 1156 } 1157 }; 1158 1159 /// This class holds the state that LSR keeps for each use in IVUsers, as well 1160 /// as uses invented by LSR itself. It includes information about what kinds of 1161 /// things can be folded into the user, information about the user itself, and 1162 /// information about how the use may be satisfied. TODO: Represent multiple 1163 /// users of the same expression in common? 1164 class LSRUse { 1165 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier; 1166 1167 public: 1168 /// An enum for a kind of use, indicating what types of scaled and immediate 1169 /// operands it might support. 1170 enum KindType { 1171 Basic, ///< A normal use, with no folding. 1172 Special, ///< A special case of basic, allowing -1 scales. 1173 Address, ///< An address use; folding according to TargetLowering 1174 ICmpZero ///< An equality icmp with both operands folded into one. 1175 // TODO: Add a generic icmp too? 1176 }; 1177 1178 using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>; 1179 1180 KindType Kind; 1181 MemAccessTy AccessTy; 1182 1183 /// The list of operands which are to be replaced. 1184 SmallVector<LSRFixup, 8> Fixups; 1185 1186 /// Keep track of the min and max offsets of the fixups. 1187 int64_t MinOffset = std::numeric_limits<int64_t>::max(); 1188 int64_t MaxOffset = std::numeric_limits<int64_t>::min(); 1189 1190 /// This records whether all of the fixups using this LSRUse are outside of 1191 /// the loop, in which case some special-case heuristics may be used. 1192 bool AllFixupsOutsideLoop = true; 1193 1194 /// RigidFormula is set to true to guarantee that this use will be associated 1195 /// with a single formula--the one that initially matched. Some SCEV 1196 /// expressions cannot be expanded. This allows LSR to consider the registers 1197 /// used by those expressions without the need to expand them later after 1198 /// changing the formula. 1199 bool RigidFormula = false; 1200 1201 /// This records the widest use type for any fixup using this 1202 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max 1203 /// fixup widths to be equivalent, because the narrower one may be relying on 1204 /// the implicit truncation to truncate away bogus bits. 1205 Type *WidestFixupType = nullptr; 1206 1207 /// A list of ways to build a value that can satisfy this user. After the 1208 /// list is populated, one of these is selected heuristically and used to 1209 /// formulate a replacement for OperandValToReplace in UserInst. 1210 SmallVector<Formula, 12> Formulae; 1211 1212 /// The set of register candidates used by all formulae in this LSRUse. 1213 SmallPtrSet<const SCEV *, 4> Regs; 1214 1215 LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {} 1216 1217 LSRFixup &getNewFixup() { 1218 Fixups.push_back(LSRFixup()); 1219 return Fixups.back(); 1220 } 1221 1222 void pushFixup(LSRFixup &f) { 1223 Fixups.push_back(f); 1224 if (f.Offset > MaxOffset) 1225 MaxOffset = f.Offset; 1226 if (f.Offset < MinOffset) 1227 MinOffset = f.Offset; 1228 } 1229 1230 bool HasFormulaWithSameRegs(const Formula &F) const; 1231 float getNotSelectedProbability(const SCEV *Reg) const; 1232 bool InsertFormula(const Formula &F, const Loop &L); 1233 void DeleteFormula(Formula &F); 1234 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses); 1235 1236 void print(raw_ostream &OS) const; 1237 void dump() const; 1238 }; 1239 1240 } // end anonymous namespace 1241 1242 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1243 LSRUse::KindType Kind, MemAccessTy AccessTy, 1244 GlobalValue *BaseGV, int64_t BaseOffset, 1245 bool HasBaseReg, int64_t Scale, 1246 Instruction *Fixup = nullptr); 1247 1248 static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) { 1249 if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg)) 1250 return 1; 1251 if (Depth == 0) 1252 return 0; 1253 if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg)) 1254 return getSetupCost(S->getStart(), Depth - 1); 1255 if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg)) 1256 return getSetupCost(S->getOperand(), Depth - 1); 1257 if (auto S = dyn_cast<SCEVNAryExpr>(Reg)) 1258 return std::accumulate(S->op_begin(), S->op_end(), 0, 1259 [&](unsigned i, const SCEV *Reg) { 1260 return i + getSetupCost(Reg, Depth - 1); 1261 }); 1262 if (auto S = dyn_cast<SCEVUDivExpr>(Reg)) 1263 return getSetupCost(S->getLHS(), Depth - 1) + 1264 getSetupCost(S->getRHS(), Depth - 1); 1265 return 0; 1266 } 1267 1268 /// Tally up interesting quantities from the given register. 1269 void Cost::RateRegister(const Formula &F, const SCEV *Reg, 1270 SmallPtrSetImpl<const SCEV *> &Regs) { 1271 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) { 1272 // If this is an addrec for another loop, it should be an invariant 1273 // with respect to L since L is the innermost loop (at least 1274 // for now LSR only handles innermost loops). 1275 if (AR->getLoop() != L) { 1276 // If the AddRec exists, consider it's register free and leave it alone. 1277 if (isExistingPhi(AR, *SE) && AMK != TTI::AMK_PostIndexed) 1278 return; 1279 1280 // It is bad to allow LSR for current loop to add induction variables 1281 // for its sibling loops. 1282 if (!AR->getLoop()->contains(L)) { 1283 Lose(); 1284 return; 1285 } 1286 1287 // Otherwise, it will be an invariant with respect to Loop L. 1288 ++C.NumRegs; 1289 return; 1290 } 1291 1292 unsigned LoopCost = 1; 1293 if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) || 1294 TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) { 1295 1296 // If the step size matches the base offset, we could use pre-indexed 1297 // addressing. 1298 if (AMK == TTI::AMK_PreIndexed) { 1299 if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE))) 1300 if (Step->getAPInt() == F.BaseOffset) 1301 LoopCost = 0; 1302 } else if (AMK == TTI::AMK_PostIndexed) { 1303 const SCEV *LoopStep = AR->getStepRecurrence(*SE); 1304 if (isa<SCEVConstant>(LoopStep)) { 1305 const SCEV *LoopStart = AR->getStart(); 1306 if (!isa<SCEVConstant>(LoopStart) && 1307 SE->isLoopInvariant(LoopStart, L)) 1308 LoopCost = 0; 1309 } 1310 } 1311 } 1312 C.AddRecCost += LoopCost; 1313 1314 // Add the step value register, if it needs one. 1315 // TODO: The non-affine case isn't precisely modeled here. 1316 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) { 1317 if (!Regs.count(AR->getOperand(1))) { 1318 RateRegister(F, AR->getOperand(1), Regs); 1319 if (isLoser()) 1320 return; 1321 } 1322 } 1323 } 1324 ++C.NumRegs; 1325 1326 // Rough heuristic; favor registers which don't require extra setup 1327 // instructions in the preheader. 1328 C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit); 1329 // Ensure we don't, even with the recusion limit, produce invalid costs. 1330 C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16); 1331 1332 C.NumIVMuls += isa<SCEVMulExpr>(Reg) && 1333 SE->hasComputableLoopEvolution(Reg, L); 1334 } 1335 1336 /// Record this register in the set. If we haven't seen it before, rate 1337 /// it. Optional LoserRegs provides a way to declare any formula that refers to 1338 /// one of those regs an instant loser. 1339 void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg, 1340 SmallPtrSetImpl<const SCEV *> &Regs, 1341 SmallPtrSetImpl<const SCEV *> *LoserRegs) { 1342 if (LoserRegs && LoserRegs->count(Reg)) { 1343 Lose(); 1344 return; 1345 } 1346 if (Regs.insert(Reg).second) { 1347 RateRegister(F, Reg, Regs); 1348 if (LoserRegs && isLoser()) 1349 LoserRegs->insert(Reg); 1350 } 1351 } 1352 1353 void Cost::RateFormula(const Formula &F, 1354 SmallPtrSetImpl<const SCEV *> &Regs, 1355 const DenseSet<const SCEV *> &VisitedRegs, 1356 const LSRUse &LU, 1357 SmallPtrSetImpl<const SCEV *> *LoserRegs) { 1358 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula"); 1359 // Tally up the registers. 1360 unsigned PrevAddRecCost = C.AddRecCost; 1361 unsigned PrevNumRegs = C.NumRegs; 1362 unsigned PrevNumBaseAdds = C.NumBaseAdds; 1363 if (const SCEV *ScaledReg = F.ScaledReg) { 1364 if (VisitedRegs.count(ScaledReg)) { 1365 Lose(); 1366 return; 1367 } 1368 RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs); 1369 if (isLoser()) 1370 return; 1371 } 1372 for (const SCEV *BaseReg : F.BaseRegs) { 1373 if (VisitedRegs.count(BaseReg)) { 1374 Lose(); 1375 return; 1376 } 1377 RatePrimaryRegister(F, BaseReg, Regs, LoserRegs); 1378 if (isLoser()) 1379 return; 1380 } 1381 1382 // Determine how many (unfolded) adds we'll need inside the loop. 1383 size_t NumBaseParts = F.getNumRegs(); 1384 if (NumBaseParts > 1) 1385 // Do not count the base and a possible second register if the target 1386 // allows to fold 2 registers. 1387 C.NumBaseAdds += 1388 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F))); 1389 C.NumBaseAdds += (F.UnfoldedOffset != 0); 1390 1391 // Accumulate non-free scaling amounts. 1392 C.ScaleCost += *getScalingFactorCost(*TTI, LU, F, *L).getValue(); 1393 1394 // Tally up the non-zero immediates. 1395 for (const LSRFixup &Fixup : LU.Fixups) { 1396 int64_t O = Fixup.Offset; 1397 int64_t Offset = (uint64_t)O + F.BaseOffset; 1398 if (F.BaseGV) 1399 C.ImmCost += 64; // Handle symbolic values conservatively. 1400 // TODO: This should probably be the pointer size. 1401 else if (Offset != 0) 1402 C.ImmCost += APInt(64, Offset, true).getMinSignedBits(); 1403 1404 // Check with target if this offset with this instruction is 1405 // specifically not supported. 1406 if (LU.Kind == LSRUse::Address && Offset != 0 && 1407 !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, 1408 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst)) 1409 C.NumBaseAdds++; 1410 } 1411 1412 // If we don't count instruction cost exit here. 1413 if (!InsnsCost) { 1414 assert(isValid() && "invalid cost"); 1415 return; 1416 } 1417 1418 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as 1419 // additional instruction (at least fill). 1420 // TODO: Need distinguish register class? 1421 unsigned TTIRegNum = TTI->getNumberOfRegisters( 1422 TTI->getRegisterClassForType(false, F.getType())) - 1; 1423 if (C.NumRegs > TTIRegNum) { 1424 // Cost already exceeded TTIRegNum, then only newly added register can add 1425 // new instructions. 1426 if (PrevNumRegs > TTIRegNum) 1427 C.Insns += (C.NumRegs - PrevNumRegs); 1428 else 1429 C.Insns += (C.NumRegs - TTIRegNum); 1430 } 1431 1432 // If ICmpZero formula ends with not 0, it could not be replaced by 1433 // just add or sub. We'll need to compare final result of AddRec. 1434 // That means we'll need an additional instruction. But if the target can 1435 // macro-fuse a compare with a branch, don't count this extra instruction. 1436 // For -10 + {0, +, 1}: 1437 // i = i + 1; 1438 // cmp i, 10 1439 // 1440 // For {-10, +, 1}: 1441 // i = i + 1; 1442 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() && 1443 !TTI->canMacroFuseCmp()) 1444 C.Insns++; 1445 // Each new AddRec adds 1 instruction to calculation. 1446 C.Insns += (C.AddRecCost - PrevAddRecCost); 1447 1448 // BaseAdds adds instructions for unfolded registers. 1449 if (LU.Kind != LSRUse::ICmpZero) 1450 C.Insns += C.NumBaseAdds - PrevNumBaseAdds; 1451 assert(isValid() && "invalid cost"); 1452 } 1453 1454 /// Set this cost to a losing value. 1455 void Cost::Lose() { 1456 C.Insns = std::numeric_limits<unsigned>::max(); 1457 C.NumRegs = std::numeric_limits<unsigned>::max(); 1458 C.AddRecCost = std::numeric_limits<unsigned>::max(); 1459 C.NumIVMuls = std::numeric_limits<unsigned>::max(); 1460 C.NumBaseAdds = std::numeric_limits<unsigned>::max(); 1461 C.ImmCost = std::numeric_limits<unsigned>::max(); 1462 C.SetupCost = std::numeric_limits<unsigned>::max(); 1463 C.ScaleCost = std::numeric_limits<unsigned>::max(); 1464 } 1465 1466 /// Choose the lower cost. 1467 bool Cost::isLess(const Cost &Other) { 1468 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost && 1469 C.Insns != Other.C.Insns) 1470 return C.Insns < Other.C.Insns; 1471 return TTI->isLSRCostLess(C, Other.C); 1472 } 1473 1474 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1475 void Cost::print(raw_ostream &OS) const { 1476 if (InsnsCost) 1477 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s "); 1478 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s"); 1479 if (C.AddRecCost != 0) 1480 OS << ", with addrec cost " << C.AddRecCost; 1481 if (C.NumIVMuls != 0) 1482 OS << ", plus " << C.NumIVMuls << " IV mul" 1483 << (C.NumIVMuls == 1 ? "" : "s"); 1484 if (C.NumBaseAdds != 0) 1485 OS << ", plus " << C.NumBaseAdds << " base add" 1486 << (C.NumBaseAdds == 1 ? "" : "s"); 1487 if (C.ScaleCost != 0) 1488 OS << ", plus " << C.ScaleCost << " scale cost"; 1489 if (C.ImmCost != 0) 1490 OS << ", plus " << C.ImmCost << " imm cost"; 1491 if (C.SetupCost != 0) 1492 OS << ", plus " << C.SetupCost << " setup cost"; 1493 } 1494 1495 LLVM_DUMP_METHOD void Cost::dump() const { 1496 print(errs()); errs() << '\n'; 1497 } 1498 #endif 1499 1500 /// Test whether this fixup always uses its value outside of the given loop. 1501 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const { 1502 // PHI nodes use their value in their incoming blocks. 1503 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) { 1504 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1505 if (PN->getIncomingValue(i) == OperandValToReplace && 1506 L->contains(PN->getIncomingBlock(i))) 1507 return false; 1508 return true; 1509 } 1510 1511 return !L->contains(UserInst); 1512 } 1513 1514 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1515 void LSRFixup::print(raw_ostream &OS) const { 1516 OS << "UserInst="; 1517 // Store is common and interesting enough to be worth special-casing. 1518 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) { 1519 OS << "store "; 1520 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false); 1521 } else if (UserInst->getType()->isVoidTy()) 1522 OS << UserInst->getOpcodeName(); 1523 else 1524 UserInst->printAsOperand(OS, /*PrintType=*/false); 1525 1526 OS << ", OperandValToReplace="; 1527 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false); 1528 1529 for (const Loop *PIL : PostIncLoops) { 1530 OS << ", PostIncLoop="; 1531 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 1532 } 1533 1534 if (Offset != 0) 1535 OS << ", Offset=" << Offset; 1536 } 1537 1538 LLVM_DUMP_METHOD void LSRFixup::dump() const { 1539 print(errs()); errs() << '\n'; 1540 } 1541 #endif 1542 1543 /// Test whether this use as a formula which has the same registers as the given 1544 /// formula. 1545 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const { 1546 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1547 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1548 // Unstable sort by host order ok, because this is only used for uniquifying. 1549 llvm::sort(Key); 1550 return Uniquifier.count(Key); 1551 } 1552 1553 /// The function returns a probability of selecting formula without Reg. 1554 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const { 1555 unsigned FNum = 0; 1556 for (const Formula &F : Formulae) 1557 if (F.referencesReg(Reg)) 1558 FNum++; 1559 return ((float)(Formulae.size() - FNum)) / Formulae.size(); 1560 } 1561 1562 /// If the given formula has not yet been inserted, add it to the list, and 1563 /// return true. Return false otherwise. The formula must be in canonical form. 1564 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) { 1565 assert(F.isCanonical(L) && "Invalid canonical representation"); 1566 1567 if (!Formulae.empty() && RigidFormula) 1568 return false; 1569 1570 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1571 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1572 // Unstable sort by host order ok, because this is only used for uniquifying. 1573 llvm::sort(Key); 1574 1575 if (!Uniquifier.insert(Key).second) 1576 return false; 1577 1578 // Using a register to hold the value of 0 is not profitable. 1579 assert((!F.ScaledReg || !F.ScaledReg->isZero()) && 1580 "Zero allocated in a scaled register!"); 1581 #ifndef NDEBUG 1582 for (const SCEV *BaseReg : F.BaseRegs) 1583 assert(!BaseReg->isZero() && "Zero allocated in a base register!"); 1584 #endif 1585 1586 // Add the formula to the list. 1587 Formulae.push_back(F); 1588 1589 // Record registers now being used by this use. 1590 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1591 if (F.ScaledReg) 1592 Regs.insert(F.ScaledReg); 1593 1594 return true; 1595 } 1596 1597 /// Remove the given formula from this use's list. 1598 void LSRUse::DeleteFormula(Formula &F) { 1599 if (&F != &Formulae.back()) 1600 std::swap(F, Formulae.back()); 1601 Formulae.pop_back(); 1602 } 1603 1604 /// Recompute the Regs field, and update RegUses. 1605 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) { 1606 // Now that we've filtered out some formulae, recompute the Regs set. 1607 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs); 1608 Regs.clear(); 1609 for (const Formula &F : Formulae) { 1610 if (F.ScaledReg) Regs.insert(F.ScaledReg); 1611 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1612 } 1613 1614 // Update the RegTracker. 1615 for (const SCEV *S : OldRegs) 1616 if (!Regs.count(S)) 1617 RegUses.dropRegister(S, LUIdx); 1618 } 1619 1620 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1621 void LSRUse::print(raw_ostream &OS) const { 1622 OS << "LSR Use: Kind="; 1623 switch (Kind) { 1624 case Basic: OS << "Basic"; break; 1625 case Special: OS << "Special"; break; 1626 case ICmpZero: OS << "ICmpZero"; break; 1627 case Address: 1628 OS << "Address of "; 1629 if (AccessTy.MemTy->isPointerTy()) 1630 OS << "pointer"; // the full pointer type could be really verbose 1631 else { 1632 OS << *AccessTy.MemTy; 1633 } 1634 1635 OS << " in addrspace(" << AccessTy.AddrSpace << ')'; 1636 } 1637 1638 OS << ", Offsets={"; 1639 bool NeedComma = false; 1640 for (const LSRFixup &Fixup : Fixups) { 1641 if (NeedComma) OS << ','; 1642 OS << Fixup.Offset; 1643 NeedComma = true; 1644 } 1645 OS << '}'; 1646 1647 if (AllFixupsOutsideLoop) 1648 OS << ", all-fixups-outside-loop"; 1649 1650 if (WidestFixupType) 1651 OS << ", widest fixup type: " << *WidestFixupType; 1652 } 1653 1654 LLVM_DUMP_METHOD void LSRUse::dump() const { 1655 print(errs()); errs() << '\n'; 1656 } 1657 #endif 1658 1659 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1660 LSRUse::KindType Kind, MemAccessTy AccessTy, 1661 GlobalValue *BaseGV, int64_t BaseOffset, 1662 bool HasBaseReg, int64_t Scale, 1663 Instruction *Fixup/*= nullptr*/) { 1664 switch (Kind) { 1665 case LSRUse::Address: 1666 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset, 1667 HasBaseReg, Scale, AccessTy.AddrSpace, Fixup); 1668 1669 case LSRUse::ICmpZero: 1670 // There's not even a target hook for querying whether it would be legal to 1671 // fold a GV into an ICmp. 1672 if (BaseGV) 1673 return false; 1674 1675 // ICmp only has two operands; don't allow more than two non-trivial parts. 1676 if (Scale != 0 && HasBaseReg && BaseOffset != 0) 1677 return false; 1678 1679 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by 1680 // putting the scaled register in the other operand of the icmp. 1681 if (Scale != 0 && Scale != -1) 1682 return false; 1683 1684 // If we have low-level target information, ask the target if it can fold an 1685 // integer immediate on an icmp. 1686 if (BaseOffset != 0) { 1687 // We have one of: 1688 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset 1689 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset 1690 // Offs is the ICmp immediate. 1691 if (Scale == 0) 1692 // The cast does the right thing with 1693 // std::numeric_limits<int64_t>::min(). 1694 BaseOffset = -(uint64_t)BaseOffset; 1695 return TTI.isLegalICmpImmediate(BaseOffset); 1696 } 1697 1698 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg 1699 return true; 1700 1701 case LSRUse::Basic: 1702 // Only handle single-register values. 1703 return !BaseGV && Scale == 0 && BaseOffset == 0; 1704 1705 case LSRUse::Special: 1706 // Special case Basic to handle -1 scales. 1707 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0; 1708 } 1709 1710 llvm_unreachable("Invalid LSRUse Kind!"); 1711 } 1712 1713 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1714 int64_t MinOffset, int64_t MaxOffset, 1715 LSRUse::KindType Kind, MemAccessTy AccessTy, 1716 GlobalValue *BaseGV, int64_t BaseOffset, 1717 bool HasBaseReg, int64_t Scale) { 1718 // Check for overflow. 1719 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) != 1720 (MinOffset > 0)) 1721 return false; 1722 MinOffset = (uint64_t)BaseOffset + MinOffset; 1723 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) != 1724 (MaxOffset > 0)) 1725 return false; 1726 MaxOffset = (uint64_t)BaseOffset + MaxOffset; 1727 1728 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset, 1729 HasBaseReg, Scale) && 1730 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset, 1731 HasBaseReg, Scale); 1732 } 1733 1734 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1735 int64_t MinOffset, int64_t MaxOffset, 1736 LSRUse::KindType Kind, MemAccessTy AccessTy, 1737 const Formula &F, const Loop &L) { 1738 // For the purpose of isAMCompletelyFolded either having a canonical formula 1739 // or a scale not equal to zero is correct. 1740 // Problems may arise from non canonical formulae having a scale == 0. 1741 // Strictly speaking it would best to just rely on canonical formulae. 1742 // However, when we generate the scaled formulae, we first check that the 1743 // scaling factor is profitable before computing the actual ScaledReg for 1744 // compile time sake. 1745 assert((F.isCanonical(L) || F.Scale != 0)); 1746 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1747 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale); 1748 } 1749 1750 /// Test whether we know how to expand the current formula. 1751 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1752 int64_t MaxOffset, LSRUse::KindType Kind, 1753 MemAccessTy AccessTy, GlobalValue *BaseGV, 1754 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) { 1755 // We know how to expand completely foldable formulae. 1756 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1757 BaseOffset, HasBaseReg, Scale) || 1758 // Or formulae that use a base register produced by a sum of base 1759 // registers. 1760 (Scale == 1 && 1761 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1762 BaseGV, BaseOffset, true, 0)); 1763 } 1764 1765 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1766 int64_t MaxOffset, LSRUse::KindType Kind, 1767 MemAccessTy AccessTy, const Formula &F) { 1768 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV, 1769 F.BaseOffset, F.HasBaseReg, F.Scale); 1770 } 1771 1772 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1773 const LSRUse &LU, const Formula &F) { 1774 // Target may want to look at the user instructions. 1775 if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) { 1776 for (const LSRFixup &Fixup : LU.Fixups) 1777 if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, 1778 (F.BaseOffset + Fixup.Offset), F.HasBaseReg, 1779 F.Scale, Fixup.UserInst)) 1780 return false; 1781 return true; 1782 } 1783 1784 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1785 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg, 1786 F.Scale); 1787 } 1788 1789 static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI, 1790 const LSRUse &LU, const Formula &F, 1791 const Loop &L) { 1792 if (!F.Scale) 1793 return 0; 1794 1795 // If the use is not completely folded in that instruction, we will have to 1796 // pay an extra cost only for scale != 1. 1797 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1798 LU.AccessTy, F, L)) 1799 return F.Scale != 1; 1800 1801 switch (LU.Kind) { 1802 case LSRUse::Address: { 1803 // Check the scaling factor cost with both the min and max offsets. 1804 InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost( 1805 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg, 1806 F.Scale, LU.AccessTy.AddrSpace); 1807 InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost( 1808 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg, 1809 F.Scale, LU.AccessTy.AddrSpace); 1810 1811 assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() && 1812 "Legal addressing mode has an illegal cost!"); 1813 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset); 1814 } 1815 case LSRUse::ICmpZero: 1816 case LSRUse::Basic: 1817 case LSRUse::Special: 1818 // The use is completely folded, i.e., everything is folded into the 1819 // instruction. 1820 return 0; 1821 } 1822 1823 llvm_unreachable("Invalid LSRUse Kind!"); 1824 } 1825 1826 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1827 LSRUse::KindType Kind, MemAccessTy AccessTy, 1828 GlobalValue *BaseGV, int64_t BaseOffset, 1829 bool HasBaseReg) { 1830 // Fast-path: zero is always foldable. 1831 if (BaseOffset == 0 && !BaseGV) return true; 1832 1833 // Conservatively, create an address with an immediate and a 1834 // base and a scale. 1835 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1836 1837 // Canonicalize a scale of 1 to a base register if the formula doesn't 1838 // already have a base register. 1839 if (!HasBaseReg && Scale == 1) { 1840 Scale = 0; 1841 HasBaseReg = true; 1842 } 1843 1844 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset, 1845 HasBaseReg, Scale); 1846 } 1847 1848 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1849 ScalarEvolution &SE, int64_t MinOffset, 1850 int64_t MaxOffset, LSRUse::KindType Kind, 1851 MemAccessTy AccessTy, const SCEV *S, 1852 bool HasBaseReg) { 1853 // Fast-path: zero is always foldable. 1854 if (S->isZero()) return true; 1855 1856 // Conservatively, create an address with an immediate and a 1857 // base and a scale. 1858 int64_t BaseOffset = ExtractImmediate(S, SE); 1859 GlobalValue *BaseGV = ExtractSymbol(S, SE); 1860 1861 // If there's anything else involved, it's not foldable. 1862 if (!S->isZero()) return false; 1863 1864 // Fast-path: zero is always foldable. 1865 if (BaseOffset == 0 && !BaseGV) return true; 1866 1867 // Conservatively, create an address with an immediate and a 1868 // base and a scale. 1869 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1870 1871 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1872 BaseOffset, HasBaseReg, Scale); 1873 } 1874 1875 namespace { 1876 1877 /// An individual increment in a Chain of IV increments. Relate an IV user to 1878 /// an expression that computes the IV it uses from the IV used by the previous 1879 /// link in the Chain. 1880 /// 1881 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the 1882 /// original IVOperand. The head of the chain's IVOperand is only valid during 1883 /// chain collection, before LSR replaces IV users. During chain generation, 1884 /// IncExpr can be used to find the new IVOperand that computes the same 1885 /// expression. 1886 struct IVInc { 1887 Instruction *UserInst; 1888 Value* IVOperand; 1889 const SCEV *IncExpr; 1890 1891 IVInc(Instruction *U, Value *O, const SCEV *E) 1892 : UserInst(U), IVOperand(O), IncExpr(E) {} 1893 }; 1894 1895 // The list of IV increments in program order. We typically add the head of a 1896 // chain without finding subsequent links. 1897 struct IVChain { 1898 SmallVector<IVInc, 1> Incs; 1899 const SCEV *ExprBase = nullptr; 1900 1901 IVChain() = default; 1902 IVChain(const IVInc &Head, const SCEV *Base) 1903 : Incs(1, Head), ExprBase(Base) {} 1904 1905 using const_iterator = SmallVectorImpl<IVInc>::const_iterator; 1906 1907 // Return the first increment in the chain. 1908 const_iterator begin() const { 1909 assert(!Incs.empty()); 1910 return std::next(Incs.begin()); 1911 } 1912 const_iterator end() const { 1913 return Incs.end(); 1914 } 1915 1916 // Returns true if this chain contains any increments. 1917 bool hasIncs() const { return Incs.size() >= 2; } 1918 1919 // Add an IVInc to the end of this chain. 1920 void add(const IVInc &X) { Incs.push_back(X); } 1921 1922 // Returns the last UserInst in the chain. 1923 Instruction *tailUserInst() const { return Incs.back().UserInst; } 1924 1925 // Returns true if IncExpr can be profitably added to this chain. 1926 bool isProfitableIncrement(const SCEV *OperExpr, 1927 const SCEV *IncExpr, 1928 ScalarEvolution&); 1929 }; 1930 1931 /// Helper for CollectChains to track multiple IV increment uses. Distinguish 1932 /// between FarUsers that definitely cross IV increments and NearUsers that may 1933 /// be used between IV increments. 1934 struct ChainUsers { 1935 SmallPtrSet<Instruction*, 4> FarUsers; 1936 SmallPtrSet<Instruction*, 4> NearUsers; 1937 }; 1938 1939 /// This class holds state for the main loop strength reduction logic. 1940 class LSRInstance { 1941 IVUsers &IU; 1942 ScalarEvolution &SE; 1943 DominatorTree &DT; 1944 LoopInfo &LI; 1945 AssumptionCache &AC; 1946 TargetLibraryInfo &TLI; 1947 const TargetTransformInfo &TTI; 1948 Loop *const L; 1949 MemorySSAUpdater *MSSAU; 1950 TTI::AddressingModeKind AMK; 1951 bool Changed = false; 1952 1953 /// This is the insert position that the current loop's induction variable 1954 /// increment should be placed. In simple loops, this is the latch block's 1955 /// terminator. But in more complicated cases, this is a position which will 1956 /// dominate all the in-loop post-increment users. 1957 Instruction *IVIncInsertPos = nullptr; 1958 1959 /// Interesting factors between use strides. 1960 /// 1961 /// We explicitly use a SetVector which contains a SmallSet, instead of the 1962 /// default, a SmallDenseSet, because we need to use the full range of 1963 /// int64_ts, and there's currently no good way of doing that with 1964 /// SmallDenseSet. 1965 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors; 1966 1967 /// Interesting use types, to facilitate truncation reuse. 1968 SmallSetVector<Type *, 4> Types; 1969 1970 /// The list of interesting uses. 1971 mutable SmallVector<LSRUse, 16> Uses; 1972 1973 /// Track which uses use which register candidates. 1974 RegUseTracker RegUses; 1975 1976 // Limit the number of chains to avoid quadratic behavior. We don't expect to 1977 // have more than a few IV increment chains in a loop. Missing a Chain falls 1978 // back to normal LSR behavior for those uses. 1979 static const unsigned MaxChains = 8; 1980 1981 /// IV users can form a chain of IV increments. 1982 SmallVector<IVChain, MaxChains> IVChainVec; 1983 1984 /// IV users that belong to profitable IVChains. 1985 SmallPtrSet<Use*, MaxChains> IVIncSet; 1986 1987 /// Induction variables that were generated and inserted by the SCEV Expander. 1988 SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs; 1989 1990 void OptimizeShadowIV(); 1991 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse); 1992 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse); 1993 void OptimizeLoopTermCond(); 1994 1995 void ChainInstruction(Instruction *UserInst, Instruction *IVOper, 1996 SmallVectorImpl<ChainUsers> &ChainUsersVec); 1997 void FinalizeChain(IVChain &Chain); 1998 void CollectChains(); 1999 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 2000 SmallVectorImpl<WeakTrackingVH> &DeadInsts); 2001 2002 void CollectInterestingTypesAndFactors(); 2003 void CollectFixupsAndInitialFormulae(); 2004 2005 // Support for sharing of LSRUses between LSRFixups. 2006 using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>; 2007 UseMapTy UseMap; 2008 2009 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg, 2010 LSRUse::KindType Kind, MemAccessTy AccessTy); 2011 2012 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind, 2013 MemAccessTy AccessTy); 2014 2015 void DeleteUse(LSRUse &LU, size_t LUIdx); 2016 2017 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU); 2018 2019 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 2020 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 2021 void CountRegisters(const Formula &F, size_t LUIdx); 2022 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F); 2023 2024 void CollectLoopInvariantFixupsAndFormulae(); 2025 2026 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base, 2027 unsigned Depth = 0); 2028 2029 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 2030 const Formula &Base, unsigned Depth, 2031 size_t Idx, bool IsScaledReg = false); 2032 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base); 2033 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 2034 const Formula &Base, size_t Idx, 2035 bool IsScaledReg = false); 2036 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 2037 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx, 2038 const Formula &Base, 2039 const SmallVectorImpl<int64_t> &Worklist, 2040 size_t Idx, bool IsScaledReg = false); 2041 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 2042 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base); 2043 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base); 2044 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base); 2045 void GenerateCrossUseConstantOffsets(); 2046 void GenerateAllReuseFormulae(); 2047 2048 void FilterOutUndesirableDedicatedRegisters(); 2049 2050 size_t EstimateSearchSpaceComplexity() const; 2051 void NarrowSearchSpaceByDetectingSupersets(); 2052 void NarrowSearchSpaceByCollapsingUnrolledCode(); 2053 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 2054 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); 2055 void NarrowSearchSpaceByFilterPostInc(); 2056 void NarrowSearchSpaceByDeletingCostlyFormulas(); 2057 void NarrowSearchSpaceByPickingWinnerRegs(); 2058 void NarrowSearchSpaceUsingHeuristics(); 2059 2060 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 2061 Cost &SolutionCost, 2062 SmallVectorImpl<const Formula *> &Workspace, 2063 const Cost &CurCost, 2064 const SmallPtrSet<const SCEV *, 16> &CurRegs, 2065 DenseSet<const SCEV *> &VisitedRegs) const; 2066 void Solve(SmallVectorImpl<const Formula *> &Solution) const; 2067 2068 BasicBlock::iterator 2069 HoistInsertPosition(BasicBlock::iterator IP, 2070 const SmallVectorImpl<Instruction *> &Inputs) const; 2071 BasicBlock::iterator 2072 AdjustInsertPositionForExpand(BasicBlock::iterator IP, 2073 const LSRFixup &LF, 2074 const LSRUse &LU, 2075 SCEVExpander &Rewriter) const; 2076 2077 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 2078 BasicBlock::iterator IP, SCEVExpander &Rewriter, 2079 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2080 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF, 2081 const Formula &F, SCEVExpander &Rewriter, 2082 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2083 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 2084 SCEVExpander &Rewriter, 2085 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2086 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution); 2087 2088 public: 2089 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, 2090 LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC, 2091 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU); 2092 2093 bool getChanged() const { return Changed; } 2094 const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const { 2095 return ScalarEvolutionIVs; 2096 } 2097 2098 void print_factors_and_types(raw_ostream &OS) const; 2099 void print_fixups(raw_ostream &OS) const; 2100 void print_uses(raw_ostream &OS) const; 2101 void print(raw_ostream &OS) const; 2102 void dump() const; 2103 }; 2104 2105 } // end anonymous namespace 2106 2107 /// If IV is used in a int-to-float cast inside the loop then try to eliminate 2108 /// the cast operation. 2109 void LSRInstance::OptimizeShadowIV() { 2110 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 2111 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2112 return; 2113 2114 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); 2115 UI != E; /* empty */) { 2116 IVUsers::const_iterator CandidateUI = UI; 2117 ++UI; 2118 Instruction *ShadowUse = CandidateUI->getUser(); 2119 Type *DestTy = nullptr; 2120 bool IsSigned = false; 2121 2122 /* If shadow use is a int->float cast then insert a second IV 2123 to eliminate this cast. 2124 2125 for (unsigned i = 0; i < n; ++i) 2126 foo((double)i); 2127 2128 is transformed into 2129 2130 double d = 0.0; 2131 for (unsigned i = 0; i < n; ++i, ++d) 2132 foo(d); 2133 */ 2134 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) { 2135 IsSigned = false; 2136 DestTy = UCast->getDestTy(); 2137 } 2138 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) { 2139 IsSigned = true; 2140 DestTy = SCast->getDestTy(); 2141 } 2142 if (!DestTy) continue; 2143 2144 // If target does not support DestTy natively then do not apply 2145 // this transformation. 2146 if (!TTI.isTypeLegal(DestTy)) continue; 2147 2148 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0)); 2149 if (!PH) continue; 2150 if (PH->getNumIncomingValues() != 2) continue; 2151 2152 // If the calculation in integers overflows, the result in FP type will 2153 // differ. So we only can do this transformation if we are guaranteed to not 2154 // deal with overflowing values 2155 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH)); 2156 if (!AR) continue; 2157 if (IsSigned && !AR->hasNoSignedWrap()) continue; 2158 if (!IsSigned && !AR->hasNoUnsignedWrap()) continue; 2159 2160 Type *SrcTy = PH->getType(); 2161 int Mantissa = DestTy->getFPMantissaWidth(); 2162 if (Mantissa == -1) continue; 2163 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa) 2164 continue; 2165 2166 unsigned Entry, Latch; 2167 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) { 2168 Entry = 0; 2169 Latch = 1; 2170 } else { 2171 Entry = 1; 2172 Latch = 0; 2173 } 2174 2175 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry)); 2176 if (!Init) continue; 2177 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ? 2178 (double)Init->getSExtValue() : 2179 (double)Init->getZExtValue()); 2180 2181 BinaryOperator *Incr = 2182 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch)); 2183 if (!Incr) continue; 2184 if (Incr->getOpcode() != Instruction::Add 2185 && Incr->getOpcode() != Instruction::Sub) 2186 continue; 2187 2188 /* Initialize new IV, double d = 0.0 in above example. */ 2189 ConstantInt *C = nullptr; 2190 if (Incr->getOperand(0) == PH) 2191 C = dyn_cast<ConstantInt>(Incr->getOperand(1)); 2192 else if (Incr->getOperand(1) == PH) 2193 C = dyn_cast<ConstantInt>(Incr->getOperand(0)); 2194 else 2195 continue; 2196 2197 if (!C) continue; 2198 2199 // Ignore negative constants, as the code below doesn't handle them 2200 // correctly. TODO: Remove this restriction. 2201 if (!C->getValue().isStrictlyPositive()) continue; 2202 2203 /* Add new PHINode. */ 2204 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH); 2205 2206 /* create new increment. '++d' in above example. */ 2207 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue()); 2208 BinaryOperator *NewIncr = 2209 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ? 2210 Instruction::FAdd : Instruction::FSub, 2211 NewPH, CFP, "IV.S.next.", Incr); 2212 2213 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry)); 2214 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch)); 2215 2216 /* Remove cast operation */ 2217 ShadowUse->replaceAllUsesWith(NewPH); 2218 ShadowUse->eraseFromParent(); 2219 Changed = true; 2220 break; 2221 } 2222 } 2223 2224 /// If Cond has an operand that is an expression of an IV, set the IV user and 2225 /// stride information and return true, otherwise return false. 2226 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) { 2227 for (IVStrideUse &U : IU) 2228 if (U.getUser() == Cond) { 2229 // NOTE: we could handle setcc instructions with multiple uses here, but 2230 // InstCombine does it as well for simple uses, it's not clear that it 2231 // occurs enough in real life to handle. 2232 CondUse = &U; 2233 return true; 2234 } 2235 return false; 2236 } 2237 2238 /// Rewrite the loop's terminating condition if it uses a max computation. 2239 /// 2240 /// This is a narrow solution to a specific, but acute, problem. For loops 2241 /// like this: 2242 /// 2243 /// i = 0; 2244 /// do { 2245 /// p[i] = 0.0; 2246 /// } while (++i < n); 2247 /// 2248 /// the trip count isn't just 'n', because 'n' might not be positive. And 2249 /// unfortunately this can come up even for loops where the user didn't use 2250 /// a C do-while loop. For example, seemingly well-behaved top-test loops 2251 /// will commonly be lowered like this: 2252 /// 2253 /// if (n > 0) { 2254 /// i = 0; 2255 /// do { 2256 /// p[i] = 0.0; 2257 /// } while (++i < n); 2258 /// } 2259 /// 2260 /// and then it's possible for subsequent optimization to obscure the if 2261 /// test in such a way that indvars can't find it. 2262 /// 2263 /// When indvars can't find the if test in loops like this, it creates a 2264 /// max expression, which allows it to give the loop a canonical 2265 /// induction variable: 2266 /// 2267 /// i = 0; 2268 /// max = n < 1 ? 1 : n; 2269 /// do { 2270 /// p[i] = 0.0; 2271 /// } while (++i != max); 2272 /// 2273 /// Canonical induction variables are necessary because the loop passes 2274 /// are designed around them. The most obvious example of this is the 2275 /// LoopInfo analysis, which doesn't remember trip count values. It 2276 /// expects to be able to rediscover the trip count each time it is 2277 /// needed, and it does this using a simple analysis that only succeeds if 2278 /// the loop has a canonical induction variable. 2279 /// 2280 /// However, when it comes time to generate code, the maximum operation 2281 /// can be quite costly, especially if it's inside of an outer loop. 2282 /// 2283 /// This function solves this problem by detecting this type of loop and 2284 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting 2285 /// the instructions for the maximum computation. 2286 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) { 2287 // Check that the loop matches the pattern we're looking for. 2288 if (Cond->getPredicate() != CmpInst::ICMP_EQ && 2289 Cond->getPredicate() != CmpInst::ICMP_NE) 2290 return Cond; 2291 2292 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1)); 2293 if (!Sel || !Sel->hasOneUse()) return Cond; 2294 2295 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 2296 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2297 return Cond; 2298 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1); 2299 2300 // Add one to the backedge-taken count to get the trip count. 2301 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount); 2302 if (IterationCount != SE.getSCEV(Sel)) return Cond; 2303 2304 // Check for a max calculation that matches the pattern. There's no check 2305 // for ICMP_ULE here because the comparison would be with zero, which 2306 // isn't interesting. 2307 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 2308 const SCEVNAryExpr *Max = nullptr; 2309 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) { 2310 Pred = ICmpInst::ICMP_SLE; 2311 Max = S; 2312 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) { 2313 Pred = ICmpInst::ICMP_SLT; 2314 Max = S; 2315 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) { 2316 Pred = ICmpInst::ICMP_ULT; 2317 Max = U; 2318 } else { 2319 // No match; bail. 2320 return Cond; 2321 } 2322 2323 // To handle a max with more than two operands, this optimization would 2324 // require additional checking and setup. 2325 if (Max->getNumOperands() != 2) 2326 return Cond; 2327 2328 const SCEV *MaxLHS = Max->getOperand(0); 2329 const SCEV *MaxRHS = Max->getOperand(1); 2330 2331 // ScalarEvolution canonicalizes constants to the left. For < and >, look 2332 // for a comparison with 1. For <= and >=, a comparison with zero. 2333 if (!MaxLHS || 2334 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One))) 2335 return Cond; 2336 2337 // Check the relevant induction variable for conformance to 2338 // the pattern. 2339 const SCEV *IV = SE.getSCEV(Cond->getOperand(0)); 2340 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV); 2341 if (!AR || !AR->isAffine() || 2342 AR->getStart() != One || 2343 AR->getStepRecurrence(SE) != One) 2344 return Cond; 2345 2346 assert(AR->getLoop() == L && 2347 "Loop condition operand is an addrec in a different loop!"); 2348 2349 // Check the right operand of the select, and remember it, as it will 2350 // be used in the new comparison instruction. 2351 Value *NewRHS = nullptr; 2352 if (ICmpInst::isTrueWhenEqual(Pred)) { 2353 // Look for n+1, and grab n. 2354 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1))) 2355 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2356 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2357 NewRHS = BO->getOperand(0); 2358 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2))) 2359 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2360 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2361 NewRHS = BO->getOperand(0); 2362 if (!NewRHS) 2363 return Cond; 2364 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS) 2365 NewRHS = Sel->getOperand(1); 2366 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS) 2367 NewRHS = Sel->getOperand(2); 2368 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS)) 2369 NewRHS = SU->getValue(); 2370 else 2371 // Max doesn't match expected pattern. 2372 return Cond; 2373 2374 // Determine the new comparison opcode. It may be signed or unsigned, 2375 // and the original comparison may be either equality or inequality. 2376 if (Cond->getPredicate() == CmpInst::ICMP_EQ) 2377 Pred = CmpInst::getInversePredicate(Pred); 2378 2379 // Ok, everything looks ok to change the condition into an SLT or SGE and 2380 // delete the max calculation. 2381 ICmpInst *NewCond = 2382 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp"); 2383 2384 // Delete the max calculation instructions. 2385 NewCond->setDebugLoc(Cond->getDebugLoc()); 2386 Cond->replaceAllUsesWith(NewCond); 2387 CondUse->setUser(NewCond); 2388 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0)); 2389 Cond->eraseFromParent(); 2390 Sel->eraseFromParent(); 2391 if (Cmp->use_empty()) 2392 Cmp->eraseFromParent(); 2393 return NewCond; 2394 } 2395 2396 /// Change loop terminating condition to use the postinc iv when possible. 2397 void 2398 LSRInstance::OptimizeLoopTermCond() { 2399 SmallPtrSet<Instruction *, 4> PostIncs; 2400 2401 // We need a different set of heuristics for rotated and non-rotated loops. 2402 // If a loop is rotated then the latch is also the backedge, so inserting 2403 // post-inc expressions just before the latch is ideal. To reduce live ranges 2404 // it also makes sense to rewrite terminating conditions to use post-inc 2405 // expressions. 2406 // 2407 // If the loop is not rotated then the latch is not a backedge; the latch 2408 // check is done in the loop head. Adding post-inc expressions before the 2409 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions 2410 // in the loop body. In this case we do *not* want to use post-inc expressions 2411 // in the latch check, and we want to insert post-inc expressions before 2412 // the backedge. 2413 BasicBlock *LatchBlock = L->getLoopLatch(); 2414 SmallVector<BasicBlock*, 8> ExitingBlocks; 2415 L->getExitingBlocks(ExitingBlocks); 2416 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) { 2417 return LatchBlock != BB; 2418 })) { 2419 // The backedge doesn't exit the loop; treat this as a head-tested loop. 2420 IVIncInsertPos = LatchBlock->getTerminator(); 2421 return; 2422 } 2423 2424 // Otherwise treat this as a rotated loop. 2425 for (BasicBlock *ExitingBlock : ExitingBlocks) { 2426 // Get the terminating condition for the loop if possible. If we 2427 // can, we want to change it to use a post-incremented version of its 2428 // induction variable, to allow coalescing the live ranges for the IV into 2429 // one register value. 2430 2431 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2432 if (!TermBr) 2433 continue; 2434 // FIXME: Overly conservative, termination condition could be an 'or' etc.. 2435 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition())) 2436 continue; 2437 2438 // Search IVUsesByStride to find Cond's IVUse if there is one. 2439 IVStrideUse *CondUse = nullptr; 2440 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition()); 2441 if (!FindIVUserForCond(Cond, CondUse)) 2442 continue; 2443 2444 // If the trip count is computed in terms of a max (due to ScalarEvolution 2445 // being unable to find a sufficient guard, for example), change the loop 2446 // comparison to use SLT or ULT instead of NE. 2447 // One consequence of doing this now is that it disrupts the count-down 2448 // optimization. That's not always a bad thing though, because in such 2449 // cases it may still be worthwhile to avoid a max. 2450 Cond = OptimizeMax(Cond, CondUse); 2451 2452 // If this exiting block dominates the latch block, it may also use 2453 // the post-inc value if it won't be shared with other uses. 2454 // Check for dominance. 2455 if (!DT.dominates(ExitingBlock, LatchBlock)) 2456 continue; 2457 2458 // Conservatively avoid trying to use the post-inc value in non-latch 2459 // exits if there may be pre-inc users in intervening blocks. 2460 if (LatchBlock != ExitingBlock) 2461 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) 2462 // Test if the use is reachable from the exiting block. This dominator 2463 // query is a conservative approximation of reachability. 2464 if (&*UI != CondUse && 2465 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) { 2466 // Conservatively assume there may be reuse if the quotient of their 2467 // strides could be a legal scale. 2468 const SCEV *A = IU.getStride(*CondUse, L); 2469 const SCEV *B = IU.getStride(*UI, L); 2470 if (!A || !B) continue; 2471 if (SE.getTypeSizeInBits(A->getType()) != 2472 SE.getTypeSizeInBits(B->getType())) { 2473 if (SE.getTypeSizeInBits(A->getType()) > 2474 SE.getTypeSizeInBits(B->getType())) 2475 B = SE.getSignExtendExpr(B, A->getType()); 2476 else 2477 A = SE.getSignExtendExpr(A, B->getType()); 2478 } 2479 if (const SCEVConstant *D = 2480 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) { 2481 const ConstantInt *C = D->getValue(); 2482 // Stride of one or negative one can have reuse with non-addresses. 2483 if (C->isOne() || C->isMinusOne()) 2484 goto decline_post_inc; 2485 // Avoid weird situations. 2486 if (C->getValue().getMinSignedBits() >= 64 || 2487 C->getValue().isMinSignedValue()) 2488 goto decline_post_inc; 2489 // Check for possible scaled-address reuse. 2490 if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) { 2491 MemAccessTy AccessTy = getAccessType( 2492 TTI, UI->getUser(), UI->getOperandValToReplace()); 2493 int64_t Scale = C->getSExtValue(); 2494 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2495 /*BaseOffset=*/0, 2496 /*HasBaseReg=*/false, Scale, 2497 AccessTy.AddrSpace)) 2498 goto decline_post_inc; 2499 Scale = -Scale; 2500 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2501 /*BaseOffset=*/0, 2502 /*HasBaseReg=*/false, Scale, 2503 AccessTy.AddrSpace)) 2504 goto decline_post_inc; 2505 } 2506 } 2507 } 2508 2509 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: " 2510 << *Cond << '\n'); 2511 2512 // It's possible for the setcc instruction to be anywhere in the loop, and 2513 // possible for it to have multiple users. If it is not immediately before 2514 // the exiting block branch, move it. 2515 if (Cond->getNextNonDebugInstruction() != TermBr) { 2516 if (Cond->hasOneUse()) { 2517 Cond->moveBefore(TermBr); 2518 } else { 2519 // Clone the terminating condition and insert into the loopend. 2520 ICmpInst *OldCond = Cond; 2521 Cond = cast<ICmpInst>(Cond->clone()); 2522 Cond->setName(L->getHeader()->getName() + ".termcond"); 2523 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond); 2524 2525 // Clone the IVUse, as the old use still exists! 2526 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace()); 2527 TermBr->replaceUsesOfWith(OldCond, Cond); 2528 } 2529 } 2530 2531 // If we get to here, we know that we can transform the setcc instruction to 2532 // use the post-incremented version of the IV, allowing us to coalesce the 2533 // live ranges for the IV correctly. 2534 CondUse->transformToPostInc(L); 2535 Changed = true; 2536 2537 PostIncs.insert(Cond); 2538 decline_post_inc:; 2539 } 2540 2541 // Determine an insertion point for the loop induction variable increment. It 2542 // must dominate all the post-inc comparisons we just set up, and it must 2543 // dominate the loop latch edge. 2544 IVIncInsertPos = L->getLoopLatch()->getTerminator(); 2545 for (Instruction *Inst : PostIncs) { 2546 BasicBlock *BB = 2547 DT.findNearestCommonDominator(IVIncInsertPos->getParent(), 2548 Inst->getParent()); 2549 if (BB == Inst->getParent()) 2550 IVIncInsertPos = Inst; 2551 else if (BB != IVIncInsertPos->getParent()) 2552 IVIncInsertPos = BB->getTerminator(); 2553 } 2554 } 2555 2556 /// Determine if the given use can accommodate a fixup at the given offset and 2557 /// other details. If so, update the use and return true. 2558 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, 2559 bool HasBaseReg, LSRUse::KindType Kind, 2560 MemAccessTy AccessTy) { 2561 int64_t NewMinOffset = LU.MinOffset; 2562 int64_t NewMaxOffset = LU.MaxOffset; 2563 MemAccessTy NewAccessTy = AccessTy; 2564 2565 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to 2566 // something conservative, however this can pessimize in the case that one of 2567 // the uses will have all its uses outside the loop, for example. 2568 if (LU.Kind != Kind) 2569 return false; 2570 2571 // Check for a mismatched access type, and fall back conservatively as needed. 2572 // TODO: Be less conservative when the type is similar and can use the same 2573 // addressing modes. 2574 if (Kind == LSRUse::Address) { 2575 if (AccessTy.MemTy != LU.AccessTy.MemTy) { 2576 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(), 2577 AccessTy.AddrSpace); 2578 } 2579 } 2580 2581 // Conservatively assume HasBaseReg is true for now. 2582 if (NewOffset < LU.MinOffset) { 2583 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2584 LU.MaxOffset - NewOffset, HasBaseReg)) 2585 return false; 2586 NewMinOffset = NewOffset; 2587 } else if (NewOffset > LU.MaxOffset) { 2588 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2589 NewOffset - LU.MinOffset, HasBaseReg)) 2590 return false; 2591 NewMaxOffset = NewOffset; 2592 } 2593 2594 // Update the use. 2595 LU.MinOffset = NewMinOffset; 2596 LU.MaxOffset = NewMaxOffset; 2597 LU.AccessTy = NewAccessTy; 2598 return true; 2599 } 2600 2601 /// Return an LSRUse index and an offset value for a fixup which needs the given 2602 /// expression, with the given kind and optional access type. Either reuse an 2603 /// existing use or create a new one, as needed. 2604 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr, 2605 LSRUse::KindType Kind, 2606 MemAccessTy AccessTy) { 2607 const SCEV *Copy = Expr; 2608 int64_t Offset = ExtractImmediate(Expr, SE); 2609 2610 // Basic uses can't accept any offset, for example. 2611 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr, 2612 Offset, /*HasBaseReg=*/ true)) { 2613 Expr = Copy; 2614 Offset = 0; 2615 } 2616 2617 std::pair<UseMapTy::iterator, bool> P = 2618 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0)); 2619 if (!P.second) { 2620 // A use already existed with this base. 2621 size_t LUIdx = P.first->second; 2622 LSRUse &LU = Uses[LUIdx]; 2623 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy)) 2624 // Reuse this use. 2625 return std::make_pair(LUIdx, Offset); 2626 } 2627 2628 // Create a new use. 2629 size_t LUIdx = Uses.size(); 2630 P.first->second = LUIdx; 2631 Uses.push_back(LSRUse(Kind, AccessTy)); 2632 LSRUse &LU = Uses[LUIdx]; 2633 2634 LU.MinOffset = Offset; 2635 LU.MaxOffset = Offset; 2636 return std::make_pair(LUIdx, Offset); 2637 } 2638 2639 /// Delete the given use from the Uses list. 2640 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) { 2641 if (&LU != &Uses.back()) 2642 std::swap(LU, Uses.back()); 2643 Uses.pop_back(); 2644 2645 // Update RegUses. 2646 RegUses.swapAndDropUse(LUIdx, Uses.size()); 2647 } 2648 2649 /// Look for a use distinct from OrigLU which is has a formula that has the same 2650 /// registers as the given formula. 2651 LSRUse * 2652 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF, 2653 const LSRUse &OrigLU) { 2654 // Search all uses for the formula. This could be more clever. 2655 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 2656 LSRUse &LU = Uses[LUIdx]; 2657 // Check whether this use is close enough to OrigLU, to see whether it's 2658 // worthwhile looking through its formulae. 2659 // Ignore ICmpZero uses because they may contain formulae generated by 2660 // GenerateICmpZeroScales, in which case adding fixup offsets may 2661 // be invalid. 2662 if (&LU != &OrigLU && 2663 LU.Kind != LSRUse::ICmpZero && 2664 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy && 2665 LU.WidestFixupType == OrigLU.WidestFixupType && 2666 LU.HasFormulaWithSameRegs(OrigF)) { 2667 // Scan through this use's formulae. 2668 for (const Formula &F : LU.Formulae) { 2669 // Check to see if this formula has the same registers and symbols 2670 // as OrigF. 2671 if (F.BaseRegs == OrigF.BaseRegs && 2672 F.ScaledReg == OrigF.ScaledReg && 2673 F.BaseGV == OrigF.BaseGV && 2674 F.Scale == OrigF.Scale && 2675 F.UnfoldedOffset == OrigF.UnfoldedOffset) { 2676 if (F.BaseOffset == 0) 2677 return &LU; 2678 // This is the formula where all the registers and symbols matched; 2679 // there aren't going to be any others. Since we declined it, we 2680 // can skip the rest of the formulae and proceed to the next LSRUse. 2681 break; 2682 } 2683 } 2684 } 2685 } 2686 2687 // Nothing looked good. 2688 return nullptr; 2689 } 2690 2691 void LSRInstance::CollectInterestingTypesAndFactors() { 2692 SmallSetVector<const SCEV *, 4> Strides; 2693 2694 // Collect interesting types and strides. 2695 SmallVector<const SCEV *, 4> Worklist; 2696 for (const IVStrideUse &U : IU) { 2697 const SCEV *Expr = IU.getExpr(U); 2698 2699 // Collect interesting types. 2700 Types.insert(SE.getEffectiveSCEVType(Expr->getType())); 2701 2702 // Add strides for mentioned loops. 2703 Worklist.push_back(Expr); 2704 do { 2705 const SCEV *S = Worklist.pop_back_val(); 2706 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 2707 if (AR->getLoop() == L) 2708 Strides.insert(AR->getStepRecurrence(SE)); 2709 Worklist.push_back(AR->getStart()); 2710 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 2711 Worklist.append(Add->op_begin(), Add->op_end()); 2712 } 2713 } while (!Worklist.empty()); 2714 } 2715 2716 // Compute interesting factors from the set of interesting strides. 2717 for (SmallSetVector<const SCEV *, 4>::const_iterator 2718 I = Strides.begin(), E = Strides.end(); I != E; ++I) 2719 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter = 2720 std::next(I); NewStrideIter != E; ++NewStrideIter) { 2721 const SCEV *OldStride = *I; 2722 const SCEV *NewStride = *NewStrideIter; 2723 2724 if (SE.getTypeSizeInBits(OldStride->getType()) != 2725 SE.getTypeSizeInBits(NewStride->getType())) { 2726 if (SE.getTypeSizeInBits(OldStride->getType()) > 2727 SE.getTypeSizeInBits(NewStride->getType())) 2728 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType()); 2729 else 2730 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType()); 2731 } 2732 if (const SCEVConstant *Factor = 2733 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride, 2734 SE, true))) { 2735 if (Factor->getAPInt().getMinSignedBits() <= 64 && !Factor->isZero()) 2736 Factors.insert(Factor->getAPInt().getSExtValue()); 2737 } else if (const SCEVConstant *Factor = 2738 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride, 2739 NewStride, 2740 SE, true))) { 2741 if (Factor->getAPInt().getMinSignedBits() <= 64 && !Factor->isZero()) 2742 Factors.insert(Factor->getAPInt().getSExtValue()); 2743 } 2744 } 2745 2746 // If all uses use the same type, don't bother looking for truncation-based 2747 // reuse. 2748 if (Types.size() == 1) 2749 Types.clear(); 2750 2751 LLVM_DEBUG(print_factors_and_types(dbgs())); 2752 } 2753 2754 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in 2755 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to 2756 /// IVStrideUses, we could partially skip this. 2757 static User::op_iterator 2758 findIVOperand(User::op_iterator OI, User::op_iterator OE, 2759 Loop *L, ScalarEvolution &SE) { 2760 for(; OI != OE; ++OI) { 2761 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) { 2762 if (!SE.isSCEVable(Oper->getType())) 2763 continue; 2764 2765 if (const SCEVAddRecExpr *AR = 2766 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) { 2767 if (AR->getLoop() == L) 2768 break; 2769 } 2770 } 2771 } 2772 return OI; 2773 } 2774 2775 /// IVChain logic must consistently peek base TruncInst operands, so wrap it in 2776 /// a convenient helper. 2777 static Value *getWideOperand(Value *Oper) { 2778 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper)) 2779 return Trunc->getOperand(0); 2780 return Oper; 2781 } 2782 2783 /// Return true if we allow an IV chain to include both types. 2784 static bool isCompatibleIVType(Value *LVal, Value *RVal) { 2785 Type *LType = LVal->getType(); 2786 Type *RType = RVal->getType(); 2787 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() && 2788 // Different address spaces means (possibly) 2789 // different types of the pointer implementation, 2790 // e.g. i16 vs i32 so disallow that. 2791 (LType->getPointerAddressSpace() == 2792 RType->getPointerAddressSpace())); 2793 } 2794 2795 /// Return an approximation of this SCEV expression's "base", or NULL for any 2796 /// constant. Returning the expression itself is conservative. Returning a 2797 /// deeper subexpression is more precise and valid as long as it isn't less 2798 /// complex than another subexpression. For expressions involving multiple 2799 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids 2800 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i], 2801 /// IVInc==b-a. 2802 /// 2803 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost 2804 /// SCEVUnknown, we simply return the rightmost SCEV operand. 2805 static const SCEV *getExprBase(const SCEV *S) { 2806 switch (S->getSCEVType()) { 2807 default: // uncluding scUnknown. 2808 return S; 2809 case scConstant: 2810 return nullptr; 2811 case scTruncate: 2812 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand()); 2813 case scZeroExtend: 2814 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand()); 2815 case scSignExtend: 2816 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand()); 2817 case scAddExpr: { 2818 // Skip over scaled operands (scMulExpr) to follow add operands as long as 2819 // there's nothing more complex. 2820 // FIXME: not sure if we want to recognize negation. 2821 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S); 2822 for (const SCEV *SubExpr : reverse(Add->operands())) { 2823 if (SubExpr->getSCEVType() == scAddExpr) 2824 return getExprBase(SubExpr); 2825 2826 if (SubExpr->getSCEVType() != scMulExpr) 2827 return SubExpr; 2828 } 2829 return S; // all operands are scaled, be conservative. 2830 } 2831 case scAddRecExpr: 2832 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart()); 2833 } 2834 llvm_unreachable("Unknown SCEV kind!"); 2835 } 2836 2837 /// Return true if the chain increment is profitable to expand into a loop 2838 /// invariant value, which may require its own register. A profitable chain 2839 /// increment will be an offset relative to the same base. We allow such offsets 2840 /// to potentially be used as chain increment as long as it's not obviously 2841 /// expensive to expand using real instructions. 2842 bool IVChain::isProfitableIncrement(const SCEV *OperExpr, 2843 const SCEV *IncExpr, 2844 ScalarEvolution &SE) { 2845 // Aggressively form chains when -stress-ivchain. 2846 if (StressIVChain) 2847 return true; 2848 2849 // Do not replace a constant offset from IV head with a nonconstant IV 2850 // increment. 2851 if (!isa<SCEVConstant>(IncExpr)) { 2852 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand)); 2853 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr))) 2854 return false; 2855 } 2856 2857 SmallPtrSet<const SCEV*, 8> Processed; 2858 return !isHighCostExpansion(IncExpr, Processed, SE); 2859 } 2860 2861 /// Return true if the number of registers needed for the chain is estimated to 2862 /// be less than the number required for the individual IV users. First prohibit 2863 /// any IV users that keep the IV live across increments (the Users set should 2864 /// be empty). Next count the number and type of increments in the chain. 2865 /// 2866 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't 2867 /// effectively use postinc addressing modes. Only consider it profitable it the 2868 /// increments can be computed in fewer registers when chained. 2869 /// 2870 /// TODO: Consider IVInc free if it's already used in another chains. 2871 static bool isProfitableChain(IVChain &Chain, 2872 SmallPtrSetImpl<Instruction *> &Users, 2873 ScalarEvolution &SE, 2874 const TargetTransformInfo &TTI) { 2875 if (StressIVChain) 2876 return true; 2877 2878 if (!Chain.hasIncs()) 2879 return false; 2880 2881 if (!Users.empty()) { 2882 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n"; 2883 for (Instruction *Inst 2884 : Users) { dbgs() << " " << *Inst << "\n"; }); 2885 return false; 2886 } 2887 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 2888 2889 // The chain itself may require a register, so intialize cost to 1. 2890 int cost = 1; 2891 2892 // A complete chain likely eliminates the need for keeping the original IV in 2893 // a register. LSR does not currently know how to form a complete chain unless 2894 // the header phi already exists. 2895 if (isa<PHINode>(Chain.tailUserInst()) 2896 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) { 2897 --cost; 2898 } 2899 const SCEV *LastIncExpr = nullptr; 2900 unsigned NumConstIncrements = 0; 2901 unsigned NumVarIncrements = 0; 2902 unsigned NumReusedIncrements = 0; 2903 2904 if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst)) 2905 return true; 2906 2907 for (const IVInc &Inc : Chain) { 2908 if (TTI.isProfitableLSRChainElement(Inc.UserInst)) 2909 return true; 2910 if (Inc.IncExpr->isZero()) 2911 continue; 2912 2913 // Incrementing by zero or some constant is neutral. We assume constants can 2914 // be folded into an addressing mode or an add's immediate operand. 2915 if (isa<SCEVConstant>(Inc.IncExpr)) { 2916 ++NumConstIncrements; 2917 continue; 2918 } 2919 2920 if (Inc.IncExpr == LastIncExpr) 2921 ++NumReusedIncrements; 2922 else 2923 ++NumVarIncrements; 2924 2925 LastIncExpr = Inc.IncExpr; 2926 } 2927 // An IV chain with a single increment is handled by LSR's postinc 2928 // uses. However, a chain with multiple increments requires keeping the IV's 2929 // value live longer than it needs to be if chained. 2930 if (NumConstIncrements > 1) 2931 --cost; 2932 2933 // Materializing increment expressions in the preheader that didn't exist in 2934 // the original code may cost a register. For example, sign-extended array 2935 // indices can produce ridiculous increments like this: 2936 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64))) 2937 cost += NumVarIncrements; 2938 2939 // Reusing variable increments likely saves a register to hold the multiple of 2940 // the stride. 2941 cost -= NumReusedIncrements; 2942 2943 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost 2944 << "\n"); 2945 2946 return cost < 0; 2947 } 2948 2949 /// Add this IV user to an existing chain or make it the head of a new chain. 2950 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper, 2951 SmallVectorImpl<ChainUsers> &ChainUsersVec) { 2952 // When IVs are used as types of varying widths, they are generally converted 2953 // to a wider type with some uses remaining narrow under a (free) trunc. 2954 Value *const NextIV = getWideOperand(IVOper); 2955 const SCEV *const OperExpr = SE.getSCEV(NextIV); 2956 const SCEV *const OperExprBase = getExprBase(OperExpr); 2957 2958 // Visit all existing chains. Check if its IVOper can be computed as a 2959 // profitable loop invariant increment from the last link in the Chain. 2960 unsigned ChainIdx = 0, NChains = IVChainVec.size(); 2961 const SCEV *LastIncExpr = nullptr; 2962 for (; ChainIdx < NChains; ++ChainIdx) { 2963 IVChain &Chain = IVChainVec[ChainIdx]; 2964 2965 // Prune the solution space aggressively by checking that both IV operands 2966 // are expressions that operate on the same unscaled SCEVUnknown. This 2967 // "base" will be canceled by the subsequent getMinusSCEV call. Checking 2968 // first avoids creating extra SCEV expressions. 2969 if (!StressIVChain && Chain.ExprBase != OperExprBase) 2970 continue; 2971 2972 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand); 2973 if (!isCompatibleIVType(PrevIV, NextIV)) 2974 continue; 2975 2976 // A phi node terminates a chain. 2977 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst())) 2978 continue; 2979 2980 // The increment must be loop-invariant so it can be kept in a register. 2981 const SCEV *PrevExpr = SE.getSCEV(PrevIV); 2982 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr); 2983 if (isa<SCEVCouldNotCompute>(IncExpr) || !SE.isLoopInvariant(IncExpr, L)) 2984 continue; 2985 2986 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) { 2987 LastIncExpr = IncExpr; 2988 break; 2989 } 2990 } 2991 // If we haven't found a chain, create a new one, unless we hit the max. Don't 2992 // bother for phi nodes, because they must be last in the chain. 2993 if (ChainIdx == NChains) { 2994 if (isa<PHINode>(UserInst)) 2995 return; 2996 if (NChains >= MaxChains && !StressIVChain) { 2997 LLVM_DEBUG(dbgs() << "IV Chain Limit\n"); 2998 return; 2999 } 3000 LastIncExpr = OperExpr; 3001 // IVUsers may have skipped over sign/zero extensions. We don't currently 3002 // attempt to form chains involving extensions unless they can be hoisted 3003 // into this loop's AddRec. 3004 if (!isa<SCEVAddRecExpr>(LastIncExpr)) 3005 return; 3006 ++NChains; 3007 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr), 3008 OperExprBase)); 3009 ChainUsersVec.resize(NChains); 3010 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst 3011 << ") IV=" << *LastIncExpr << "\n"); 3012 } else { 3013 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst 3014 << ") IV+" << *LastIncExpr << "\n"); 3015 // Add this IV user to the end of the chain. 3016 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr)); 3017 } 3018 IVChain &Chain = IVChainVec[ChainIdx]; 3019 3020 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers; 3021 // This chain's NearUsers become FarUsers. 3022 if (!LastIncExpr->isZero()) { 3023 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(), 3024 NearUsers.end()); 3025 NearUsers.clear(); 3026 } 3027 3028 // All other uses of IVOperand become near uses of the chain. 3029 // We currently ignore intermediate values within SCEV expressions, assuming 3030 // they will eventually be used be the current chain, or can be computed 3031 // from one of the chain increments. To be more precise we could 3032 // transitively follow its user and only add leaf IV users to the set. 3033 for (User *U : IVOper->users()) { 3034 Instruction *OtherUse = dyn_cast<Instruction>(U); 3035 if (!OtherUse) 3036 continue; 3037 // Uses in the chain will no longer be uses if the chain is formed. 3038 // Include the head of the chain in this iteration (not Chain.begin()). 3039 IVChain::const_iterator IncIter = Chain.Incs.begin(); 3040 IVChain::const_iterator IncEnd = Chain.Incs.end(); 3041 for( ; IncIter != IncEnd; ++IncIter) { 3042 if (IncIter->UserInst == OtherUse) 3043 break; 3044 } 3045 if (IncIter != IncEnd) 3046 continue; 3047 3048 if (SE.isSCEVable(OtherUse->getType()) 3049 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse)) 3050 && IU.isIVUserOrOperand(OtherUse)) { 3051 continue; 3052 } 3053 NearUsers.insert(OtherUse); 3054 } 3055 3056 // Since this user is part of the chain, it's no longer considered a use 3057 // of the chain. 3058 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst); 3059 } 3060 3061 /// Populate the vector of Chains. 3062 /// 3063 /// This decreases ILP at the architecture level. Targets with ample registers, 3064 /// multiple memory ports, and no register renaming probably don't want 3065 /// this. However, such targets should probably disable LSR altogether. 3066 /// 3067 /// The job of LSR is to make a reasonable choice of induction variables across 3068 /// the loop. Subsequent passes can easily "unchain" computation exposing more 3069 /// ILP *within the loop* if the target wants it. 3070 /// 3071 /// Finding the best IV chain is potentially a scheduling problem. Since LSR 3072 /// will not reorder memory operations, it will recognize this as a chain, but 3073 /// will generate redundant IV increments. Ideally this would be corrected later 3074 /// by a smart scheduler: 3075 /// = A[i] 3076 /// = A[i+x] 3077 /// A[i] = 3078 /// A[i+x] = 3079 /// 3080 /// TODO: Walk the entire domtree within this loop, not just the path to the 3081 /// loop latch. This will discover chains on side paths, but requires 3082 /// maintaining multiple copies of the Chains state. 3083 void LSRInstance::CollectChains() { 3084 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n"); 3085 SmallVector<ChainUsers, 8> ChainUsersVec; 3086 3087 SmallVector<BasicBlock *,8> LatchPath; 3088 BasicBlock *LoopHeader = L->getHeader(); 3089 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch()); 3090 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) { 3091 LatchPath.push_back(Rung->getBlock()); 3092 } 3093 LatchPath.push_back(LoopHeader); 3094 3095 // Walk the instruction stream from the loop header to the loop latch. 3096 for (BasicBlock *BB : reverse(LatchPath)) { 3097 for (Instruction &I : *BB) { 3098 // Skip instructions that weren't seen by IVUsers analysis. 3099 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I)) 3100 continue; 3101 3102 // Ignore users that are part of a SCEV expression. This way we only 3103 // consider leaf IV Users. This effectively rediscovers a portion of 3104 // IVUsers analysis but in program order this time. 3105 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I))) 3106 continue; 3107 3108 // Remove this instruction from any NearUsers set it may be in. 3109 for (unsigned ChainIdx = 0, NChains = IVChainVec.size(); 3110 ChainIdx < NChains; ++ChainIdx) { 3111 ChainUsersVec[ChainIdx].NearUsers.erase(&I); 3112 } 3113 // Search for operands that can be chained. 3114 SmallPtrSet<Instruction*, 4> UniqueOperands; 3115 User::op_iterator IVOpEnd = I.op_end(); 3116 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE); 3117 while (IVOpIter != IVOpEnd) { 3118 Instruction *IVOpInst = cast<Instruction>(*IVOpIter); 3119 if (UniqueOperands.insert(IVOpInst).second) 3120 ChainInstruction(&I, IVOpInst, ChainUsersVec); 3121 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 3122 } 3123 } // Continue walking down the instructions. 3124 } // Continue walking down the domtree. 3125 // Visit phi backedges to determine if the chain can generate the IV postinc. 3126 for (PHINode &PN : L->getHeader()->phis()) { 3127 if (!SE.isSCEVable(PN.getType())) 3128 continue; 3129 3130 Instruction *IncV = 3131 dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch())); 3132 if (IncV) 3133 ChainInstruction(&PN, IncV, ChainUsersVec); 3134 } 3135 // Remove any unprofitable chains. 3136 unsigned ChainIdx = 0; 3137 for (unsigned UsersIdx = 0, NChains = IVChainVec.size(); 3138 UsersIdx < NChains; ++UsersIdx) { 3139 if (!isProfitableChain(IVChainVec[UsersIdx], 3140 ChainUsersVec[UsersIdx].FarUsers, SE, TTI)) 3141 continue; 3142 // Preserve the chain at UsesIdx. 3143 if (ChainIdx != UsersIdx) 3144 IVChainVec[ChainIdx] = IVChainVec[UsersIdx]; 3145 FinalizeChain(IVChainVec[ChainIdx]); 3146 ++ChainIdx; 3147 } 3148 IVChainVec.resize(ChainIdx); 3149 } 3150 3151 void LSRInstance::FinalizeChain(IVChain &Chain) { 3152 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 3153 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n"); 3154 3155 for (const IVInc &Inc : Chain) { 3156 LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n"); 3157 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand); 3158 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand"); 3159 IVIncSet.insert(UseI); 3160 } 3161 } 3162 3163 /// Return true if the IVInc can be folded into an addressing mode. 3164 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst, 3165 Value *Operand, const TargetTransformInfo &TTI) { 3166 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr); 3167 if (!IncConst || !isAddressUse(TTI, UserInst, Operand)) 3168 return false; 3169 3170 if (IncConst->getAPInt().getMinSignedBits() > 64) 3171 return false; 3172 3173 MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand); 3174 int64_t IncOffset = IncConst->getValue()->getSExtValue(); 3175 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr, 3176 IncOffset, /*HasBaseReg=*/false)) 3177 return false; 3178 3179 return true; 3180 } 3181 3182 /// Generate an add or subtract for each IVInc in a chain to materialize the IV 3183 /// user's operand from the previous IV user's operand. 3184 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 3185 SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 3186 // Find the new IVOperand for the head of the chain. It may have been replaced 3187 // by LSR. 3188 const IVInc &Head = Chain.Incs[0]; 3189 User::op_iterator IVOpEnd = Head.UserInst->op_end(); 3190 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user. 3191 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(), 3192 IVOpEnd, L, SE); 3193 Value *IVSrc = nullptr; 3194 while (IVOpIter != IVOpEnd) { 3195 IVSrc = getWideOperand(*IVOpIter); 3196 3197 // If this operand computes the expression that the chain needs, we may use 3198 // it. (Check this after setting IVSrc which is used below.) 3199 // 3200 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too 3201 // narrow for the chain, so we can no longer use it. We do allow using a 3202 // wider phi, assuming the LSR checked for free truncation. In that case we 3203 // should already have a truncate on this operand such that 3204 // getSCEV(IVSrc) == IncExpr. 3205 if (SE.getSCEV(*IVOpIter) == Head.IncExpr 3206 || SE.getSCEV(IVSrc) == Head.IncExpr) { 3207 break; 3208 } 3209 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 3210 } 3211 if (IVOpIter == IVOpEnd) { 3212 // Gracefully give up on this chain. 3213 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n"); 3214 return; 3215 } 3216 assert(IVSrc && "Failed to find IV chain source"); 3217 3218 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n"); 3219 Type *IVTy = IVSrc->getType(); 3220 Type *IntTy = SE.getEffectiveSCEVType(IVTy); 3221 const SCEV *LeftOverExpr = nullptr; 3222 for (const IVInc &Inc : Chain) { 3223 Instruction *InsertPt = Inc.UserInst; 3224 if (isa<PHINode>(InsertPt)) 3225 InsertPt = L->getLoopLatch()->getTerminator(); 3226 3227 // IVOper will replace the current IV User's operand. IVSrc is the IV 3228 // value currently held in a register. 3229 Value *IVOper = IVSrc; 3230 if (!Inc.IncExpr->isZero()) { 3231 // IncExpr was the result of subtraction of two narrow values, so must 3232 // be signed. 3233 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy); 3234 LeftOverExpr = LeftOverExpr ? 3235 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr; 3236 } 3237 if (LeftOverExpr && !LeftOverExpr->isZero()) { 3238 // Expand the IV increment. 3239 Rewriter.clearPostInc(); 3240 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt); 3241 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc), 3242 SE.getUnknown(IncV)); 3243 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt); 3244 3245 // If an IV increment can't be folded, use it as the next IV value. 3246 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) { 3247 assert(IVTy == IVOper->getType() && "inconsistent IV increment type"); 3248 IVSrc = IVOper; 3249 LeftOverExpr = nullptr; 3250 } 3251 } 3252 Type *OperTy = Inc.IVOperand->getType(); 3253 if (IVTy != OperTy) { 3254 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) && 3255 "cannot extend a chained IV"); 3256 IRBuilder<> Builder(InsertPt); 3257 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain"); 3258 } 3259 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper); 3260 if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand)) 3261 DeadInsts.emplace_back(OperandIsInstr); 3262 } 3263 // If LSR created a new, wider phi, we may also replace its postinc. We only 3264 // do this if we also found a wide value for the head of the chain. 3265 if (isa<PHINode>(Chain.tailUserInst())) { 3266 for (PHINode &Phi : L->getHeader()->phis()) { 3267 if (!isCompatibleIVType(&Phi, IVSrc)) 3268 continue; 3269 Instruction *PostIncV = dyn_cast<Instruction>( 3270 Phi.getIncomingValueForBlock(L->getLoopLatch())); 3271 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc))) 3272 continue; 3273 Value *IVOper = IVSrc; 3274 Type *PostIncTy = PostIncV->getType(); 3275 if (IVTy != PostIncTy) { 3276 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types"); 3277 IRBuilder<> Builder(L->getLoopLatch()->getTerminator()); 3278 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc()); 3279 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain"); 3280 } 3281 Phi.replaceUsesOfWith(PostIncV, IVOper); 3282 DeadInsts.emplace_back(PostIncV); 3283 } 3284 } 3285 } 3286 3287 void LSRInstance::CollectFixupsAndInitialFormulae() { 3288 BranchInst *ExitBranch = nullptr; 3289 bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI); 3290 3291 for (const IVStrideUse &U : IU) { 3292 Instruction *UserInst = U.getUser(); 3293 // Skip IV users that are part of profitable IV Chains. 3294 User::op_iterator UseI = 3295 find(UserInst->operands(), U.getOperandValToReplace()); 3296 assert(UseI != UserInst->op_end() && "cannot find IV operand"); 3297 if (IVIncSet.count(UseI)) { 3298 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n'); 3299 continue; 3300 } 3301 3302 LSRUse::KindType Kind = LSRUse::Basic; 3303 MemAccessTy AccessTy; 3304 if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) { 3305 Kind = LSRUse::Address; 3306 AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace()); 3307 } 3308 3309 const SCEV *S = IU.getExpr(U); 3310 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops(); 3311 3312 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as 3313 // (N - i == 0), and this allows (N - i) to be the expression that we work 3314 // with rather than just N or i, so we can consider the register 3315 // requirements for both N and i at the same time. Limiting this code to 3316 // equality icmps is not a problem because all interesting loops use 3317 // equality icmps, thanks to IndVarSimplify. 3318 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) { 3319 // If CI can be saved in some target, like replaced inside hardware loop 3320 // in PowerPC, no need to generate initial formulae for it. 3321 if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition())) 3322 continue; 3323 if (CI->isEquality()) { 3324 // Swap the operands if needed to put the OperandValToReplace on the 3325 // left, for consistency. 3326 Value *NV = CI->getOperand(1); 3327 if (NV == U.getOperandValToReplace()) { 3328 CI->setOperand(1, CI->getOperand(0)); 3329 CI->setOperand(0, NV); 3330 NV = CI->getOperand(1); 3331 Changed = true; 3332 } 3333 3334 // x == y --> x - y == 0 3335 const SCEV *N = SE.getSCEV(NV); 3336 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE) && 3337 (!NV->getType()->isPointerTy() || 3338 SE.getPointerBase(N) == SE.getPointerBase(S))) { 3339 // S is normalized, so normalize N before folding it into S 3340 // to keep the result normalized. 3341 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE); 3342 Kind = LSRUse::ICmpZero; 3343 S = SE.getMinusSCEV(N, S); 3344 } 3345 3346 // -1 and the negations of all interesting strides (except the negation 3347 // of -1) are now also interesting. 3348 for (size_t i = 0, e = Factors.size(); i != e; ++i) 3349 if (Factors[i] != -1) 3350 Factors.insert(-(uint64_t)Factors[i]); 3351 Factors.insert(-1); 3352 } 3353 } 3354 3355 // Get or create an LSRUse. 3356 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy); 3357 size_t LUIdx = P.first; 3358 int64_t Offset = P.second; 3359 LSRUse &LU = Uses[LUIdx]; 3360 3361 // Record the fixup. 3362 LSRFixup &LF = LU.getNewFixup(); 3363 LF.UserInst = UserInst; 3364 LF.OperandValToReplace = U.getOperandValToReplace(); 3365 LF.PostIncLoops = TmpPostIncLoops; 3366 LF.Offset = Offset; 3367 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3368 3369 if (!LU.WidestFixupType || 3370 SE.getTypeSizeInBits(LU.WidestFixupType) < 3371 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3372 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3373 3374 // If this is the first use of this LSRUse, give it a formula. 3375 if (LU.Formulae.empty()) { 3376 InsertInitialFormula(S, LU, LUIdx); 3377 CountRegisters(LU.Formulae.back(), LUIdx); 3378 } 3379 } 3380 3381 LLVM_DEBUG(print_fixups(dbgs())); 3382 } 3383 3384 /// Insert a formula for the given expression into the given use, separating out 3385 /// loop-variant portions from loop-invariant and loop-computable portions. 3386 void 3387 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) { 3388 // Mark uses whose expressions cannot be expanded. 3389 if (!isSafeToExpand(S, SE, /*CanonicalMode*/ false)) 3390 LU.RigidFormula = true; 3391 3392 Formula F; 3393 F.initialMatch(S, L, SE); 3394 bool Inserted = InsertFormula(LU, LUIdx, F); 3395 assert(Inserted && "Initial formula already exists!"); (void)Inserted; 3396 } 3397 3398 /// Insert a simple single-register formula for the given expression into the 3399 /// given use. 3400 void 3401 LSRInstance::InsertSupplementalFormula(const SCEV *S, 3402 LSRUse &LU, size_t LUIdx) { 3403 Formula F; 3404 F.BaseRegs.push_back(S); 3405 F.HasBaseReg = true; 3406 bool Inserted = InsertFormula(LU, LUIdx, F); 3407 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted; 3408 } 3409 3410 /// Note which registers are used by the given formula, updating RegUses. 3411 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) { 3412 if (F.ScaledReg) 3413 RegUses.countRegister(F.ScaledReg, LUIdx); 3414 for (const SCEV *BaseReg : F.BaseRegs) 3415 RegUses.countRegister(BaseReg, LUIdx); 3416 } 3417 3418 /// If the given formula has not yet been inserted, add it to the list, and 3419 /// return true. Return false otherwise. 3420 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) { 3421 // Do not insert formula that we will not be able to expand. 3422 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) && 3423 "Formula is illegal"); 3424 3425 if (!LU.InsertFormula(F, *L)) 3426 return false; 3427 3428 CountRegisters(F, LUIdx); 3429 return true; 3430 } 3431 3432 /// Check for other uses of loop-invariant values which we're tracking. These 3433 /// other uses will pin these values in registers, making them less profitable 3434 /// for elimination. 3435 /// TODO: This currently misses non-constant addrec step registers. 3436 /// TODO: Should this give more weight to users inside the loop? 3437 void 3438 LSRInstance::CollectLoopInvariantFixupsAndFormulae() { 3439 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end()); 3440 SmallPtrSet<const SCEV *, 32> Visited; 3441 3442 while (!Worklist.empty()) { 3443 const SCEV *S = Worklist.pop_back_val(); 3444 3445 // Don't process the same SCEV twice 3446 if (!Visited.insert(S).second) 3447 continue; 3448 3449 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) 3450 Worklist.append(N->op_begin(), N->op_end()); 3451 else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S)) 3452 Worklist.push_back(C->getOperand()); 3453 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { 3454 Worklist.push_back(D->getLHS()); 3455 Worklist.push_back(D->getRHS()); 3456 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) { 3457 const Value *V = US->getValue(); 3458 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 3459 // Look for instructions defined outside the loop. 3460 if (L->contains(Inst)) continue; 3461 } else if (isa<UndefValue>(V)) 3462 // Undef doesn't have a live range, so it doesn't matter. 3463 continue; 3464 for (const Use &U : V->uses()) { 3465 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser()); 3466 // Ignore non-instructions. 3467 if (!UserInst) 3468 continue; 3469 // Don't bother if the instruction is an EHPad. 3470 if (UserInst->isEHPad()) 3471 continue; 3472 // Ignore instructions in other functions (as can happen with 3473 // Constants). 3474 if (UserInst->getParent()->getParent() != L->getHeader()->getParent()) 3475 continue; 3476 // Ignore instructions not dominated by the loop. 3477 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ? 3478 UserInst->getParent() : 3479 cast<PHINode>(UserInst)->getIncomingBlock( 3480 PHINode::getIncomingValueNumForOperand(U.getOperandNo())); 3481 if (!DT.dominates(L->getHeader(), UseBB)) 3482 continue; 3483 // Don't bother if the instruction is in a BB which ends in an EHPad. 3484 if (UseBB->getTerminator()->isEHPad()) 3485 continue; 3486 3487 // Ignore cases in which the currently-examined value could come from 3488 // a basic block terminated with an EHPad. This checks all incoming 3489 // blocks of the phi node since it is possible that the same incoming 3490 // value comes from multiple basic blocks, only some of which may end 3491 // in an EHPad. If any of them do, a subsequent rewrite attempt by this 3492 // pass would try to insert instructions into an EHPad, hitting an 3493 // assertion. 3494 if (isa<PHINode>(UserInst)) { 3495 const auto *PhiNode = cast<PHINode>(UserInst); 3496 bool HasIncompatibleEHPTerminatedBlock = false; 3497 llvm::Value *ExpectedValue = U; 3498 for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) { 3499 if (PhiNode->getIncomingValue(I) == ExpectedValue) { 3500 if (PhiNode->getIncomingBlock(I)->getTerminator()->isEHPad()) { 3501 HasIncompatibleEHPTerminatedBlock = true; 3502 break; 3503 } 3504 } 3505 } 3506 if (HasIncompatibleEHPTerminatedBlock) { 3507 continue; 3508 } 3509 } 3510 3511 // Don't bother rewriting PHIs in catchswitch blocks. 3512 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator())) 3513 continue; 3514 // Ignore uses which are part of other SCEV expressions, to avoid 3515 // analyzing them multiple times. 3516 if (SE.isSCEVable(UserInst->getType())) { 3517 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst)); 3518 // If the user is a no-op, look through to its uses. 3519 if (!isa<SCEVUnknown>(UserS)) 3520 continue; 3521 if (UserS == US) { 3522 Worklist.push_back( 3523 SE.getUnknown(const_cast<Instruction *>(UserInst))); 3524 continue; 3525 } 3526 } 3527 // Ignore icmp instructions which are already being analyzed. 3528 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) { 3529 unsigned OtherIdx = !U.getOperandNo(); 3530 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx)); 3531 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L)) 3532 continue; 3533 } 3534 3535 std::pair<size_t, int64_t> P = getUse( 3536 S, LSRUse::Basic, MemAccessTy()); 3537 size_t LUIdx = P.first; 3538 int64_t Offset = P.second; 3539 LSRUse &LU = Uses[LUIdx]; 3540 LSRFixup &LF = LU.getNewFixup(); 3541 LF.UserInst = const_cast<Instruction *>(UserInst); 3542 LF.OperandValToReplace = U; 3543 LF.Offset = Offset; 3544 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3545 if (!LU.WidestFixupType || 3546 SE.getTypeSizeInBits(LU.WidestFixupType) < 3547 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3548 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3549 InsertSupplementalFormula(US, LU, LUIdx); 3550 CountRegisters(LU.Formulae.back(), Uses.size() - 1); 3551 break; 3552 } 3553 } 3554 } 3555 } 3556 3557 /// Split S into subexpressions which can be pulled out into separate 3558 /// registers. If C is non-null, multiply each subexpression by C. 3559 /// 3560 /// Return remainder expression after factoring the subexpressions captured by 3561 /// Ops. If Ops is complete, return NULL. 3562 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C, 3563 SmallVectorImpl<const SCEV *> &Ops, 3564 const Loop *L, 3565 ScalarEvolution &SE, 3566 unsigned Depth = 0) { 3567 // Arbitrarily cap recursion to protect compile time. 3568 if (Depth >= 3) 3569 return S; 3570 3571 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3572 // Break out add operands. 3573 for (const SCEV *S : Add->operands()) { 3574 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1); 3575 if (Remainder) 3576 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3577 } 3578 return nullptr; 3579 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 3580 // Split a non-zero base out of an addrec. 3581 if (AR->getStart()->isZero() || !AR->isAffine()) 3582 return S; 3583 3584 const SCEV *Remainder = CollectSubexprs(AR->getStart(), 3585 C, Ops, L, SE, Depth+1); 3586 // Split the non-zero AddRec unless it is part of a nested recurrence that 3587 // does not pertain to this loop. 3588 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) { 3589 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3590 Remainder = nullptr; 3591 } 3592 if (Remainder != AR->getStart()) { 3593 if (!Remainder) 3594 Remainder = SE.getConstant(AR->getType(), 0); 3595 return SE.getAddRecExpr(Remainder, 3596 AR->getStepRecurrence(SE), 3597 AR->getLoop(), 3598 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 3599 SCEV::FlagAnyWrap); 3600 } 3601 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3602 // Break (C * (a + b + c)) into C*a + C*b + C*c. 3603 if (Mul->getNumOperands() != 2) 3604 return S; 3605 if (const SCEVConstant *Op0 = 3606 dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3607 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0; 3608 const SCEV *Remainder = 3609 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1); 3610 if (Remainder) 3611 Ops.push_back(SE.getMulExpr(C, Remainder)); 3612 return nullptr; 3613 } 3614 } 3615 return S; 3616 } 3617 3618 /// Return true if the SCEV represents a value that may end up as a 3619 /// post-increment operation. 3620 static bool mayUsePostIncMode(const TargetTransformInfo &TTI, 3621 LSRUse &LU, const SCEV *S, const Loop *L, 3622 ScalarEvolution &SE) { 3623 if (LU.Kind != LSRUse::Address || 3624 !LU.AccessTy.getType()->isIntOrIntVectorTy()) 3625 return false; 3626 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 3627 if (!AR) 3628 return false; 3629 const SCEV *LoopStep = AR->getStepRecurrence(SE); 3630 if (!isa<SCEVConstant>(LoopStep)) 3631 return false; 3632 // Check if a post-indexed load/store can be used. 3633 if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) || 3634 TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) { 3635 const SCEV *LoopStart = AR->getStart(); 3636 if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L)) 3637 return true; 3638 } 3639 return false; 3640 } 3641 3642 /// Helper function for LSRInstance::GenerateReassociations. 3643 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 3644 const Formula &Base, 3645 unsigned Depth, size_t Idx, 3646 bool IsScaledReg) { 3647 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3648 // Don't generate reassociations for the base register of a value that 3649 // may generate a post-increment operator. The reason is that the 3650 // reassociations cause extra base+register formula to be created, 3651 // and possibly chosen, but the post-increment is more efficient. 3652 if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, BaseReg, L, SE)) 3653 return; 3654 SmallVector<const SCEV *, 8> AddOps; 3655 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE); 3656 if (Remainder) 3657 AddOps.push_back(Remainder); 3658 3659 if (AddOps.size() == 1) 3660 return; 3661 3662 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(), 3663 JE = AddOps.end(); 3664 J != JE; ++J) { 3665 // Loop-variant "unknown" values are uninteresting; we won't be able to 3666 // do anything meaningful with them. 3667 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L)) 3668 continue; 3669 3670 // Don't pull a constant into a register if the constant could be folded 3671 // into an immediate field. 3672 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3673 LU.AccessTy, *J, Base.getNumRegs() > 1)) 3674 continue; 3675 3676 // Collect all operands except *J. 3677 SmallVector<const SCEV *, 8> InnerAddOps( 3678 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J); 3679 InnerAddOps.append(std::next(J), 3680 ((const SmallVector<const SCEV *, 8> &)AddOps).end()); 3681 3682 // Don't leave just a constant behind in a register if the constant could 3683 // be folded into an immediate field. 3684 if (InnerAddOps.size() == 1 && 3685 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3686 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1)) 3687 continue; 3688 3689 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps); 3690 if (InnerSum->isZero()) 3691 continue; 3692 Formula F = Base; 3693 3694 // Add the remaining pieces of the add back into the new formula. 3695 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum); 3696 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 && 3697 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3698 InnerSumSC->getValue()->getZExtValue())) { 3699 F.UnfoldedOffset = 3700 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue(); 3701 if (IsScaledReg) 3702 F.ScaledReg = nullptr; 3703 else 3704 F.BaseRegs.erase(F.BaseRegs.begin() + Idx); 3705 } else if (IsScaledReg) 3706 F.ScaledReg = InnerSum; 3707 else 3708 F.BaseRegs[Idx] = InnerSum; 3709 3710 // Add J as its own register, or an unfolded immediate. 3711 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J); 3712 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 && 3713 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3714 SC->getValue()->getZExtValue())) 3715 F.UnfoldedOffset = 3716 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue(); 3717 else 3718 F.BaseRegs.push_back(*J); 3719 // We may have changed the number of register in base regs, adjust the 3720 // formula accordingly. 3721 F.canonicalize(*L); 3722 3723 if (InsertFormula(LU, LUIdx, F)) 3724 // If that formula hadn't been seen before, recurse to find more like 3725 // it. 3726 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2) 3727 // Because just Depth is not enough to bound compile time. 3728 // This means that every time AddOps.size() is greater 16^x we will add 3729 // x to Depth. 3730 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), 3731 Depth + 1 + (Log2_32(AddOps.size()) >> 2)); 3732 } 3733 } 3734 3735 /// Split out subexpressions from adds and the bases of addrecs. 3736 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx, 3737 Formula Base, unsigned Depth) { 3738 assert(Base.isCanonical(*L) && "Input must be in the canonical form"); 3739 // Arbitrarily cap recursion to protect compile time. 3740 if (Depth >= 3) 3741 return; 3742 3743 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3744 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i); 3745 3746 if (Base.Scale == 1) 3747 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, 3748 /* Idx */ -1, /* IsScaledReg */ true); 3749 } 3750 3751 /// Generate a formula consisting of all of the loop-dominating registers added 3752 /// into a single register. 3753 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx, 3754 Formula Base) { 3755 // This method is only interesting on a plurality of registers. 3756 if (Base.BaseRegs.size() + (Base.Scale == 1) + 3757 (Base.UnfoldedOffset != 0) <= 1) 3758 return; 3759 3760 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before 3761 // processing the formula. 3762 Base.unscale(); 3763 SmallVector<const SCEV *, 4> Ops; 3764 Formula NewBase = Base; 3765 NewBase.BaseRegs.clear(); 3766 Type *CombinedIntegerType = nullptr; 3767 for (const SCEV *BaseReg : Base.BaseRegs) { 3768 if (SE.properlyDominates(BaseReg, L->getHeader()) && 3769 !SE.hasComputableLoopEvolution(BaseReg, L)) { 3770 if (!CombinedIntegerType) 3771 CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType()); 3772 Ops.push_back(BaseReg); 3773 } 3774 else 3775 NewBase.BaseRegs.push_back(BaseReg); 3776 } 3777 3778 // If no register is relevant, we're done. 3779 if (Ops.size() == 0) 3780 return; 3781 3782 // Utility function for generating the required variants of the combined 3783 // registers. 3784 auto GenerateFormula = [&](const SCEV *Sum) { 3785 Formula F = NewBase; 3786 3787 // TODO: If Sum is zero, it probably means ScalarEvolution missed an 3788 // opportunity to fold something. For now, just ignore such cases 3789 // rather than proceed with zero in a register. 3790 if (Sum->isZero()) 3791 return; 3792 3793 F.BaseRegs.push_back(Sum); 3794 F.canonicalize(*L); 3795 (void)InsertFormula(LU, LUIdx, F); 3796 }; 3797 3798 // If we collected at least two registers, generate a formula combining them. 3799 if (Ops.size() > 1) { 3800 SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops. 3801 GenerateFormula(SE.getAddExpr(OpsCopy)); 3802 } 3803 3804 // If we have an unfolded offset, generate a formula combining it with the 3805 // registers collected. 3806 if (NewBase.UnfoldedOffset) { 3807 assert(CombinedIntegerType && "Missing a type for the unfolded offset"); 3808 Ops.push_back(SE.getConstant(CombinedIntegerType, NewBase.UnfoldedOffset, 3809 true)); 3810 NewBase.UnfoldedOffset = 0; 3811 GenerateFormula(SE.getAddExpr(Ops)); 3812 } 3813 } 3814 3815 /// Helper function for LSRInstance::GenerateSymbolicOffsets. 3816 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 3817 const Formula &Base, size_t Idx, 3818 bool IsScaledReg) { 3819 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3820 GlobalValue *GV = ExtractSymbol(G, SE); 3821 if (G->isZero() || !GV) 3822 return; 3823 Formula F = Base; 3824 F.BaseGV = GV; 3825 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3826 return; 3827 if (IsScaledReg) 3828 F.ScaledReg = G; 3829 else 3830 F.BaseRegs[Idx] = G; 3831 (void)InsertFormula(LU, LUIdx, F); 3832 } 3833 3834 /// Generate reuse formulae using symbolic offsets. 3835 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, 3836 Formula Base) { 3837 // We can't add a symbolic offset if the address already contains one. 3838 if (Base.BaseGV) return; 3839 3840 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3841 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i); 3842 if (Base.Scale == 1) 3843 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1, 3844 /* IsScaledReg */ true); 3845 } 3846 3847 /// Helper function for LSRInstance::GenerateConstantOffsets. 3848 void LSRInstance::GenerateConstantOffsetsImpl( 3849 LSRUse &LU, unsigned LUIdx, const Formula &Base, 3850 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) { 3851 3852 auto GenerateOffset = [&](const SCEV *G, int64_t Offset) { 3853 Formula F = Base; 3854 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset; 3855 3856 if (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) { 3857 // Add the offset to the base register. 3858 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G); 3859 // If it cancelled out, drop the base register, otherwise update it. 3860 if (NewG->isZero()) { 3861 if (IsScaledReg) { 3862 F.Scale = 0; 3863 F.ScaledReg = nullptr; 3864 } else 3865 F.deleteBaseReg(F.BaseRegs[Idx]); 3866 F.canonicalize(*L); 3867 } else if (IsScaledReg) 3868 F.ScaledReg = NewG; 3869 else 3870 F.BaseRegs[Idx] = NewG; 3871 3872 (void)InsertFormula(LU, LUIdx, F); 3873 } 3874 }; 3875 3876 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3877 3878 // With constant offsets and constant steps, we can generate pre-inc 3879 // accesses by having the offset equal the step. So, for access #0 with a 3880 // step of 8, we generate a G - 8 base which would require the first access 3881 // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer 3882 // for itself and hopefully becomes the base for other accesses. This means 3883 // means that a single pre-indexed access can be generated to become the new 3884 // base pointer for each iteration of the loop, resulting in no extra add/sub 3885 // instructions for pointer updating. 3886 if (AMK == TTI::AMK_PreIndexed && LU.Kind == LSRUse::Address) { 3887 if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) { 3888 if (auto *StepRec = 3889 dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) { 3890 const APInt &StepInt = StepRec->getAPInt(); 3891 int64_t Step = StepInt.isNegative() ? 3892 StepInt.getSExtValue() : StepInt.getZExtValue(); 3893 3894 for (int64_t Offset : Worklist) { 3895 Offset -= Step; 3896 GenerateOffset(G, Offset); 3897 } 3898 } 3899 } 3900 } 3901 for (int64_t Offset : Worklist) 3902 GenerateOffset(G, Offset); 3903 3904 int64_t Imm = ExtractImmediate(G, SE); 3905 if (G->isZero() || Imm == 0) 3906 return; 3907 Formula F = Base; 3908 F.BaseOffset = (uint64_t)F.BaseOffset + Imm; 3909 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3910 return; 3911 if (IsScaledReg) { 3912 F.ScaledReg = G; 3913 } else { 3914 F.BaseRegs[Idx] = G; 3915 // We may generate non canonical Formula if G is a recurrent expr reg 3916 // related with current loop while F.ScaledReg is not. 3917 F.canonicalize(*L); 3918 } 3919 (void)InsertFormula(LU, LUIdx, F); 3920 } 3921 3922 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets. 3923 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, 3924 Formula Base) { 3925 // TODO: For now, just add the min and max offset, because it usually isn't 3926 // worthwhile looking at everything inbetween. 3927 SmallVector<int64_t, 2> Worklist; 3928 Worklist.push_back(LU.MinOffset); 3929 if (LU.MaxOffset != LU.MinOffset) 3930 Worklist.push_back(LU.MaxOffset); 3931 3932 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3933 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i); 3934 if (Base.Scale == 1) 3935 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1, 3936 /* IsScaledReg */ true); 3937 } 3938 3939 /// For ICmpZero, check to see if we can scale up the comparison. For example, x 3940 /// == y -> x*c == y*c. 3941 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, 3942 Formula Base) { 3943 if (LU.Kind != LSRUse::ICmpZero) return; 3944 3945 // Determine the integer type for the base formula. 3946 Type *IntTy = Base.getType(); 3947 if (!IntTy) return; 3948 if (SE.getTypeSizeInBits(IntTy) > 64) return; 3949 3950 // Don't do this if there is more than one offset. 3951 if (LU.MinOffset != LU.MaxOffset) return; 3952 3953 // Check if transformation is valid. It is illegal to multiply pointer. 3954 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy()) 3955 return; 3956 for (const SCEV *BaseReg : Base.BaseRegs) 3957 if (BaseReg->getType()->isPointerTy()) 3958 return; 3959 assert(!Base.BaseGV && "ICmpZero use is not legal!"); 3960 3961 // Check each interesting stride. 3962 for (int64_t Factor : Factors) { 3963 // Check that Factor can be represented by IntTy 3964 if (!ConstantInt::isValueValidForType(IntTy, Factor)) 3965 continue; 3966 // Check that the multiplication doesn't overflow. 3967 if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1) 3968 continue; 3969 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor; 3970 assert(Factor != 0 && "Zero factor not expected!"); 3971 if (NewBaseOffset / Factor != Base.BaseOffset) 3972 continue; 3973 // If the offset will be truncated at this use, check that it is in bounds. 3974 if (!IntTy->isPointerTy() && 3975 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset)) 3976 continue; 3977 3978 // Check that multiplying with the use offset doesn't overflow. 3979 int64_t Offset = LU.MinOffset; 3980 if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1) 3981 continue; 3982 Offset = (uint64_t)Offset * Factor; 3983 if (Offset / Factor != LU.MinOffset) 3984 continue; 3985 // If the offset will be truncated at this use, check that it is in bounds. 3986 if (!IntTy->isPointerTy() && 3987 !ConstantInt::isValueValidForType(IntTy, Offset)) 3988 continue; 3989 3990 Formula F = Base; 3991 F.BaseOffset = NewBaseOffset; 3992 3993 // Check that this scale is legal. 3994 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F)) 3995 continue; 3996 3997 // Compensate for the use having MinOffset built into it. 3998 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset; 3999 4000 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 4001 4002 // Check that multiplying with each base register doesn't overflow. 4003 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) { 4004 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS); 4005 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i]) 4006 goto next; 4007 } 4008 4009 // Check that multiplying with the scaled register doesn't overflow. 4010 if (F.ScaledReg) { 4011 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS); 4012 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg) 4013 continue; 4014 } 4015 4016 // Check that multiplying with the unfolded offset doesn't overflow. 4017 if (F.UnfoldedOffset != 0) { 4018 if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() && 4019 Factor == -1) 4020 continue; 4021 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor; 4022 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset) 4023 continue; 4024 // If the offset will be truncated, check that it is in bounds. 4025 if (!IntTy->isPointerTy() && 4026 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset)) 4027 continue; 4028 } 4029 4030 // If we make it here and it's legal, add it. 4031 (void)InsertFormula(LU, LUIdx, F); 4032 next:; 4033 } 4034 } 4035 4036 /// Generate stride factor reuse formulae by making use of scaled-offset address 4037 /// modes, for example. 4038 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) { 4039 // Determine the integer type for the base formula. 4040 Type *IntTy = Base.getType(); 4041 if (!IntTy) return; 4042 4043 // If this Formula already has a scaled register, we can't add another one. 4044 // Try to unscale the formula to generate a better scale. 4045 if (Base.Scale != 0 && !Base.unscale()) 4046 return; 4047 4048 assert(Base.Scale == 0 && "unscale did not did its job!"); 4049 4050 // Check each interesting stride. 4051 for (int64_t Factor : Factors) { 4052 Base.Scale = Factor; 4053 Base.HasBaseReg = Base.BaseRegs.size() > 1; 4054 // Check whether this scale is going to be legal. 4055 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 4056 Base)) { 4057 // As a special-case, handle special out-of-loop Basic users specially. 4058 // TODO: Reconsider this special case. 4059 if (LU.Kind == LSRUse::Basic && 4060 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special, 4061 LU.AccessTy, Base) && 4062 LU.AllFixupsOutsideLoop) 4063 LU.Kind = LSRUse::Special; 4064 else 4065 continue; 4066 } 4067 // For an ICmpZero, negating a solitary base register won't lead to 4068 // new solutions. 4069 if (LU.Kind == LSRUse::ICmpZero && 4070 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV) 4071 continue; 4072 // For each addrec base reg, if its loop is current loop, apply the scale. 4073 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) { 4074 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]); 4075 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) { 4076 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 4077 if (FactorS->isZero()) 4078 continue; 4079 // Divide out the factor, ignoring high bits, since we'll be 4080 // scaling the value back up in the end. 4081 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) { 4082 // TODO: This could be optimized to avoid all the copying. 4083 Formula F = Base; 4084 F.ScaledReg = Quotient; 4085 F.deleteBaseReg(F.BaseRegs[i]); 4086 // The canonical representation of 1*reg is reg, which is already in 4087 // Base. In that case, do not try to insert the formula, it will be 4088 // rejected anyway. 4089 if (F.Scale == 1 && (F.BaseRegs.empty() || 4090 (AR->getLoop() != L && LU.AllFixupsOutsideLoop))) 4091 continue; 4092 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate 4093 // non canonical Formula with ScaledReg's loop not being L. 4094 if (F.Scale == 1 && LU.AllFixupsOutsideLoop) 4095 F.canonicalize(*L); 4096 (void)InsertFormula(LU, LUIdx, F); 4097 } 4098 } 4099 } 4100 } 4101 } 4102 4103 /// Generate reuse formulae from different IV types. 4104 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) { 4105 // Don't bother truncating symbolic values. 4106 if (Base.BaseGV) return; 4107 4108 // Determine the integer type for the base formula. 4109 Type *DstTy = Base.getType(); 4110 if (!DstTy) return; 4111 if (DstTy->isPointerTy()) 4112 return; 4113 4114 // It is invalid to extend a pointer type so exit early if ScaledReg or 4115 // any of the BaseRegs are pointers. 4116 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy()) 4117 return; 4118 if (any_of(Base.BaseRegs, 4119 [](const SCEV *S) { return S->getType()->isPointerTy(); })) 4120 return; 4121 4122 for (Type *SrcTy : Types) { 4123 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) { 4124 Formula F = Base; 4125 4126 // Sometimes SCEV is able to prove zero during ext transform. It may 4127 // happen if SCEV did not do all possible transforms while creating the 4128 // initial node (maybe due to depth limitations), but it can do them while 4129 // taking ext. 4130 if (F.ScaledReg) { 4131 const SCEV *NewScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy); 4132 if (NewScaledReg->isZero()) 4133 continue; 4134 F.ScaledReg = NewScaledReg; 4135 } 4136 bool HasZeroBaseReg = false; 4137 for (const SCEV *&BaseReg : F.BaseRegs) { 4138 const SCEV *NewBaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy); 4139 if (NewBaseReg->isZero()) { 4140 HasZeroBaseReg = true; 4141 break; 4142 } 4143 BaseReg = NewBaseReg; 4144 } 4145 if (HasZeroBaseReg) 4146 continue; 4147 4148 // TODO: This assumes we've done basic processing on all uses and 4149 // have an idea what the register usage is. 4150 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses)) 4151 continue; 4152 4153 F.canonicalize(*L); 4154 (void)InsertFormula(LU, LUIdx, F); 4155 } 4156 } 4157 } 4158 4159 namespace { 4160 4161 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer 4162 /// modifications so that the search phase doesn't have to worry about the data 4163 /// structures moving underneath it. 4164 struct WorkItem { 4165 size_t LUIdx; 4166 int64_t Imm; 4167 const SCEV *OrigReg; 4168 4169 WorkItem(size_t LI, int64_t I, const SCEV *R) 4170 : LUIdx(LI), Imm(I), OrigReg(R) {} 4171 4172 void print(raw_ostream &OS) const; 4173 void dump() const; 4174 }; 4175 4176 } // end anonymous namespace 4177 4178 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4179 void WorkItem::print(raw_ostream &OS) const { 4180 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx 4181 << " , add offset " << Imm; 4182 } 4183 4184 LLVM_DUMP_METHOD void WorkItem::dump() const { 4185 print(errs()); errs() << '\n'; 4186 } 4187 #endif 4188 4189 /// Look for registers which are a constant distance apart and try to form reuse 4190 /// opportunities between them. 4191 void LSRInstance::GenerateCrossUseConstantOffsets() { 4192 // Group the registers by their value without any added constant offset. 4193 using ImmMapTy = std::map<int64_t, const SCEV *>; 4194 4195 DenseMap<const SCEV *, ImmMapTy> Map; 4196 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap; 4197 SmallVector<const SCEV *, 8> Sequence; 4198 for (const SCEV *Use : RegUses) { 4199 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify. 4200 int64_t Imm = ExtractImmediate(Reg, SE); 4201 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy())); 4202 if (Pair.second) 4203 Sequence.push_back(Reg); 4204 Pair.first->second.insert(std::make_pair(Imm, Use)); 4205 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use); 4206 } 4207 4208 // Now examine each set of registers with the same base value. Build up 4209 // a list of work to do and do the work in a separate step so that we're 4210 // not adding formulae and register counts while we're searching. 4211 SmallVector<WorkItem, 32> WorkItems; 4212 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems; 4213 for (const SCEV *Reg : Sequence) { 4214 const ImmMapTy &Imms = Map.find(Reg)->second; 4215 4216 // It's not worthwhile looking for reuse if there's only one offset. 4217 if (Imms.size() == 1) 4218 continue; 4219 4220 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':'; 4221 for (const auto &Entry 4222 : Imms) dbgs() 4223 << ' ' << Entry.first; 4224 dbgs() << '\n'); 4225 4226 // Examine each offset. 4227 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end(); 4228 J != JE; ++J) { 4229 const SCEV *OrigReg = J->second; 4230 4231 int64_t JImm = J->first; 4232 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg); 4233 4234 if (!isa<SCEVConstant>(OrigReg) && 4235 UsedByIndicesMap[Reg].count() == 1) { 4236 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg 4237 << '\n'); 4238 continue; 4239 } 4240 4241 // Conservatively examine offsets between this orig reg a few selected 4242 // other orig regs. 4243 int64_t First = Imms.begin()->first; 4244 int64_t Last = std::prev(Imms.end())->first; 4245 // Compute (First + Last) / 2 without overflow using the fact that 4246 // First + Last = 2 * (First + Last) + (First ^ Last). 4247 int64_t Avg = (First & Last) + ((First ^ Last) >> 1); 4248 // If the result is negative and First is odd and Last even (or vice versa), 4249 // we rounded towards -inf. Add 1 in that case, to round towards 0. 4250 Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63)); 4251 ImmMapTy::const_iterator OtherImms[] = { 4252 Imms.begin(), std::prev(Imms.end()), 4253 Imms.lower_bound(Avg)}; 4254 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) { 4255 ImmMapTy::const_iterator M = OtherImms[i]; 4256 if (M == J || M == JE) continue; 4257 4258 // Compute the difference between the two. 4259 int64_t Imm = (uint64_t)JImm - M->first; 4260 for (unsigned LUIdx : UsedByIndices.set_bits()) 4261 // Make a memo of this use, offset, and register tuple. 4262 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second) 4263 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg)); 4264 } 4265 } 4266 } 4267 4268 Map.clear(); 4269 Sequence.clear(); 4270 UsedByIndicesMap.clear(); 4271 UniqueItems.clear(); 4272 4273 // Now iterate through the worklist and add new formulae. 4274 for (const WorkItem &WI : WorkItems) { 4275 size_t LUIdx = WI.LUIdx; 4276 LSRUse &LU = Uses[LUIdx]; 4277 int64_t Imm = WI.Imm; 4278 const SCEV *OrigReg = WI.OrigReg; 4279 4280 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType()); 4281 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm)); 4282 unsigned BitWidth = SE.getTypeSizeInBits(IntTy); 4283 4284 // TODO: Use a more targeted data structure. 4285 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) { 4286 Formula F = LU.Formulae[L]; 4287 // FIXME: The code for the scaled and unscaled registers looks 4288 // very similar but slightly different. Investigate if they 4289 // could be merged. That way, we would not have to unscale the 4290 // Formula. 4291 F.unscale(); 4292 // Use the immediate in the scaled register. 4293 if (F.ScaledReg == OrigReg) { 4294 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale; 4295 // Don't create 50 + reg(-50). 4296 if (F.referencesReg(SE.getSCEV( 4297 ConstantInt::get(IntTy, -(uint64_t)Offset)))) 4298 continue; 4299 Formula NewF = F; 4300 NewF.BaseOffset = Offset; 4301 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 4302 NewF)) 4303 continue; 4304 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg); 4305 4306 // If the new scale is a constant in a register, and adding the constant 4307 // value to the immediate would produce a value closer to zero than the 4308 // immediate itself, then the formula isn't worthwhile. 4309 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) 4310 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) && 4311 (C->getAPInt().abs() * APInt(BitWidth, F.Scale)) 4312 .ule(std::abs(NewF.BaseOffset))) 4313 continue; 4314 4315 // OK, looks good. 4316 NewF.canonicalize(*this->L); 4317 (void)InsertFormula(LU, LUIdx, NewF); 4318 } else { 4319 // Use the immediate in a base register. 4320 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) { 4321 const SCEV *BaseReg = F.BaseRegs[N]; 4322 if (BaseReg != OrigReg) 4323 continue; 4324 Formula NewF = F; 4325 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm; 4326 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, 4327 LU.Kind, LU.AccessTy, NewF)) { 4328 if (AMK == TTI::AMK_PostIndexed && 4329 mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE)) 4330 continue; 4331 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm)) 4332 continue; 4333 NewF = F; 4334 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm; 4335 } 4336 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg); 4337 4338 // If the new formula has a constant in a register, and adding the 4339 // constant value to the immediate would produce a value closer to 4340 // zero than the immediate itself, then the formula isn't worthwhile. 4341 for (const SCEV *NewReg : NewF.BaseRegs) 4342 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) 4343 if ((C->getAPInt() + NewF.BaseOffset) 4344 .abs() 4345 .slt(std::abs(NewF.BaseOffset)) && 4346 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >= 4347 countTrailingZeros<uint64_t>(NewF.BaseOffset)) 4348 goto skip_formula; 4349 4350 // Ok, looks good. 4351 NewF.canonicalize(*this->L); 4352 (void)InsertFormula(LU, LUIdx, NewF); 4353 break; 4354 skip_formula:; 4355 } 4356 } 4357 } 4358 } 4359 } 4360 4361 /// Generate formulae for each use. 4362 void 4363 LSRInstance::GenerateAllReuseFormulae() { 4364 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan 4365 // queries are more precise. 4366 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4367 LSRUse &LU = Uses[LUIdx]; 4368 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4369 GenerateReassociations(LU, LUIdx, LU.Formulae[i]); 4370 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4371 GenerateCombinations(LU, LUIdx, LU.Formulae[i]); 4372 } 4373 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4374 LSRUse &LU = Uses[LUIdx]; 4375 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4376 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]); 4377 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4378 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]); 4379 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4380 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]); 4381 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4382 GenerateScales(LU, LUIdx, LU.Formulae[i]); 4383 } 4384 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4385 LSRUse &LU = Uses[LUIdx]; 4386 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4387 GenerateTruncates(LU, LUIdx, LU.Formulae[i]); 4388 } 4389 4390 GenerateCrossUseConstantOffsets(); 4391 4392 LLVM_DEBUG(dbgs() << "\n" 4393 "After generating reuse formulae:\n"; 4394 print_uses(dbgs())); 4395 } 4396 4397 /// If there are multiple formulae with the same set of registers used 4398 /// by other uses, pick the best one and delete the others. 4399 void LSRInstance::FilterOutUndesirableDedicatedRegisters() { 4400 DenseSet<const SCEV *> VisitedRegs; 4401 SmallPtrSet<const SCEV *, 16> Regs; 4402 SmallPtrSet<const SCEV *, 16> LoserRegs; 4403 #ifndef NDEBUG 4404 bool ChangedFormulae = false; 4405 #endif 4406 4407 // Collect the best formula for each unique set of shared registers. This 4408 // is reset for each use. 4409 using BestFormulaeTy = 4410 DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>; 4411 4412 BestFormulaeTy BestFormulae; 4413 4414 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4415 LSRUse &LU = Uses[LUIdx]; 4416 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); 4417 dbgs() << '\n'); 4418 4419 bool Any = false; 4420 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); 4421 FIdx != NumForms; ++FIdx) { 4422 Formula &F = LU.Formulae[FIdx]; 4423 4424 // Some formulas are instant losers. For example, they may depend on 4425 // nonexistent AddRecs from other loops. These need to be filtered 4426 // immediately, otherwise heuristics could choose them over others leading 4427 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here 4428 // avoids the need to recompute this information across formulae using the 4429 // same bad AddRec. Passing LoserRegs is also essential unless we remove 4430 // the corresponding bad register from the Regs set. 4431 Cost CostF(L, SE, TTI, AMK); 4432 Regs.clear(); 4433 CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs); 4434 if (CostF.isLoser()) { 4435 // During initial formula generation, undesirable formulae are generated 4436 // by uses within other loops that have some non-trivial address mode or 4437 // use the postinc form of the IV. LSR needs to provide these formulae 4438 // as the basis of rediscovering the desired formula that uses an AddRec 4439 // corresponding to the existing phi. Once all formulae have been 4440 // generated, these initial losers may be pruned. 4441 LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs()); 4442 dbgs() << "\n"); 4443 } 4444 else { 4445 SmallVector<const SCEV *, 4> Key; 4446 for (const SCEV *Reg : F.BaseRegs) { 4447 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx)) 4448 Key.push_back(Reg); 4449 } 4450 if (F.ScaledReg && 4451 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx)) 4452 Key.push_back(F.ScaledReg); 4453 // Unstable sort by host order ok, because this is only used for 4454 // uniquifying. 4455 llvm::sort(Key); 4456 4457 std::pair<BestFormulaeTy::const_iterator, bool> P = 4458 BestFormulae.insert(std::make_pair(Key, FIdx)); 4459 if (P.second) 4460 continue; 4461 4462 Formula &Best = LU.Formulae[P.first->second]; 4463 4464 Cost CostBest(L, SE, TTI, AMK); 4465 Regs.clear(); 4466 CostBest.RateFormula(Best, Regs, VisitedRegs, LU); 4467 if (CostF.isLess(CostBest)) 4468 std::swap(F, Best); 4469 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4470 dbgs() << "\n" 4471 " in favor of formula "; 4472 Best.print(dbgs()); dbgs() << '\n'); 4473 } 4474 #ifndef NDEBUG 4475 ChangedFormulae = true; 4476 #endif 4477 LU.DeleteFormula(F); 4478 --FIdx; 4479 --NumForms; 4480 Any = true; 4481 } 4482 4483 // Now that we've filtered out some formulae, recompute the Regs set. 4484 if (Any) 4485 LU.RecomputeRegs(LUIdx, RegUses); 4486 4487 // Reset this to prepare for the next use. 4488 BestFormulae.clear(); 4489 } 4490 4491 LLVM_DEBUG(if (ChangedFormulae) { 4492 dbgs() << "\n" 4493 "After filtering out undesirable candidates:\n"; 4494 print_uses(dbgs()); 4495 }); 4496 } 4497 4498 /// Estimate the worst-case number of solutions the solver might have to 4499 /// consider. It almost never considers this many solutions because it prune the 4500 /// search space, but the pruning isn't always sufficient. 4501 size_t LSRInstance::EstimateSearchSpaceComplexity() const { 4502 size_t Power = 1; 4503 for (const LSRUse &LU : Uses) { 4504 size_t FSize = LU.Formulae.size(); 4505 if (FSize >= ComplexityLimit) { 4506 Power = ComplexityLimit; 4507 break; 4508 } 4509 Power *= FSize; 4510 if (Power >= ComplexityLimit) 4511 break; 4512 } 4513 return Power; 4514 } 4515 4516 /// When one formula uses a superset of the registers of another formula, it 4517 /// won't help reduce register pressure (though it may not necessarily hurt 4518 /// register pressure); remove it to simplify the system. 4519 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() { 4520 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4521 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4522 4523 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae " 4524 "which use a superset of registers used by other " 4525 "formulae.\n"); 4526 4527 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4528 LSRUse &LU = Uses[LUIdx]; 4529 bool Any = false; 4530 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4531 Formula &F = LU.Formulae[i]; 4532 // Look for a formula with a constant or GV in a register. If the use 4533 // also has a formula with that same value in an immediate field, 4534 // delete the one that uses a register. 4535 for (SmallVectorImpl<const SCEV *>::const_iterator 4536 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) { 4537 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) { 4538 Formula NewF = F; 4539 //FIXME: Formulas should store bitwidth to do wrapping properly. 4540 // See PR41034. 4541 NewF.BaseOffset += (uint64_t)C->getValue()->getSExtValue(); 4542 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4543 (I - F.BaseRegs.begin())); 4544 if (LU.HasFormulaWithSameRegs(NewF)) { 4545 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4546 dbgs() << '\n'); 4547 LU.DeleteFormula(F); 4548 --i; 4549 --e; 4550 Any = true; 4551 break; 4552 } 4553 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) { 4554 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) 4555 if (!F.BaseGV) { 4556 Formula NewF = F; 4557 NewF.BaseGV = GV; 4558 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4559 (I - F.BaseRegs.begin())); 4560 if (LU.HasFormulaWithSameRegs(NewF)) { 4561 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4562 dbgs() << '\n'); 4563 LU.DeleteFormula(F); 4564 --i; 4565 --e; 4566 Any = true; 4567 break; 4568 } 4569 } 4570 } 4571 } 4572 } 4573 if (Any) 4574 LU.RecomputeRegs(LUIdx, RegUses); 4575 } 4576 4577 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4578 } 4579 } 4580 4581 /// When there are many registers for expressions like A, A+1, A+2, etc., 4582 /// allocate a single register for them. 4583 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() { 4584 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4585 return; 4586 4587 LLVM_DEBUG( 4588 dbgs() << "The search space is too complex.\n" 4589 "Narrowing the search space by assuming that uses separated " 4590 "by a constant offset will use the same registers.\n"); 4591 4592 // This is especially useful for unrolled loops. 4593 4594 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4595 LSRUse &LU = Uses[LUIdx]; 4596 for (const Formula &F : LU.Formulae) { 4597 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1)) 4598 continue; 4599 4600 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU); 4601 if (!LUThatHas) 4602 continue; 4603 4604 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false, 4605 LU.Kind, LU.AccessTy)) 4606 continue; 4607 4608 LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n'); 4609 4610 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop; 4611 4612 // Transfer the fixups of LU to LUThatHas. 4613 for (LSRFixup &Fixup : LU.Fixups) { 4614 Fixup.Offset += F.BaseOffset; 4615 LUThatHas->pushFixup(Fixup); 4616 LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n'); 4617 } 4618 4619 // Delete formulae from the new use which are no longer legal. 4620 bool Any = false; 4621 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) { 4622 Formula &F = LUThatHas->Formulae[i]; 4623 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset, 4624 LUThatHas->Kind, LUThatHas->AccessTy, F)) { 4625 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4626 LUThatHas->DeleteFormula(F); 4627 --i; 4628 --e; 4629 Any = true; 4630 } 4631 } 4632 4633 if (Any) 4634 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses); 4635 4636 // Delete the old use. 4637 DeleteUse(LU, LUIdx); 4638 --LUIdx; 4639 --NumUses; 4640 break; 4641 } 4642 } 4643 4644 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4645 } 4646 4647 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that 4648 /// we've done more filtering, as it may be able to find more formulae to 4649 /// eliminate. 4650 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){ 4651 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4652 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4653 4654 LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out " 4655 "undesirable dedicated registers.\n"); 4656 4657 FilterOutUndesirableDedicatedRegisters(); 4658 4659 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4660 } 4661 } 4662 4663 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale. 4664 /// Pick the best one and delete the others. 4665 /// This narrowing heuristic is to keep as many formulae with different 4666 /// Scale and ScaledReg pair as possible while narrowing the search space. 4667 /// The benefit is that it is more likely to find out a better solution 4668 /// from a formulae set with more Scale and ScaledReg variations than 4669 /// a formulae set with the same Scale and ScaledReg. The picking winner 4670 /// reg heuristic will often keep the formulae with the same Scale and 4671 /// ScaledReg and filter others, and we want to avoid that if possible. 4672 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() { 4673 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4674 return; 4675 4676 LLVM_DEBUG( 4677 dbgs() << "The search space is too complex.\n" 4678 "Narrowing the search space by choosing the best Formula " 4679 "from the Formulae with the same Scale and ScaledReg.\n"); 4680 4681 // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse. 4682 using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>; 4683 4684 BestFormulaeTy BestFormulae; 4685 #ifndef NDEBUG 4686 bool ChangedFormulae = false; 4687 #endif 4688 DenseSet<const SCEV *> VisitedRegs; 4689 SmallPtrSet<const SCEV *, 16> Regs; 4690 4691 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4692 LSRUse &LU = Uses[LUIdx]; 4693 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); 4694 dbgs() << '\n'); 4695 4696 // Return true if Formula FA is better than Formula FB. 4697 auto IsBetterThan = [&](Formula &FA, Formula &FB) { 4698 // First we will try to choose the Formula with fewer new registers. 4699 // For a register used by current Formula, the more the register is 4700 // shared among LSRUses, the less we increase the register number 4701 // counter of the formula. 4702 size_t FARegNum = 0; 4703 for (const SCEV *Reg : FA.BaseRegs) { 4704 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); 4705 FARegNum += (NumUses - UsedByIndices.count() + 1); 4706 } 4707 size_t FBRegNum = 0; 4708 for (const SCEV *Reg : FB.BaseRegs) { 4709 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); 4710 FBRegNum += (NumUses - UsedByIndices.count() + 1); 4711 } 4712 if (FARegNum != FBRegNum) 4713 return FARegNum < FBRegNum; 4714 4715 // If the new register numbers are the same, choose the Formula with 4716 // less Cost. 4717 Cost CostFA(L, SE, TTI, AMK); 4718 Cost CostFB(L, SE, TTI, AMK); 4719 Regs.clear(); 4720 CostFA.RateFormula(FA, Regs, VisitedRegs, LU); 4721 Regs.clear(); 4722 CostFB.RateFormula(FB, Regs, VisitedRegs, LU); 4723 return CostFA.isLess(CostFB); 4724 }; 4725 4726 bool Any = false; 4727 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms; 4728 ++FIdx) { 4729 Formula &F = LU.Formulae[FIdx]; 4730 if (!F.ScaledReg) 4731 continue; 4732 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx}); 4733 if (P.second) 4734 continue; 4735 4736 Formula &Best = LU.Formulae[P.first->second]; 4737 if (IsBetterThan(F, Best)) 4738 std::swap(F, Best); 4739 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4740 dbgs() << "\n" 4741 " in favor of formula "; 4742 Best.print(dbgs()); dbgs() << '\n'); 4743 #ifndef NDEBUG 4744 ChangedFormulae = true; 4745 #endif 4746 LU.DeleteFormula(F); 4747 --FIdx; 4748 --NumForms; 4749 Any = true; 4750 } 4751 if (Any) 4752 LU.RecomputeRegs(LUIdx, RegUses); 4753 4754 // Reset this to prepare for the next use. 4755 BestFormulae.clear(); 4756 } 4757 4758 LLVM_DEBUG(if (ChangedFormulae) { 4759 dbgs() << "\n" 4760 "After filtering out undesirable candidates:\n"; 4761 print_uses(dbgs()); 4762 }); 4763 } 4764 4765 /// If we are over the complexity limit, filter out any post-inc prefering 4766 /// variables to only post-inc values. 4767 void LSRInstance::NarrowSearchSpaceByFilterPostInc() { 4768 if (AMK != TTI::AMK_PostIndexed) 4769 return; 4770 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4771 return; 4772 4773 LLVM_DEBUG(dbgs() << "The search space is too complex.\n" 4774 "Narrowing the search space by choosing the lowest " 4775 "register Formula for PostInc Uses.\n"); 4776 4777 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4778 LSRUse &LU = Uses[LUIdx]; 4779 4780 if (LU.Kind != LSRUse::Address) 4781 continue; 4782 if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) && 4783 !TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType())) 4784 continue; 4785 4786 size_t MinRegs = std::numeric_limits<size_t>::max(); 4787 for (const Formula &F : LU.Formulae) 4788 MinRegs = std::min(F.getNumRegs(), MinRegs); 4789 4790 bool Any = false; 4791 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms; 4792 ++FIdx) { 4793 Formula &F = LU.Formulae[FIdx]; 4794 if (F.getNumRegs() > MinRegs) { 4795 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4796 dbgs() << "\n"); 4797 LU.DeleteFormula(F); 4798 --FIdx; 4799 --NumForms; 4800 Any = true; 4801 } 4802 } 4803 if (Any) 4804 LU.RecomputeRegs(LUIdx, RegUses); 4805 4806 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4807 break; 4808 } 4809 4810 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4811 } 4812 4813 /// The function delete formulas with high registers number expectation. 4814 /// Assuming we don't know the value of each formula (already delete 4815 /// all inefficient), generate probability of not selecting for each 4816 /// register. 4817 /// For example, 4818 /// Use1: 4819 /// reg(a) + reg({0,+,1}) 4820 /// reg(a) + reg({-1,+,1}) + 1 4821 /// reg({a,+,1}) 4822 /// Use2: 4823 /// reg(b) + reg({0,+,1}) 4824 /// reg(b) + reg({-1,+,1}) + 1 4825 /// reg({b,+,1}) 4826 /// Use3: 4827 /// reg(c) + reg(b) + reg({0,+,1}) 4828 /// reg(c) + reg({b,+,1}) 4829 /// 4830 /// Probability of not selecting 4831 /// Use1 Use2 Use3 4832 /// reg(a) (1/3) * 1 * 1 4833 /// reg(b) 1 * (1/3) * (1/2) 4834 /// reg({0,+,1}) (2/3) * (2/3) * (1/2) 4835 /// reg({-1,+,1}) (2/3) * (2/3) * 1 4836 /// reg({a,+,1}) (2/3) * 1 * 1 4837 /// reg({b,+,1}) 1 * (2/3) * (2/3) 4838 /// reg(c) 1 * 1 * 0 4839 /// 4840 /// Now count registers number mathematical expectation for each formula: 4841 /// Note that for each use we exclude probability if not selecting for the use. 4842 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding 4843 /// probabilty 1/3 of not selecting for Use1). 4844 /// Use1: 4845 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted 4846 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted 4847 /// reg({a,+,1}) 1 4848 /// Use2: 4849 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted 4850 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted 4851 /// reg({b,+,1}) 2/3 4852 /// Use3: 4853 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted 4854 /// reg(c) + reg({b,+,1}) 1 + 2/3 4855 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() { 4856 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4857 return; 4858 // Ok, we have too many of formulae on our hands to conveniently handle. 4859 // Use a rough heuristic to thin out the list. 4860 4861 // Set of Regs wich will be 100% used in final solution. 4862 // Used in each formula of a solution (in example above this is reg(c)). 4863 // We can skip them in calculations. 4864 SmallPtrSet<const SCEV *, 4> UniqRegs; 4865 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4866 4867 // Map each register to probability of not selecting 4868 DenseMap <const SCEV *, float> RegNumMap; 4869 for (const SCEV *Reg : RegUses) { 4870 if (UniqRegs.count(Reg)) 4871 continue; 4872 float PNotSel = 1; 4873 for (const LSRUse &LU : Uses) { 4874 if (!LU.Regs.count(Reg)) 4875 continue; 4876 float P = LU.getNotSelectedProbability(Reg); 4877 if (P != 0.0) 4878 PNotSel *= P; 4879 else 4880 UniqRegs.insert(Reg); 4881 } 4882 RegNumMap.insert(std::make_pair(Reg, PNotSel)); 4883 } 4884 4885 LLVM_DEBUG( 4886 dbgs() << "Narrowing the search space by deleting costly formulas\n"); 4887 4888 // Delete formulas where registers number expectation is high. 4889 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4890 LSRUse &LU = Uses[LUIdx]; 4891 // If nothing to delete - continue. 4892 if (LU.Formulae.size() < 2) 4893 continue; 4894 // This is temporary solution to test performance. Float should be 4895 // replaced with round independent type (based on integers) to avoid 4896 // different results for different target builds. 4897 float FMinRegNum = LU.Formulae[0].getNumRegs(); 4898 float FMinARegNum = LU.Formulae[0].getNumRegs(); 4899 size_t MinIdx = 0; 4900 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4901 Formula &F = LU.Formulae[i]; 4902 float FRegNum = 0; 4903 float FARegNum = 0; 4904 for (const SCEV *BaseReg : F.BaseRegs) { 4905 if (UniqRegs.count(BaseReg)) 4906 continue; 4907 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4908 if (isa<SCEVAddRecExpr>(BaseReg)) 4909 FARegNum += 4910 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4911 } 4912 if (const SCEV *ScaledReg = F.ScaledReg) { 4913 if (!UniqRegs.count(ScaledReg)) { 4914 FRegNum += 4915 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4916 if (isa<SCEVAddRecExpr>(ScaledReg)) 4917 FARegNum += 4918 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4919 } 4920 } 4921 if (FMinRegNum > FRegNum || 4922 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) { 4923 FMinRegNum = FRegNum; 4924 FMinARegNum = FARegNum; 4925 MinIdx = i; 4926 } 4927 } 4928 LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs()); 4929 dbgs() << " with min reg num " << FMinRegNum << '\n'); 4930 if (MinIdx != 0) 4931 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]); 4932 while (LU.Formulae.size() != 1) { 4933 LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs()); 4934 dbgs() << '\n'); 4935 LU.Formulae.pop_back(); 4936 } 4937 LU.RecomputeRegs(LUIdx, RegUses); 4938 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula"); 4939 Formula &F = LU.Formulae[0]; 4940 LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n'); 4941 // When we choose the formula, the regs become unique. 4942 UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 4943 if (F.ScaledReg) 4944 UniqRegs.insert(F.ScaledReg); 4945 } 4946 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4947 } 4948 4949 /// Pick a register which seems likely to be profitable, and then in any use 4950 /// which has any reference to that register, delete all formulae which do not 4951 /// reference that register. 4952 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() { 4953 // With all other options exhausted, loop until the system is simple 4954 // enough to handle. 4955 SmallPtrSet<const SCEV *, 4> Taken; 4956 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4957 // Ok, we have too many of formulae on our hands to conveniently handle. 4958 // Use a rough heuristic to thin out the list. 4959 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4960 4961 // Pick the register which is used by the most LSRUses, which is likely 4962 // to be a good reuse register candidate. 4963 const SCEV *Best = nullptr; 4964 unsigned BestNum = 0; 4965 for (const SCEV *Reg : RegUses) { 4966 if (Taken.count(Reg)) 4967 continue; 4968 if (!Best) { 4969 Best = Reg; 4970 BestNum = RegUses.getUsedByIndices(Reg).count(); 4971 } else { 4972 unsigned Count = RegUses.getUsedByIndices(Reg).count(); 4973 if (Count > BestNum) { 4974 Best = Reg; 4975 BestNum = Count; 4976 } 4977 } 4978 } 4979 assert(Best && "Failed to find best LSRUse candidate"); 4980 4981 LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best 4982 << " will yield profitable reuse.\n"); 4983 Taken.insert(Best); 4984 4985 // In any use with formulae which references this register, delete formulae 4986 // which don't reference it. 4987 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4988 LSRUse &LU = Uses[LUIdx]; 4989 if (!LU.Regs.count(Best)) continue; 4990 4991 bool Any = false; 4992 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4993 Formula &F = LU.Formulae[i]; 4994 if (!F.referencesReg(Best)) { 4995 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4996 LU.DeleteFormula(F); 4997 --e; 4998 --i; 4999 Any = true; 5000 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?"); 5001 continue; 5002 } 5003 } 5004 5005 if (Any) 5006 LU.RecomputeRegs(LUIdx, RegUses); 5007 } 5008 5009 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 5010 } 5011 } 5012 5013 /// If there are an extraordinary number of formulae to choose from, use some 5014 /// rough heuristics to prune down the number of formulae. This keeps the main 5015 /// solver from taking an extraordinary amount of time in some worst-case 5016 /// scenarios. 5017 void LSRInstance::NarrowSearchSpaceUsingHeuristics() { 5018 NarrowSearchSpaceByDetectingSupersets(); 5019 NarrowSearchSpaceByCollapsingUnrolledCode(); 5020 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 5021 if (FilterSameScaledReg) 5022 NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); 5023 NarrowSearchSpaceByFilterPostInc(); 5024 if (LSRExpNarrow) 5025 NarrowSearchSpaceByDeletingCostlyFormulas(); 5026 else 5027 NarrowSearchSpaceByPickingWinnerRegs(); 5028 } 5029 5030 /// This is the recursive solver. 5031 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 5032 Cost &SolutionCost, 5033 SmallVectorImpl<const Formula *> &Workspace, 5034 const Cost &CurCost, 5035 const SmallPtrSet<const SCEV *, 16> &CurRegs, 5036 DenseSet<const SCEV *> &VisitedRegs) const { 5037 // Some ideas: 5038 // - prune more: 5039 // - use more aggressive filtering 5040 // - sort the formula so that the most profitable solutions are found first 5041 // - sort the uses too 5042 // - search faster: 5043 // - don't compute a cost, and then compare. compare while computing a cost 5044 // and bail early. 5045 // - track register sets with SmallBitVector 5046 5047 const LSRUse &LU = Uses[Workspace.size()]; 5048 5049 // If this use references any register that's already a part of the 5050 // in-progress solution, consider it a requirement that a formula must 5051 // reference that register in order to be considered. This prunes out 5052 // unprofitable searching. 5053 SmallSetVector<const SCEV *, 4> ReqRegs; 5054 for (const SCEV *S : CurRegs) 5055 if (LU.Regs.count(S)) 5056 ReqRegs.insert(S); 5057 5058 SmallPtrSet<const SCEV *, 16> NewRegs; 5059 Cost NewCost(L, SE, TTI, AMK); 5060 for (const Formula &F : LU.Formulae) { 5061 // Ignore formulae which may not be ideal in terms of register reuse of 5062 // ReqRegs. The formula should use all required registers before 5063 // introducing new ones. 5064 // This can sometimes (notably when trying to favour postinc) lead to 5065 // sub-optimial decisions. There it is best left to the cost modelling to 5066 // get correct. 5067 if (AMK != TTI::AMK_PostIndexed || LU.Kind != LSRUse::Address) { 5068 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size()); 5069 for (const SCEV *Reg : ReqRegs) { 5070 if ((F.ScaledReg && F.ScaledReg == Reg) || 5071 is_contained(F.BaseRegs, Reg)) { 5072 --NumReqRegsToFind; 5073 if (NumReqRegsToFind == 0) 5074 break; 5075 } 5076 } 5077 if (NumReqRegsToFind != 0) { 5078 // If none of the formulae satisfied the required registers, then we could 5079 // clear ReqRegs and try again. Currently, we simply give up in this case. 5080 continue; 5081 } 5082 } 5083 5084 // Evaluate the cost of the current formula. If it's already worse than 5085 // the current best, prune the search at that point. 5086 NewCost = CurCost; 5087 NewRegs = CurRegs; 5088 NewCost.RateFormula(F, NewRegs, VisitedRegs, LU); 5089 if (NewCost.isLess(SolutionCost)) { 5090 Workspace.push_back(&F); 5091 if (Workspace.size() != Uses.size()) { 5092 SolveRecurse(Solution, SolutionCost, Workspace, NewCost, 5093 NewRegs, VisitedRegs); 5094 if (F.getNumRegs() == 1 && Workspace.size() == 1) 5095 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]); 5096 } else { 5097 LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs()); 5098 dbgs() << ".\nRegs:\n"; 5099 for (const SCEV *S : NewRegs) dbgs() 5100 << "- " << *S << "\n"; 5101 dbgs() << '\n'); 5102 5103 SolutionCost = NewCost; 5104 Solution = Workspace; 5105 } 5106 Workspace.pop_back(); 5107 } 5108 } 5109 } 5110 5111 /// Choose one formula from each use. Return the results in the given Solution 5112 /// vector. 5113 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const { 5114 SmallVector<const Formula *, 8> Workspace; 5115 Cost SolutionCost(L, SE, TTI, AMK); 5116 SolutionCost.Lose(); 5117 Cost CurCost(L, SE, TTI, AMK); 5118 SmallPtrSet<const SCEV *, 16> CurRegs; 5119 DenseSet<const SCEV *> VisitedRegs; 5120 Workspace.reserve(Uses.size()); 5121 5122 // SolveRecurse does all the work. 5123 SolveRecurse(Solution, SolutionCost, Workspace, CurCost, 5124 CurRegs, VisitedRegs); 5125 if (Solution.empty()) { 5126 LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n"); 5127 return; 5128 } 5129 5130 // Ok, we've now made all our decisions. 5131 LLVM_DEBUG(dbgs() << "\n" 5132 "The chosen solution requires "; 5133 SolutionCost.print(dbgs()); dbgs() << ":\n"; 5134 for (size_t i = 0, e = Uses.size(); i != e; ++i) { 5135 dbgs() << " "; 5136 Uses[i].print(dbgs()); 5137 dbgs() << "\n" 5138 " "; 5139 Solution[i]->print(dbgs()); 5140 dbgs() << '\n'; 5141 }); 5142 5143 assert(Solution.size() == Uses.size() && "Malformed solution!"); 5144 } 5145 5146 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as 5147 /// we can go while still being dominated by the input positions. This helps 5148 /// canonicalize the insert position, which encourages sharing. 5149 BasicBlock::iterator 5150 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP, 5151 const SmallVectorImpl<Instruction *> &Inputs) 5152 const { 5153 Instruction *Tentative = &*IP; 5154 while (true) { 5155 bool AllDominate = true; 5156 Instruction *BetterPos = nullptr; 5157 // Don't bother attempting to insert before a catchswitch, their basic block 5158 // cannot have other non-PHI instructions. 5159 if (isa<CatchSwitchInst>(Tentative)) 5160 return IP; 5161 5162 for (Instruction *Inst : Inputs) { 5163 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) { 5164 AllDominate = false; 5165 break; 5166 } 5167 // Attempt to find an insert position in the middle of the block, 5168 // instead of at the end, so that it can be used for other expansions. 5169 if (Tentative->getParent() == Inst->getParent() && 5170 (!BetterPos || !DT.dominates(Inst, BetterPos))) 5171 BetterPos = &*std::next(BasicBlock::iterator(Inst)); 5172 } 5173 if (!AllDominate) 5174 break; 5175 if (BetterPos) 5176 IP = BetterPos->getIterator(); 5177 else 5178 IP = Tentative->getIterator(); 5179 5180 const Loop *IPLoop = LI.getLoopFor(IP->getParent()); 5181 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0; 5182 5183 BasicBlock *IDom; 5184 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) { 5185 if (!Rung) return IP; 5186 Rung = Rung->getIDom(); 5187 if (!Rung) return IP; 5188 IDom = Rung->getBlock(); 5189 5190 // Don't climb into a loop though. 5191 const Loop *IDomLoop = LI.getLoopFor(IDom); 5192 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0; 5193 if (IDomDepth <= IPLoopDepth && 5194 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop)) 5195 break; 5196 } 5197 5198 Tentative = IDom->getTerminator(); 5199 } 5200 5201 return IP; 5202 } 5203 5204 /// Determine an input position which will be dominated by the operands and 5205 /// which will dominate the result. 5206 BasicBlock::iterator 5207 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP, 5208 const LSRFixup &LF, 5209 const LSRUse &LU, 5210 SCEVExpander &Rewriter) const { 5211 // Collect some instructions which must be dominated by the 5212 // expanding replacement. These must be dominated by any operands that 5213 // will be required in the expansion. 5214 SmallVector<Instruction *, 4> Inputs; 5215 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace)) 5216 Inputs.push_back(I); 5217 if (LU.Kind == LSRUse::ICmpZero) 5218 if (Instruction *I = 5219 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1))) 5220 Inputs.push_back(I); 5221 if (LF.PostIncLoops.count(L)) { 5222 if (LF.isUseFullyOutsideLoop(L)) 5223 Inputs.push_back(L->getLoopLatch()->getTerminator()); 5224 else 5225 Inputs.push_back(IVIncInsertPos); 5226 } 5227 // The expansion must also be dominated by the increment positions of any 5228 // loops it for which it is using post-inc mode. 5229 for (const Loop *PIL : LF.PostIncLoops) { 5230 if (PIL == L) continue; 5231 5232 // Be dominated by the loop exit. 5233 SmallVector<BasicBlock *, 4> ExitingBlocks; 5234 PIL->getExitingBlocks(ExitingBlocks); 5235 if (!ExitingBlocks.empty()) { 5236 BasicBlock *BB = ExitingBlocks[0]; 5237 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i) 5238 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]); 5239 Inputs.push_back(BB->getTerminator()); 5240 } 5241 } 5242 5243 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() 5244 && !isa<DbgInfoIntrinsic>(LowestIP) && 5245 "Insertion point must be a normal instruction"); 5246 5247 // Then, climb up the immediate dominator tree as far as we can go while 5248 // still being dominated by the input positions. 5249 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs); 5250 5251 // Don't insert instructions before PHI nodes. 5252 while (isa<PHINode>(IP)) ++IP; 5253 5254 // Ignore landingpad instructions. 5255 while (IP->isEHPad()) ++IP; 5256 5257 // Ignore debug intrinsics. 5258 while (isa<DbgInfoIntrinsic>(IP)) ++IP; 5259 5260 // Set IP below instructions recently inserted by SCEVExpander. This keeps the 5261 // IP consistent across expansions and allows the previously inserted 5262 // instructions to be reused by subsequent expansion. 5263 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP) 5264 ++IP; 5265 5266 return IP; 5267 } 5268 5269 /// Emit instructions for the leading candidate expression for this LSRUse (this 5270 /// is called "expanding"). 5271 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF, 5272 const Formula &F, BasicBlock::iterator IP, 5273 SCEVExpander &Rewriter, 5274 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5275 if (LU.RigidFormula) 5276 return LF.OperandValToReplace; 5277 5278 // Determine an input position which will be dominated by the operands and 5279 // which will dominate the result. 5280 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter); 5281 Rewriter.setInsertPoint(&*IP); 5282 5283 // Inform the Rewriter if we have a post-increment use, so that it can 5284 // perform an advantageous expansion. 5285 Rewriter.setPostInc(LF.PostIncLoops); 5286 5287 // This is the type that the user actually needs. 5288 Type *OpTy = LF.OperandValToReplace->getType(); 5289 // This will be the type that we'll initially expand to. 5290 Type *Ty = F.getType(); 5291 if (!Ty) 5292 // No type known; just expand directly to the ultimate type. 5293 Ty = OpTy; 5294 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy)) 5295 // Expand directly to the ultimate type if it's the right size. 5296 Ty = OpTy; 5297 // This is the type to do integer arithmetic in. 5298 Type *IntTy = SE.getEffectiveSCEVType(Ty); 5299 5300 // Build up a list of operands to add together to form the full base. 5301 SmallVector<const SCEV *, 8> Ops; 5302 5303 // Expand the BaseRegs portion. 5304 for (const SCEV *Reg : F.BaseRegs) { 5305 assert(!Reg->isZero() && "Zero allocated in a base register!"); 5306 5307 // If we're expanding for a post-inc user, make the post-inc adjustment. 5308 Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE); 5309 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr))); 5310 } 5311 5312 // Expand the ScaledReg portion. 5313 Value *ICmpScaledV = nullptr; 5314 if (F.Scale != 0) { 5315 const SCEV *ScaledS = F.ScaledReg; 5316 5317 // If we're expanding for a post-inc user, make the post-inc adjustment. 5318 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops); 5319 ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE); 5320 5321 if (LU.Kind == LSRUse::ICmpZero) { 5322 // Expand ScaleReg as if it was part of the base regs. 5323 if (F.Scale == 1) 5324 Ops.push_back( 5325 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr))); 5326 else { 5327 // An interesting way of "folding" with an icmp is to use a negated 5328 // scale, which we'll implement by inserting it into the other operand 5329 // of the icmp. 5330 assert(F.Scale == -1 && 5331 "The only scale supported by ICmpZero uses is -1!"); 5332 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr); 5333 } 5334 } else { 5335 // Otherwise just expand the scaled register and an explicit scale, 5336 // which is expected to be matched as part of the address. 5337 5338 // Flush the operand list to suppress SCEVExpander hoisting address modes. 5339 // Unless the addressing mode will not be folded. 5340 if (!Ops.empty() && LU.Kind == LSRUse::Address && 5341 isAMCompletelyFolded(TTI, LU, F)) { 5342 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr); 5343 Ops.clear(); 5344 Ops.push_back(SE.getUnknown(FullV)); 5345 } 5346 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)); 5347 if (F.Scale != 1) 5348 ScaledS = 5349 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale)); 5350 Ops.push_back(ScaledS); 5351 } 5352 } 5353 5354 // Expand the GV portion. 5355 if (F.BaseGV) { 5356 // Flush the operand list to suppress SCEVExpander hoisting. 5357 if (!Ops.empty()) { 5358 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), IntTy); 5359 Ops.clear(); 5360 Ops.push_back(SE.getUnknown(FullV)); 5361 } 5362 Ops.push_back(SE.getUnknown(F.BaseGV)); 5363 } 5364 5365 // Flush the operand list to suppress SCEVExpander hoisting of both folded and 5366 // unfolded offsets. LSR assumes they both live next to their uses. 5367 if (!Ops.empty()) { 5368 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 5369 Ops.clear(); 5370 Ops.push_back(SE.getUnknown(FullV)); 5371 } 5372 5373 // Expand the immediate portion. 5374 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset; 5375 if (Offset != 0) { 5376 if (LU.Kind == LSRUse::ICmpZero) { 5377 // The other interesting way of "folding" with an ICmpZero is to use a 5378 // negated immediate. 5379 if (!ICmpScaledV) 5380 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset); 5381 else { 5382 Ops.push_back(SE.getUnknown(ICmpScaledV)); 5383 ICmpScaledV = ConstantInt::get(IntTy, Offset); 5384 } 5385 } else { 5386 // Just add the immediate values. These again are expected to be matched 5387 // as part of the address. 5388 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset))); 5389 } 5390 } 5391 5392 // Expand the unfolded offset portion. 5393 int64_t UnfoldedOffset = F.UnfoldedOffset; 5394 if (UnfoldedOffset != 0) { 5395 // Just add the immediate values. 5396 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, 5397 UnfoldedOffset))); 5398 } 5399 5400 // Emit instructions summing all the operands. 5401 const SCEV *FullS = Ops.empty() ? 5402 SE.getConstant(IntTy, 0) : 5403 SE.getAddExpr(Ops); 5404 Value *FullV = Rewriter.expandCodeFor(FullS, Ty); 5405 5406 // We're done expanding now, so reset the rewriter. 5407 Rewriter.clearPostInc(); 5408 5409 // An ICmpZero Formula represents an ICmp which we're handling as a 5410 // comparison against zero. Now that we've expanded an expression for that 5411 // form, update the ICmp's other operand. 5412 if (LU.Kind == LSRUse::ICmpZero) { 5413 ICmpInst *CI = cast<ICmpInst>(LF.UserInst); 5414 if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1))) 5415 DeadInsts.emplace_back(OperandIsInstr); 5416 assert(!F.BaseGV && "ICmp does not support folding a global value and " 5417 "a scale at the same time!"); 5418 if (F.Scale == -1) { 5419 if (ICmpScaledV->getType() != OpTy) { 5420 Instruction *Cast = 5421 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false, 5422 OpTy, false), 5423 ICmpScaledV, OpTy, "tmp", CI); 5424 ICmpScaledV = Cast; 5425 } 5426 CI->setOperand(1, ICmpScaledV); 5427 } else { 5428 // A scale of 1 means that the scale has been expanded as part of the 5429 // base regs. 5430 assert((F.Scale == 0 || F.Scale == 1) && 5431 "ICmp does not support folding a global value and " 5432 "a scale at the same time!"); 5433 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy), 5434 -(uint64_t)Offset); 5435 if (C->getType() != OpTy) 5436 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 5437 OpTy, false), 5438 C, OpTy); 5439 5440 CI->setOperand(1, C); 5441 } 5442 } 5443 5444 return FullV; 5445 } 5446 5447 /// Helper for Rewrite. PHI nodes are special because the use of their operands 5448 /// effectively happens in their predecessor blocks, so the expression may need 5449 /// to be expanded in multiple places. 5450 void LSRInstance::RewriteForPHI( 5451 PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F, 5452 SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5453 DenseMap<BasicBlock *, Value *> Inserted; 5454 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5455 if (PN->getIncomingValue(i) == LF.OperandValToReplace) { 5456 bool needUpdateFixups = false; 5457 BasicBlock *BB = PN->getIncomingBlock(i); 5458 5459 // If this is a critical edge, split the edge so that we do not insert 5460 // the code on all predecessor/successor paths. We do this unless this 5461 // is the canonical backedge for this loop, which complicates post-inc 5462 // users. 5463 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 && 5464 !isa<IndirectBrInst>(BB->getTerminator()) && 5465 !isa<CatchSwitchInst>(BB->getTerminator())) { 5466 BasicBlock *Parent = PN->getParent(); 5467 Loop *PNLoop = LI.getLoopFor(Parent); 5468 if (!PNLoop || Parent != PNLoop->getHeader()) { 5469 // Split the critical edge. 5470 BasicBlock *NewBB = nullptr; 5471 if (!Parent->isLandingPad()) { 5472 NewBB = 5473 SplitCriticalEdge(BB, Parent, 5474 CriticalEdgeSplittingOptions(&DT, &LI, MSSAU) 5475 .setMergeIdenticalEdges() 5476 .setKeepOneInputPHIs()); 5477 } else { 5478 SmallVector<BasicBlock*, 2> NewBBs; 5479 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI); 5480 NewBB = NewBBs[0]; 5481 } 5482 // If NewBB==NULL, then SplitCriticalEdge refused to split because all 5483 // phi predecessors are identical. The simple thing to do is skip 5484 // splitting in this case rather than complicate the API. 5485 if (NewBB) { 5486 // If PN is outside of the loop and BB is in the loop, we want to 5487 // move the block to be immediately before the PHI block, not 5488 // immediately after BB. 5489 if (L->contains(BB) && !L->contains(PN)) 5490 NewBB->moveBefore(PN->getParent()); 5491 5492 // Splitting the edge can reduce the number of PHI entries we have. 5493 e = PN->getNumIncomingValues(); 5494 BB = NewBB; 5495 i = PN->getBasicBlockIndex(BB); 5496 5497 needUpdateFixups = true; 5498 } 5499 } 5500 } 5501 5502 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair = 5503 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr))); 5504 if (!Pair.second) 5505 PN->setIncomingValue(i, Pair.first->second); 5506 else { 5507 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(), 5508 Rewriter, DeadInsts); 5509 5510 // If this is reuse-by-noop-cast, insert the noop cast. 5511 Type *OpTy = LF.OperandValToReplace->getType(); 5512 if (FullV->getType() != OpTy) 5513 FullV = 5514 CastInst::Create(CastInst::getCastOpcode(FullV, false, 5515 OpTy, false), 5516 FullV, LF.OperandValToReplace->getType(), 5517 "tmp", BB->getTerminator()); 5518 5519 PN->setIncomingValue(i, FullV); 5520 Pair.first->second = FullV; 5521 } 5522 5523 // If LSR splits critical edge and phi node has other pending 5524 // fixup operands, we need to update those pending fixups. Otherwise 5525 // formulae will not be implemented completely and some instructions 5526 // will not be eliminated. 5527 if (needUpdateFixups) { 5528 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) 5529 for (LSRFixup &Fixup : Uses[LUIdx].Fixups) 5530 // If fixup is supposed to rewrite some operand in the phi 5531 // that was just updated, it may be already moved to 5532 // another phi node. Such fixup requires update. 5533 if (Fixup.UserInst == PN) { 5534 // Check if the operand we try to replace still exists in the 5535 // original phi. 5536 bool foundInOriginalPHI = false; 5537 for (const auto &val : PN->incoming_values()) 5538 if (val == Fixup.OperandValToReplace) { 5539 foundInOriginalPHI = true; 5540 break; 5541 } 5542 5543 // If fixup operand found in original PHI - nothing to do. 5544 if (foundInOriginalPHI) 5545 continue; 5546 5547 // Otherwise it might be moved to another PHI and requires update. 5548 // If fixup operand not found in any of the incoming blocks that 5549 // means we have already rewritten it - nothing to do. 5550 for (const auto &Block : PN->blocks()) 5551 for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I); 5552 ++I) { 5553 PHINode *NewPN = cast<PHINode>(I); 5554 for (const auto &val : NewPN->incoming_values()) 5555 if (val == Fixup.OperandValToReplace) 5556 Fixup.UserInst = NewPN; 5557 } 5558 } 5559 } 5560 } 5561 } 5562 5563 /// Emit instructions for the leading candidate expression for this LSRUse (this 5564 /// is called "expanding"), and update the UserInst to reference the newly 5565 /// expanded value. 5566 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF, 5567 const Formula &F, SCEVExpander &Rewriter, 5568 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5569 // First, find an insertion point that dominates UserInst. For PHI nodes, 5570 // find the nearest block which dominates all the relevant uses. 5571 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) { 5572 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts); 5573 } else { 5574 Value *FullV = 5575 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts); 5576 5577 // If this is reuse-by-noop-cast, insert the noop cast. 5578 Type *OpTy = LF.OperandValToReplace->getType(); 5579 if (FullV->getType() != OpTy) { 5580 Instruction *Cast = 5581 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false), 5582 FullV, OpTy, "tmp", LF.UserInst); 5583 FullV = Cast; 5584 } 5585 5586 // Update the user. ICmpZero is handled specially here (for now) because 5587 // Expand may have updated one of the operands of the icmp already, and 5588 // its new value may happen to be equal to LF.OperandValToReplace, in 5589 // which case doing replaceUsesOfWith leads to replacing both operands 5590 // with the same value. TODO: Reorganize this. 5591 if (LU.Kind == LSRUse::ICmpZero) 5592 LF.UserInst->setOperand(0, FullV); 5593 else 5594 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV); 5595 } 5596 5597 if (auto *OperandIsInstr = dyn_cast<Instruction>(LF.OperandValToReplace)) 5598 DeadInsts.emplace_back(OperandIsInstr); 5599 } 5600 5601 // Check if there are any loop exit values which are only used once within the 5602 // loop which may potentially be optimized with a call to rewriteLoopExitValue. 5603 static bool LoopExitValHasSingleUse(Loop *L) { 5604 BasicBlock *ExitBB = L->getExitBlock(); 5605 if (!ExitBB) 5606 return false; 5607 5608 for (PHINode &ExitPhi : ExitBB->phis()) { 5609 if (ExitPhi.getNumIncomingValues() != 1) 5610 break; 5611 5612 BasicBlock *Pred = ExitPhi.getIncomingBlock(0); 5613 Value *IVNext = ExitPhi.getIncomingValueForBlock(Pred); 5614 // One use would be the exit phi node, and there should be only one other 5615 // use for this to be considered. 5616 if (IVNext->getNumUses() == 2) 5617 return true; 5618 } 5619 return false; 5620 } 5621 5622 /// Rewrite all the fixup locations with new values, following the chosen 5623 /// solution. 5624 void LSRInstance::ImplementSolution( 5625 const SmallVectorImpl<const Formula *> &Solution) { 5626 // Keep track of instructions we may have made dead, so that 5627 // we can remove them after we are done working. 5628 SmallVector<WeakTrackingVH, 16> DeadInsts; 5629 5630 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(), "lsr", 5631 false); 5632 #ifndef NDEBUG 5633 Rewriter.setDebugType(DEBUG_TYPE); 5634 #endif 5635 Rewriter.disableCanonicalMode(); 5636 Rewriter.enableLSRMode(); 5637 Rewriter.setIVIncInsertPos(L, IVIncInsertPos); 5638 5639 // Mark phi nodes that terminate chains so the expander tries to reuse them. 5640 for (const IVChain &Chain : IVChainVec) { 5641 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst())) 5642 Rewriter.setChainedPhi(PN); 5643 } 5644 5645 // Expand the new value definitions and update the users. 5646 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) 5647 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) { 5648 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts); 5649 Changed = true; 5650 } 5651 5652 for (const IVChain &Chain : IVChainVec) { 5653 GenerateIVChain(Chain, Rewriter, DeadInsts); 5654 Changed = true; 5655 } 5656 5657 for (const WeakVH &IV : Rewriter.getInsertedIVs()) 5658 if (IV && dyn_cast<Instruction>(&*IV)->getParent()) 5659 ScalarEvolutionIVs.push_back(IV); 5660 5661 // Clean up after ourselves. This must be done before deleting any 5662 // instructions. 5663 Rewriter.clear(); 5664 5665 Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, 5666 &TLI, MSSAU); 5667 5668 // In our cost analysis above, we assume that each addrec consumes exactly 5669 // one register, and arrange to have increments inserted just before the 5670 // latch to maximimize the chance this is true. However, if we reused 5671 // existing IVs, we now need to move the increments to match our 5672 // expectations. Otherwise, our cost modeling results in us having a 5673 // chosen a non-optimal result for the actual schedule. (And yes, this 5674 // scheduling decision does impact later codegen.) 5675 for (PHINode &PN : L->getHeader()->phis()) { 5676 BinaryOperator *BO = nullptr; 5677 Value *Start = nullptr, *Step = nullptr; 5678 if (!matchSimpleRecurrence(&PN, BO, Start, Step)) 5679 continue; 5680 5681 switch (BO->getOpcode()) { 5682 case Instruction::Sub: 5683 if (BO->getOperand(0) != &PN) 5684 // sub is non-commutative - match handling elsewhere in LSR 5685 continue; 5686 break; 5687 case Instruction::Add: 5688 break; 5689 default: 5690 continue; 5691 }; 5692 5693 if (!isa<Constant>(Step)) 5694 // If not a constant step, might increase register pressure 5695 // (We assume constants have been canonicalized to RHS) 5696 continue; 5697 5698 if (BO->getParent() == IVIncInsertPos->getParent()) 5699 // Only bother moving across blocks. Isel can handle block local case. 5700 continue; 5701 5702 // Can we legally schedule inc at the desired point? 5703 if (!llvm::all_of(BO->uses(), 5704 [&](Use &U) {return DT.dominates(IVIncInsertPos, U);})) 5705 continue; 5706 BO->moveBefore(IVIncInsertPos); 5707 Changed = true; 5708 } 5709 5710 5711 } 5712 5713 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, 5714 DominatorTree &DT, LoopInfo &LI, 5715 const TargetTransformInfo &TTI, AssumptionCache &AC, 5716 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU) 5717 : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L), 5718 MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 0 ? 5719 PreferredAddresingMode : TTI.getPreferredAddressingMode(L, &SE)) { 5720 // If LoopSimplify form is not available, stay out of trouble. 5721 if (!L->isLoopSimplifyForm()) 5722 return; 5723 5724 // If there's no interesting work to be done, bail early. 5725 if (IU.empty()) return; 5726 5727 // If there's too much analysis to be done, bail early. We won't be able to 5728 // model the problem anyway. 5729 unsigned NumUsers = 0; 5730 for (const IVStrideUse &U : IU) { 5731 if (++NumUsers > MaxIVUsers) { 5732 (void)U; 5733 LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U 5734 << "\n"); 5735 return; 5736 } 5737 // Bail out if we have a PHI on an EHPad that gets a value from a 5738 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is 5739 // no good place to stick any instructions. 5740 if (auto *PN = dyn_cast<PHINode>(U.getUser())) { 5741 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI(); 5742 if (isa<FuncletPadInst>(FirstNonPHI) || 5743 isa<CatchSwitchInst>(FirstNonPHI)) 5744 for (BasicBlock *PredBB : PN->blocks()) 5745 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI())) 5746 return; 5747 } 5748 } 5749 5750 LLVM_DEBUG(dbgs() << "\nLSR on loop "; 5751 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false); 5752 dbgs() << ":\n"); 5753 5754 // First, perform some low-level loop optimizations. 5755 OptimizeShadowIV(); 5756 OptimizeLoopTermCond(); 5757 5758 // If loop preparation eliminates all interesting IV users, bail. 5759 if (IU.empty()) return; 5760 5761 // Skip nested loops until we can model them better with formulae. 5762 if (!L->isInnermost()) { 5763 LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n"); 5764 return; 5765 } 5766 5767 // Start collecting data and preparing for the solver. 5768 // If number of registers is not the major cost, we cannot benefit from the 5769 // current profitable chain optimization which is based on number of 5770 // registers. 5771 // FIXME: add profitable chain optimization for other kinds major cost, for 5772 // example number of instructions. 5773 if (TTI.isNumRegsMajorCostOfLSR() || StressIVChain) 5774 CollectChains(); 5775 CollectInterestingTypesAndFactors(); 5776 CollectFixupsAndInitialFormulae(); 5777 CollectLoopInvariantFixupsAndFormulae(); 5778 5779 if (Uses.empty()) 5780 return; 5781 5782 LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n"; 5783 print_uses(dbgs())); 5784 5785 // Now use the reuse data to generate a bunch of interesting ways 5786 // to formulate the values needed for the uses. 5787 GenerateAllReuseFormulae(); 5788 5789 FilterOutUndesirableDedicatedRegisters(); 5790 NarrowSearchSpaceUsingHeuristics(); 5791 5792 SmallVector<const Formula *, 8> Solution; 5793 Solve(Solution); 5794 5795 // Release memory that is no longer needed. 5796 Factors.clear(); 5797 Types.clear(); 5798 RegUses.clear(); 5799 5800 if (Solution.empty()) 5801 return; 5802 5803 #ifndef NDEBUG 5804 // Formulae should be legal. 5805 for (const LSRUse &LU : Uses) { 5806 for (const Formula &F : LU.Formulae) 5807 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 5808 F) && "Illegal formula generated!"); 5809 }; 5810 #endif 5811 5812 // Now that we've decided what we want, make it so. 5813 ImplementSolution(Solution); 5814 } 5815 5816 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5817 void LSRInstance::print_factors_and_types(raw_ostream &OS) const { 5818 if (Factors.empty() && Types.empty()) return; 5819 5820 OS << "LSR has identified the following interesting factors and types: "; 5821 bool First = true; 5822 5823 for (int64_t Factor : Factors) { 5824 if (!First) OS << ", "; 5825 First = false; 5826 OS << '*' << Factor; 5827 } 5828 5829 for (Type *Ty : Types) { 5830 if (!First) OS << ", "; 5831 First = false; 5832 OS << '(' << *Ty << ')'; 5833 } 5834 OS << '\n'; 5835 } 5836 5837 void LSRInstance::print_fixups(raw_ostream &OS) const { 5838 OS << "LSR is examining the following fixup sites:\n"; 5839 for (const LSRUse &LU : Uses) 5840 for (const LSRFixup &LF : LU.Fixups) { 5841 dbgs() << " "; 5842 LF.print(OS); 5843 OS << '\n'; 5844 } 5845 } 5846 5847 void LSRInstance::print_uses(raw_ostream &OS) const { 5848 OS << "LSR is examining the following uses:\n"; 5849 for (const LSRUse &LU : Uses) { 5850 dbgs() << " "; 5851 LU.print(OS); 5852 OS << '\n'; 5853 for (const Formula &F : LU.Formulae) { 5854 OS << " "; 5855 F.print(OS); 5856 OS << '\n'; 5857 } 5858 } 5859 } 5860 5861 void LSRInstance::print(raw_ostream &OS) const { 5862 print_factors_and_types(OS); 5863 print_fixups(OS); 5864 print_uses(OS); 5865 } 5866 5867 LLVM_DUMP_METHOD void LSRInstance::dump() const { 5868 print(errs()); errs() << '\n'; 5869 } 5870 #endif 5871 5872 namespace { 5873 5874 class LoopStrengthReduce : public LoopPass { 5875 public: 5876 static char ID; // Pass ID, replacement for typeid 5877 5878 LoopStrengthReduce(); 5879 5880 private: 5881 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 5882 void getAnalysisUsage(AnalysisUsage &AU) const override; 5883 }; 5884 5885 } // end anonymous namespace 5886 5887 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) { 5888 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry()); 5889 } 5890 5891 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const { 5892 // We split critical edges, so we change the CFG. However, we do update 5893 // many analyses if they are around. 5894 AU.addPreservedID(LoopSimplifyID); 5895 5896 AU.addRequired<LoopInfoWrapperPass>(); 5897 AU.addPreserved<LoopInfoWrapperPass>(); 5898 AU.addRequiredID(LoopSimplifyID); 5899 AU.addRequired<DominatorTreeWrapperPass>(); 5900 AU.addPreserved<DominatorTreeWrapperPass>(); 5901 AU.addRequired<ScalarEvolutionWrapperPass>(); 5902 AU.addPreserved<ScalarEvolutionWrapperPass>(); 5903 AU.addRequired<AssumptionCacheTracker>(); 5904 AU.addRequired<TargetLibraryInfoWrapperPass>(); 5905 // Requiring LoopSimplify a second time here prevents IVUsers from running 5906 // twice, since LoopSimplify was invalidated by running ScalarEvolution. 5907 AU.addRequiredID(LoopSimplifyID); 5908 AU.addRequired<IVUsersWrapperPass>(); 5909 AU.addPreserved<IVUsersWrapperPass>(); 5910 AU.addRequired<TargetTransformInfoWrapperPass>(); 5911 AU.addPreserved<MemorySSAWrapperPass>(); 5912 } 5913 5914 namespace { 5915 5916 /// Enables more convenient iteration over a DWARF expression vector. 5917 static iterator_range<llvm::DIExpression::expr_op_iterator> 5918 ToDwarfOpIter(SmallVectorImpl<uint64_t> &Expr) { 5919 llvm::DIExpression::expr_op_iterator Begin = 5920 llvm::DIExpression::expr_op_iterator(Expr.begin()); 5921 llvm::DIExpression::expr_op_iterator End = 5922 llvm::DIExpression::expr_op_iterator(Expr.end()); 5923 return {Begin, End}; 5924 } 5925 5926 struct SCEVDbgValueBuilder { 5927 SCEVDbgValueBuilder() = default; 5928 SCEVDbgValueBuilder(const SCEVDbgValueBuilder &Base) { clone(Base); } 5929 5930 void clone(const SCEVDbgValueBuilder &Base) { 5931 LocationOps = Base.LocationOps; 5932 Expr = Base.Expr; 5933 } 5934 5935 void clear() { 5936 LocationOps.clear(); 5937 Expr.clear(); 5938 } 5939 5940 /// The DIExpression as we translate the SCEV. 5941 SmallVector<uint64_t, 6> Expr; 5942 /// The location ops of the DIExpression. 5943 SmallVector<Value *, 2> LocationOps; 5944 5945 void pushOperator(uint64_t Op) { Expr.push_back(Op); } 5946 void pushUInt(uint64_t Operand) { Expr.push_back(Operand); } 5947 5948 /// Add a DW_OP_LLVM_arg to the expression, followed by the index of the value 5949 /// in the set of values referenced by the expression. 5950 void pushLocation(llvm::Value *V) { 5951 Expr.push_back(llvm::dwarf::DW_OP_LLVM_arg); 5952 auto *It = std::find(LocationOps.begin(), LocationOps.end(), V); 5953 unsigned ArgIndex = 0; 5954 if (It != LocationOps.end()) { 5955 ArgIndex = std::distance(LocationOps.begin(), It); 5956 } else { 5957 ArgIndex = LocationOps.size(); 5958 LocationOps.push_back(V); 5959 } 5960 Expr.push_back(ArgIndex); 5961 } 5962 5963 void pushValue(const SCEVUnknown *U) { 5964 llvm::Value *V = cast<SCEVUnknown>(U)->getValue(); 5965 pushLocation(V); 5966 } 5967 5968 bool pushConst(const SCEVConstant *C) { 5969 if (C->getAPInt().getMinSignedBits() > 64) 5970 return false; 5971 Expr.push_back(llvm::dwarf::DW_OP_consts); 5972 Expr.push_back(C->getAPInt().getSExtValue()); 5973 return true; 5974 } 5975 5976 // Iterating the expression as DWARF ops is convenient when updating 5977 // DWARF_OP_LLVM_args. 5978 iterator_range<llvm::DIExpression::expr_op_iterator> expr_ops() { 5979 return ToDwarfOpIter(Expr); 5980 } 5981 5982 /// Several SCEV types are sequences of the same arithmetic operator applied 5983 /// to constants and values that may be extended or truncated. 5984 bool pushArithmeticExpr(const llvm::SCEVCommutativeExpr *CommExpr, 5985 uint64_t DwarfOp) { 5986 assert((isa<llvm::SCEVAddExpr>(CommExpr) || isa<SCEVMulExpr>(CommExpr)) && 5987 "Expected arithmetic SCEV type"); 5988 bool Success = true; 5989 unsigned EmitOperator = 0; 5990 for (auto &Op : CommExpr->operands()) { 5991 Success &= pushSCEV(Op); 5992 5993 if (EmitOperator >= 1) 5994 pushOperator(DwarfOp); 5995 ++EmitOperator; 5996 } 5997 return Success; 5998 } 5999 6000 // TODO: Identify and omit noop casts. 6001 bool pushCast(const llvm::SCEVCastExpr *C, bool IsSigned) { 6002 const llvm::SCEV *Inner = C->getOperand(0); 6003 const llvm::Type *Type = C->getType(); 6004 uint64_t ToWidth = Type->getIntegerBitWidth(); 6005 bool Success = pushSCEV(Inner); 6006 uint64_t CastOps[] = {dwarf::DW_OP_LLVM_convert, ToWidth, 6007 IsSigned ? llvm::dwarf::DW_ATE_signed 6008 : llvm::dwarf::DW_ATE_unsigned}; 6009 for (const auto &Op : CastOps) 6010 pushOperator(Op); 6011 return Success; 6012 } 6013 6014 // TODO: MinMax - although these haven't been encountered in the test suite. 6015 bool pushSCEV(const llvm::SCEV *S) { 6016 bool Success = true; 6017 if (const SCEVConstant *StartInt = dyn_cast<SCEVConstant>(S)) { 6018 Success &= pushConst(StartInt); 6019 6020 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6021 if (!U->getValue()) 6022 return false; 6023 pushLocation(U->getValue()); 6024 6025 } else if (const SCEVMulExpr *MulRec = dyn_cast<SCEVMulExpr>(S)) { 6026 Success &= pushArithmeticExpr(MulRec, llvm::dwarf::DW_OP_mul); 6027 6028 } else if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6029 Success &= pushSCEV(UDiv->getLHS()); 6030 Success &= pushSCEV(UDiv->getRHS()); 6031 pushOperator(llvm::dwarf::DW_OP_div); 6032 6033 } else if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(S)) { 6034 // Assert if a new and unknown SCEVCastEXpr type is encountered. 6035 assert((isa<SCEVZeroExtendExpr>(Cast) || isa<SCEVTruncateExpr>(Cast) || 6036 isa<SCEVPtrToIntExpr>(Cast) || isa<SCEVSignExtendExpr>(Cast)) && 6037 "Unexpected cast type in SCEV."); 6038 Success &= pushCast(Cast, (isa<SCEVSignExtendExpr>(Cast))); 6039 6040 } else if (const SCEVAddExpr *AddExpr = dyn_cast<SCEVAddExpr>(S)) { 6041 Success &= pushArithmeticExpr(AddExpr, llvm::dwarf::DW_OP_plus); 6042 6043 } else if (isa<SCEVAddRecExpr>(S)) { 6044 // Nested SCEVAddRecExpr are generated by nested loops and are currently 6045 // unsupported. 6046 return false; 6047 6048 } else { 6049 return false; 6050 } 6051 return Success; 6052 } 6053 6054 /// Return true if the combination of arithmetic operator and underlying 6055 /// SCEV constant value is an identity function. 6056 bool isIdentityFunction(uint64_t Op, const SCEV *S) { 6057 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 6058 if (C->getAPInt().getMinSignedBits() > 64) 6059 return false; 6060 int64_t I = C->getAPInt().getSExtValue(); 6061 switch (Op) { 6062 case llvm::dwarf::DW_OP_plus: 6063 case llvm::dwarf::DW_OP_minus: 6064 return I == 0; 6065 case llvm::dwarf::DW_OP_mul: 6066 case llvm::dwarf::DW_OP_div: 6067 return I == 1; 6068 } 6069 } 6070 return false; 6071 } 6072 6073 /// Convert a SCEV of a value to a DIExpression that is pushed onto the 6074 /// builder's expression stack. The stack should already contain an 6075 /// expression for the iteration count, so that it can be multiplied by 6076 /// the stride and added to the start. 6077 /// Components of the expression are omitted if they are an identity function. 6078 /// Chain (non-affine) SCEVs are not supported. 6079 bool SCEVToValueExpr(const llvm::SCEVAddRecExpr &SAR, ScalarEvolution &SE) { 6080 assert(SAR.isAffine() && "Expected affine SCEV"); 6081 // TODO: Is this check needed? 6082 if (isa<SCEVAddRecExpr>(SAR.getStart())) 6083 return false; 6084 6085 const SCEV *Start = SAR.getStart(); 6086 const SCEV *Stride = SAR.getStepRecurrence(SE); 6087 6088 // Skip pushing arithmetic noops. 6089 if (!isIdentityFunction(llvm::dwarf::DW_OP_mul, Stride)) { 6090 if (!pushSCEV(Stride)) 6091 return false; 6092 pushOperator(llvm::dwarf::DW_OP_mul); 6093 } 6094 if (!isIdentityFunction(llvm::dwarf::DW_OP_plus, Start)) { 6095 if (!pushSCEV(Start)) 6096 return false; 6097 pushOperator(llvm::dwarf::DW_OP_plus); 6098 } 6099 return true; 6100 } 6101 6102 /// Create an expression that is an offset from a value (usually the IV). 6103 void createOffsetExpr(int64_t Offset, Value *OffsetValue) { 6104 pushLocation(OffsetValue); 6105 DIExpression::appendOffset(Expr, Offset); 6106 LLVM_DEBUG( 6107 dbgs() << "scev-salvage: Generated IV offset expression. Offset: " 6108 << std::to_string(Offset) << "\n"); 6109 } 6110 6111 /// Combine a translation of the SCEV and the IV to create an expression that 6112 /// recovers a location's value. 6113 /// returns true if an expression was created. 6114 bool createIterCountExpr(const SCEV *S, 6115 const SCEVDbgValueBuilder &IterationCount, 6116 ScalarEvolution &SE) { 6117 // SCEVs for SSA values are most frquently of the form 6118 // {start,+,stride}, but sometimes they are ({start,+,stride} + %a + ..). 6119 // This is because %a is a PHI node that is not the IV. However, these 6120 // SCEVs have not been observed to result in debuginfo-lossy optimisations, 6121 // so its not expected this point will be reached. 6122 if (!isa<SCEVAddRecExpr>(S)) 6123 return false; 6124 6125 LLVM_DEBUG(dbgs() << "scev-salvage: Location to salvage SCEV: " << *S 6126 << '\n'); 6127 6128 const auto *Rec = cast<SCEVAddRecExpr>(S); 6129 if (!Rec->isAffine()) 6130 return false; 6131 6132 if (S->getExpressionSize() > MaxSCEVSalvageExpressionSize) 6133 return false; 6134 6135 // Initialise a new builder with the iteration count expression. In 6136 // combination with the value's SCEV this enables recovery. 6137 clone(IterationCount); 6138 if (!SCEVToValueExpr(*Rec, SE)) 6139 return false; 6140 6141 return true; 6142 } 6143 6144 /// Convert a SCEV of a value to a DIExpression that is pushed onto the 6145 /// builder's expression stack. The stack should already contain an 6146 /// expression for the iteration count, so that it can be multiplied by 6147 /// the stride and added to the start. 6148 /// Components of the expression are omitted if they are an identity function. 6149 bool SCEVToIterCountExpr(const llvm::SCEVAddRecExpr &SAR, 6150 ScalarEvolution &SE) { 6151 assert(SAR.isAffine() && "Expected affine SCEV"); 6152 if (isa<SCEVAddRecExpr>(SAR.getStart())) { 6153 LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV. Unsupported nested AddRec: " 6154 << SAR << '\n'); 6155 return false; 6156 } 6157 const SCEV *Start = SAR.getStart(); 6158 const SCEV *Stride = SAR.getStepRecurrence(SE); 6159 6160 // Skip pushing arithmetic noops. 6161 if (!isIdentityFunction(llvm::dwarf::DW_OP_minus, Start)) { 6162 if (!pushSCEV(Start)) 6163 return false; 6164 pushOperator(llvm::dwarf::DW_OP_minus); 6165 } 6166 if (!isIdentityFunction(llvm::dwarf::DW_OP_div, Stride)) { 6167 if (!pushSCEV(Stride)) 6168 return false; 6169 pushOperator(llvm::dwarf::DW_OP_div); 6170 } 6171 return true; 6172 } 6173 6174 // Append the current expression and locations to a location list and an 6175 // expression list. Modify the DW_OP_LLVM_arg indexes to account for 6176 // the locations already present in the destination list. 6177 void appendToVectors(SmallVectorImpl<uint64_t> &DestExpr, 6178 SmallVectorImpl<Value *> &DestLocations) { 6179 assert(!DestLocations.empty() && 6180 "Expected the locations vector to contain the IV"); 6181 // The DWARF_OP_LLVM_arg arguments of the expression being appended must be 6182 // modified to account for the locations already in the destination vector. 6183 // All builders contain the IV as the first location op. 6184 assert(!LocationOps.empty() && 6185 "Expected the location ops to contain the IV."); 6186 // DestIndexMap[n] contains the index in DestLocations for the nth 6187 // location in this SCEVDbgValueBuilder. 6188 SmallVector<uint64_t, 2> DestIndexMap; 6189 for (const auto &Op : LocationOps) { 6190 auto It = find(DestLocations, Op); 6191 if (It != DestLocations.end()) { 6192 // Location already exists in DestLocations, reuse existing ArgIndex. 6193 DestIndexMap.push_back(std::distance(DestLocations.begin(), It)); 6194 continue; 6195 } 6196 // Location is not in DestLocations, add it. 6197 DestIndexMap.push_back(DestLocations.size()); 6198 DestLocations.push_back(Op); 6199 } 6200 6201 for (const auto &Op : expr_ops()) { 6202 if (Op.getOp() != dwarf::DW_OP_LLVM_arg) { 6203 Op.appendToVector(DestExpr); 6204 continue; 6205 } 6206 6207 DestExpr.push_back(dwarf::DW_OP_LLVM_arg); 6208 // `DW_OP_LLVM_arg n` represents the nth LocationOp in this SCEV, 6209 // DestIndexMap[n] contains its new index in DestLocations. 6210 uint64_t NewIndex = DestIndexMap[Op.getArg(0)]; 6211 DestExpr.push_back(NewIndex); 6212 } 6213 } 6214 }; 6215 6216 /// Holds all the required data to salvage a dbg.value using the pre-LSR SCEVs 6217 /// and DIExpression. 6218 struct DVIRecoveryRec { 6219 DVIRecoveryRec(DbgValueInst *DbgValue) 6220 : DVI(DbgValue), Expr(DbgValue->getExpression()), 6221 HadLocationArgList(false) {} 6222 6223 DbgValueInst *DVI; 6224 DIExpression *Expr; 6225 bool HadLocationArgList; 6226 SmallVector<WeakVH, 2> LocationOps; 6227 SmallVector<const llvm::SCEV *, 2> SCEVs; 6228 SmallVector<std::unique_ptr<SCEVDbgValueBuilder>, 2> RecoveryExprs; 6229 6230 void clear() { 6231 for (auto &RE : RecoveryExprs) 6232 RE.reset(); 6233 RecoveryExprs.clear(); 6234 } 6235 6236 ~DVIRecoveryRec() { clear(); } 6237 }; 6238 } // namespace 6239 6240 /// Returns the total number of DW_OP_llvm_arg operands in the expression. 6241 /// This helps in determining if a DIArglist is necessary or can be omitted from 6242 /// the dbg.value. 6243 static unsigned numLLVMArgOps(SmallVectorImpl<uint64_t> &Expr) { 6244 auto expr_ops = ToDwarfOpIter(Expr); 6245 unsigned Count = 0; 6246 for (auto Op : expr_ops) 6247 if (Op.getOp() == dwarf::DW_OP_LLVM_arg) 6248 Count++; 6249 return Count; 6250 } 6251 6252 /// Overwrites DVI with the location and Ops as the DIExpression. This will 6253 /// create an invalid expression if Ops has any dwarf::DW_OP_llvm_arg operands, 6254 /// because a DIArglist is not created for the first argument of the dbg.value. 6255 static void updateDVIWithLocation(DbgValueInst &DVI, Value *Location, 6256 SmallVectorImpl<uint64_t> &Ops) { 6257 assert( 6258 numLLVMArgOps(Ops) == 0 && 6259 "Expected expression that does not contain any DW_OP_llvm_arg operands."); 6260 DVI.setRawLocation(ValueAsMetadata::get(Location)); 6261 DVI.setExpression(DIExpression::get(DVI.getContext(), Ops)); 6262 } 6263 6264 /// Overwrite DVI with locations placed into a DIArglist. 6265 static void updateDVIWithLocations(DbgValueInst &DVI, 6266 SmallVectorImpl<Value *> &Locations, 6267 SmallVectorImpl<uint64_t> &Ops) { 6268 assert(numLLVMArgOps(Ops) != 0 && 6269 "Expected expression that references DIArglist locations using " 6270 "DW_OP_llvm_arg operands."); 6271 SmallVector<ValueAsMetadata *, 3> MetadataLocs; 6272 for (Value *V : Locations) 6273 MetadataLocs.push_back(ValueAsMetadata::get(V)); 6274 auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs); 6275 DVI.setRawLocation(llvm::DIArgList::get(DVI.getContext(), ValArrayRef)); 6276 DVI.setExpression(DIExpression::get(DVI.getContext(), Ops)); 6277 } 6278 6279 /// Write the new expression and new location ops for the dbg.value. If possible 6280 /// reduce the szie of the dbg.value intrinsic by omitting DIArglist. This 6281 /// can be omitted if: 6282 /// 1. There is only a single location, refenced by a single DW_OP_llvm_arg. 6283 /// 2. The DW_OP_LLVM_arg is the first operand in the expression. 6284 static void UpdateDbgValueInst(DVIRecoveryRec &DVIRec, 6285 SmallVectorImpl<Value *> &NewLocationOps, 6286 SmallVectorImpl<uint64_t> &NewExpr) { 6287 unsigned NumLLVMArgs = numLLVMArgOps(NewExpr); 6288 if (NumLLVMArgs == 0) { 6289 // Location assumed to be on the stack. 6290 updateDVIWithLocation(*DVIRec.DVI, NewLocationOps[0], NewExpr); 6291 } else if (NumLLVMArgs == 1 && NewExpr[0] == dwarf::DW_OP_LLVM_arg) { 6292 // There is only a single DW_OP_llvm_arg at the start of the expression, 6293 // so it can be omitted along with DIArglist. 6294 assert(NewExpr[1] == 0 && 6295 "Lone LLVM_arg in a DIExpression should refer to location-op 0."); 6296 llvm::SmallVector<uint64_t, 6> ShortenedOps(llvm::drop_begin(NewExpr, 2)); 6297 updateDVIWithLocation(*DVIRec.DVI, NewLocationOps[0], ShortenedOps); 6298 } else { 6299 // Multiple DW_OP_llvm_arg, so DIArgList is strictly necessary. 6300 updateDVIWithLocations(*DVIRec.DVI, NewLocationOps, NewExpr); 6301 } 6302 6303 // If the DIExpression was previously empty then add the stack terminator. 6304 // Non-empty expressions have only had elements inserted into them and so the 6305 // terminator should already be present e.g. stack_value or fragment. 6306 DIExpression *SalvageExpr = DVIRec.DVI->getExpression(); 6307 if (!DVIRec.Expr->isComplex() && SalvageExpr->isComplex()) { 6308 SalvageExpr = DIExpression::append(SalvageExpr, {dwarf::DW_OP_stack_value}); 6309 DVIRec.DVI->setExpression(SalvageExpr); 6310 } 6311 } 6312 6313 /// Cached location ops may be erased during LSR, in which case an undef is 6314 /// required when restoring from the cache. The type of that location is no 6315 /// longer available, so just use int8. The undef will be replaced by one or 6316 /// more locations later when a SCEVDbgValueBuilder selects alternative 6317 /// locations to use for the salvage. 6318 static Value *getValueOrUndef(WeakVH &VH, LLVMContext &C) { 6319 return (VH) ? VH : UndefValue::get(llvm::Type::getInt8Ty(C)); 6320 } 6321 6322 /// Restore the DVI's pre-LSR arguments. Substitute undef for any erased values. 6323 static void restorePreTransformState(DVIRecoveryRec &DVIRec) { 6324 LLVM_DEBUG(dbgs() << "scev-salvage: restore dbg.value to pre-LSR state\n" 6325 << "scev-salvage: post-LSR: " << *DVIRec.DVI << '\n'); 6326 assert(DVIRec.Expr && "Expected an expression"); 6327 DVIRec.DVI->setExpression(DVIRec.Expr); 6328 6329 // Even a single location-op may be inside a DIArgList and referenced with 6330 // DW_OP_LLVM_arg, which is valid only with a DIArgList. 6331 if (!DVIRec.HadLocationArgList) { 6332 assert(DVIRec.LocationOps.size() == 1 && 6333 "Unexpected number of location ops."); 6334 // LSR's unsuccessful salvage attempt may have added DIArgList, which in 6335 // this case was not present before, so force the location back to a single 6336 // uncontained Value. 6337 Value *CachedValue = 6338 getValueOrUndef(DVIRec.LocationOps[0], DVIRec.DVI->getContext()); 6339 DVIRec.DVI->setRawLocation(ValueAsMetadata::get(CachedValue)); 6340 } else { 6341 SmallVector<ValueAsMetadata *, 3> MetadataLocs; 6342 for (WeakVH VH : DVIRec.LocationOps) { 6343 Value *CachedValue = getValueOrUndef(VH, DVIRec.DVI->getContext()); 6344 MetadataLocs.push_back(ValueAsMetadata::get(CachedValue)); 6345 } 6346 auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(MetadataLocs); 6347 DVIRec.DVI->setRawLocation( 6348 llvm::DIArgList::get(DVIRec.DVI->getContext(), ValArrayRef)); 6349 } 6350 LLVM_DEBUG(dbgs() << "scev-salvage: pre-LSR: " << *DVIRec.DVI << '\n'); 6351 } 6352 6353 static bool SalvageDVI(llvm::Loop *L, ScalarEvolution &SE, 6354 llvm::PHINode *LSRInductionVar, DVIRecoveryRec &DVIRec, 6355 const SCEV *SCEVInductionVar, 6356 SCEVDbgValueBuilder IterCountExpr) { 6357 if (!DVIRec.DVI->isUndef()) 6358 return false; 6359 6360 // LSR may have caused several changes to the dbg.value in the failed salvage 6361 // attempt. So restore the DIExpression, the location ops and also the 6362 // location ops format, which is always DIArglist for multiple ops, but only 6363 // sometimes for a single op. 6364 restorePreTransformState(DVIRec); 6365 6366 // LocationOpIndexMap[i] will store the post-LSR location index of 6367 // the non-optimised out location at pre-LSR index i. 6368 SmallVector<int64_t, 2> LocationOpIndexMap; 6369 LocationOpIndexMap.assign(DVIRec.LocationOps.size(), -1); 6370 SmallVector<Value *, 2> NewLocationOps; 6371 NewLocationOps.push_back(LSRInductionVar); 6372 6373 for (unsigned i = 0; i < DVIRec.LocationOps.size(); i++) { 6374 WeakVH VH = DVIRec.LocationOps[i]; 6375 // Place the locations not optimised out in the list first, avoiding 6376 // inserts later. The map is used to update the DIExpression's 6377 // DW_OP_LLVM_arg arguments as the expression is updated. 6378 if (VH && !isa<UndefValue>(VH)) { 6379 NewLocationOps.push_back(VH); 6380 LocationOpIndexMap[i] = NewLocationOps.size() - 1; 6381 LLVM_DEBUG(dbgs() << "scev-salvage: Location index " << i 6382 << " now at index " << LocationOpIndexMap[i] << "\n"); 6383 continue; 6384 } 6385 6386 // It's possible that a value referred to in the SCEV may have been 6387 // optimised out by LSR. 6388 if (SE.containsErasedValue(DVIRec.SCEVs[i]) || 6389 SE.containsUndefs(DVIRec.SCEVs[i])) { 6390 LLVM_DEBUG(dbgs() << "scev-salvage: SCEV for location at index: " << i 6391 << " refers to a location that is now undef or erased. " 6392 "Salvage abandoned.\n"); 6393 return false; 6394 } 6395 6396 LLVM_DEBUG(dbgs() << "scev-salvage: salvaging location at index " << i 6397 << " with SCEV: " << *DVIRec.SCEVs[i] << "\n"); 6398 6399 DVIRec.RecoveryExprs[i] = std::make_unique<SCEVDbgValueBuilder>(); 6400 SCEVDbgValueBuilder *SalvageExpr = DVIRec.RecoveryExprs[i].get(); 6401 6402 // Create an offset-based salvage expression if possible, as it requires 6403 // less DWARF ops than an iteration count-based expression. 6404 if (Optional<APInt> Offset = 6405 SE.computeConstantDifference(DVIRec.SCEVs[i], SCEVInductionVar)) { 6406 if (Offset.getValue().getMinSignedBits() <= 64) 6407 SalvageExpr->createOffsetExpr(Offset.getValue().getSExtValue(), 6408 LSRInductionVar); 6409 } else if (!SalvageExpr->createIterCountExpr(DVIRec.SCEVs[i], IterCountExpr, 6410 SE)) 6411 return false; 6412 } 6413 6414 // Merge the DbgValueBuilder generated expressions and the original 6415 // DIExpression, place the result into an new vector. 6416 SmallVector<uint64_t, 3> NewExpr; 6417 if (DVIRec.Expr->getNumElements() == 0) { 6418 assert(DVIRec.RecoveryExprs.size() == 1 && 6419 "Expected only a single recovery expression for an empty " 6420 "DIExpression."); 6421 assert(DVIRec.RecoveryExprs[0] && 6422 "Expected a SCEVDbgSalvageBuilder for location 0"); 6423 SCEVDbgValueBuilder *B = DVIRec.RecoveryExprs[0].get(); 6424 B->appendToVectors(NewExpr, NewLocationOps); 6425 } 6426 for (const auto &Op : DVIRec.Expr->expr_ops()) { 6427 // Most Ops needn't be updated. 6428 if (Op.getOp() != dwarf::DW_OP_LLVM_arg) { 6429 Op.appendToVector(NewExpr); 6430 continue; 6431 } 6432 6433 uint64_t LocationArgIndex = Op.getArg(0); 6434 SCEVDbgValueBuilder *DbgBuilder = 6435 DVIRec.RecoveryExprs[LocationArgIndex].get(); 6436 // The location doesn't have s SCEVDbgValueBuilder, so LSR did not 6437 // optimise it away. So just translate the argument to the updated 6438 // location index. 6439 if (!DbgBuilder) { 6440 NewExpr.push_back(dwarf::DW_OP_LLVM_arg); 6441 assert(LocationOpIndexMap[Op.getArg(0)] != -1 && 6442 "Expected a positive index for the location-op position."); 6443 NewExpr.push_back(LocationOpIndexMap[Op.getArg(0)]); 6444 continue; 6445 } 6446 // The location has a recovery expression. 6447 DbgBuilder->appendToVectors(NewExpr, NewLocationOps); 6448 } 6449 6450 UpdateDbgValueInst(DVIRec, NewLocationOps, NewExpr); 6451 LLVM_DEBUG(dbgs() << "scev-salvage: Updated DVI: " << *DVIRec.DVI << "\n"); 6452 return true; 6453 } 6454 6455 /// Obtain an expression for the iteration count, then attempt to salvage the 6456 /// dbg.value intrinsics. 6457 static void 6458 DbgRewriteSalvageableDVIs(llvm::Loop *L, ScalarEvolution &SE, 6459 llvm::PHINode *LSRInductionVar, 6460 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &DVIToUpdate) { 6461 if (DVIToUpdate.empty()) 6462 return; 6463 6464 const llvm::SCEV *SCEVInductionVar = SE.getSCEV(LSRInductionVar); 6465 assert(SCEVInductionVar && 6466 "Anticipated a SCEV for the post-LSR induction variable"); 6467 6468 if (const SCEVAddRecExpr *IVAddRec = 6469 dyn_cast<SCEVAddRecExpr>(SCEVInductionVar)) { 6470 if (!IVAddRec->isAffine()) 6471 return; 6472 6473 // Prevent translation using excessive resources. 6474 if (IVAddRec->getExpressionSize() > MaxSCEVSalvageExpressionSize) 6475 return; 6476 6477 // The iteration count is required to recover location values. 6478 SCEVDbgValueBuilder IterCountExpr; 6479 IterCountExpr.pushLocation(LSRInductionVar); 6480 if (!IterCountExpr.SCEVToIterCountExpr(*IVAddRec, SE)) 6481 return; 6482 6483 LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV: " << *SCEVInductionVar 6484 << '\n'); 6485 6486 for (auto &DVIRec : DVIToUpdate) { 6487 SalvageDVI(L, SE, LSRInductionVar, *DVIRec, SCEVInductionVar, 6488 IterCountExpr); 6489 } 6490 } 6491 } 6492 6493 /// Identify and cache salvageable DVI locations and expressions along with the 6494 /// corresponding SCEV(s). Also ensure that the DVI is not deleted between 6495 /// cacheing and salvaging. 6496 static void DbgGatherSalvagableDVI( 6497 Loop *L, ScalarEvolution &SE, 6498 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> &SalvageableDVISCEVs, 6499 SmallSet<AssertingVH<DbgValueInst>, 2> &DVIHandles) { 6500 for (auto &B : L->getBlocks()) { 6501 for (auto &I : *B) { 6502 auto DVI = dyn_cast<DbgValueInst>(&I); 6503 if (!DVI) 6504 continue; 6505 // Ensure that if any location op is undef that the dbg.vlue is not 6506 // cached. 6507 if (DVI->isUndef()) 6508 continue; 6509 6510 // Check that the location op SCEVs are suitable for translation to 6511 // DIExpression. 6512 const auto &HasTranslatableLocationOps = 6513 [&](const DbgValueInst *DVI) -> bool { 6514 for (const auto LocOp : DVI->location_ops()) { 6515 if (!LocOp) 6516 return false; 6517 6518 if (!SE.isSCEVable(LocOp->getType())) 6519 return false; 6520 6521 const SCEV *S = SE.getSCEV(LocOp); 6522 if (SE.containsUndefs(S)) 6523 return false; 6524 } 6525 return true; 6526 }; 6527 6528 if (!HasTranslatableLocationOps(DVI)) 6529 continue; 6530 6531 std::unique_ptr<DVIRecoveryRec> NewRec = 6532 std::make_unique<DVIRecoveryRec>(DVI); 6533 // Each location Op may need a SCEVDbgValueBuilder in order to recover it. 6534 // Pre-allocating a vector will enable quick lookups of the builder later 6535 // during the salvage. 6536 NewRec->RecoveryExprs.resize(DVI->getNumVariableLocationOps()); 6537 for (const auto LocOp : DVI->location_ops()) { 6538 NewRec->SCEVs.push_back(SE.getSCEV(LocOp)); 6539 NewRec->LocationOps.push_back(LocOp); 6540 NewRec->HadLocationArgList = DVI->hasArgList(); 6541 } 6542 SalvageableDVISCEVs.push_back(std::move(NewRec)); 6543 DVIHandles.insert(DVI); 6544 } 6545 } 6546 } 6547 6548 /// Ideally pick the PHI IV inserted by ScalarEvolutionExpander. As a fallback 6549 /// any PHi from the loop header is usable, but may have less chance of 6550 /// surviving subsequent transforms. 6551 static llvm::PHINode *GetInductionVariable(const Loop &L, ScalarEvolution &SE, 6552 const LSRInstance &LSR) { 6553 6554 auto IsSuitableIV = [&](PHINode *P) { 6555 if (!SE.isSCEVable(P->getType())) 6556 return false; 6557 if (const SCEVAddRecExpr *Rec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(P))) 6558 return Rec->isAffine() && !SE.containsUndefs(SE.getSCEV(P)); 6559 return false; 6560 }; 6561 6562 // For now, just pick the first IV that was generated and inserted by 6563 // ScalarEvolution. Ideally pick an IV that is unlikely to be optimised away 6564 // by subsequent transforms. 6565 for (const WeakVH &IV : LSR.getScalarEvolutionIVs()) { 6566 if (!IV) 6567 continue; 6568 6569 // There should only be PHI node IVs. 6570 PHINode *P = cast<PHINode>(&*IV); 6571 6572 if (IsSuitableIV(P)) 6573 return P; 6574 } 6575 6576 for (PHINode &P : L.getHeader()->phis()) { 6577 if (IsSuitableIV(&P)) 6578 return &P; 6579 } 6580 return nullptr; 6581 } 6582 6583 static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, 6584 DominatorTree &DT, LoopInfo &LI, 6585 const TargetTransformInfo &TTI, 6586 AssumptionCache &AC, TargetLibraryInfo &TLI, 6587 MemorySSA *MSSA) { 6588 6589 // Debug preservation - before we start removing anything identify which DVI 6590 // meet the salvageable criteria and store their DIExpression and SCEVs. 6591 SmallVector<std::unique_ptr<DVIRecoveryRec>, 2> SalvageableDVIRecords; 6592 SmallSet<AssertingVH<DbgValueInst>, 2> DVIHandles; 6593 DbgGatherSalvagableDVI(L, SE, SalvageableDVIRecords, DVIHandles); 6594 6595 bool Changed = false; 6596 std::unique_ptr<MemorySSAUpdater> MSSAU; 6597 if (MSSA) 6598 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA); 6599 6600 // Run the main LSR transformation. 6601 const LSRInstance &Reducer = 6602 LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get()); 6603 Changed |= Reducer.getChanged(); 6604 6605 // Remove any extra phis created by processing inner loops. 6606 Changed |= DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get()); 6607 if (EnablePhiElim && L->isLoopSimplifyForm()) { 6608 SmallVector<WeakTrackingVH, 16> DeadInsts; 6609 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 6610 SCEVExpander Rewriter(SE, DL, "lsr", false); 6611 #ifndef NDEBUG 6612 Rewriter.setDebugType(DEBUG_TYPE); 6613 #endif 6614 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI); 6615 if (numFolded) { 6616 Changed = true; 6617 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI, 6618 MSSAU.get()); 6619 DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get()); 6620 } 6621 } 6622 // LSR may at times remove all uses of an induction variable from a loop. 6623 // The only remaining use is the PHI in the exit block. 6624 // When this is the case, if the exit value of the IV can be calculated using 6625 // SCEV, we can replace the exit block PHI with the final value of the IV and 6626 // skip the updates in each loop iteration. 6627 if (L->isRecursivelyLCSSAForm(DT, LI) && LoopExitValHasSingleUse(L)) { 6628 SmallVector<WeakTrackingVH, 16> DeadInsts; 6629 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 6630 SCEVExpander Rewriter(SE, DL, "lsr", false); 6631 int Rewrites = rewriteLoopExitValues(L, &LI, &TLI, &SE, &TTI, Rewriter, &DT, 6632 OnlyCheapRepl, DeadInsts); 6633 if (Rewrites) { 6634 Changed = true; 6635 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI, 6636 MSSAU.get()); 6637 DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get()); 6638 } 6639 } 6640 6641 if (SalvageableDVIRecords.empty()) 6642 return Changed; 6643 6644 // Obtain relevant IVs and attempt to rewrite the salvageable DVIs with 6645 // expressions composed using the derived iteration count. 6646 // TODO: Allow for multiple IV references for nested AddRecSCEVs 6647 for (auto &L : LI) { 6648 if (llvm::PHINode *IV = GetInductionVariable(*L, SE, Reducer)) 6649 DbgRewriteSalvageableDVIs(L, SE, IV, SalvageableDVIRecords); 6650 else { 6651 LLVM_DEBUG(dbgs() << "scev-salvage: SCEV salvaging not possible. An IV " 6652 "could not be identified.\n"); 6653 } 6654 } 6655 6656 for (auto &Rec : SalvageableDVIRecords) 6657 Rec->clear(); 6658 SalvageableDVIRecords.clear(); 6659 DVIHandles.clear(); 6660 return Changed; 6661 } 6662 6663 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) { 6664 if (skipLoop(L)) 6665 return false; 6666 6667 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU(); 6668 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 6669 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 6670 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 6671 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 6672 *L->getHeader()->getParent()); 6673 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache( 6674 *L->getHeader()->getParent()); 6675 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI( 6676 *L->getHeader()->getParent()); 6677 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 6678 MemorySSA *MSSA = nullptr; 6679 if (MSSAAnalysis) 6680 MSSA = &MSSAAnalysis->getMSSA(); 6681 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA); 6682 } 6683 6684 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM, 6685 LoopStandardAnalysisResults &AR, 6686 LPMUpdater &) { 6687 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE, 6688 AR.DT, AR.LI, AR.TTI, AR.AC, AR.TLI, AR.MSSA)) 6689 return PreservedAnalyses::all(); 6690 6691 auto PA = getLoopPassPreservedAnalyses(); 6692 if (AR.MSSA) 6693 PA.preserve<MemorySSAAnalysis>(); 6694 return PA; 6695 } 6696 6697 char LoopStrengthReduce::ID = 0; 6698 6699 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce", 6700 "Loop Strength Reduction", false, false) 6701 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 6702 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 6703 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 6704 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass) 6705 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 6706 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 6707 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce", 6708 "Loop Strength Reduction", false, false) 6709 6710 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); } 6711