1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This transformation analyzes and transforms the induction variables (and 11 // computations derived from them) into forms suitable for efficient execution 12 // on the target. 13 // 14 // This pass performs a strength reduction on array references inside loops that 15 // have as one or more of their components the loop induction variable, it 16 // rewrites expressions to take advantage of scaled-index addressing modes 17 // available on the target, and it performs a variety of other optimizations 18 // related to loop induction variables. 19 // 20 // Terminology note: this code has a lot of handling for "post-increment" or 21 // "post-inc" users. This is not talking about post-increment addressing modes; 22 // it is instead talking about code like this: 23 // 24 // %i = phi [ 0, %entry ], [ %i.next, %latch ] 25 // ... 26 // %i.next = add %i, 1 27 // %c = icmp eq %i.next, %n 28 // 29 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however 30 // it's useful to think about these as the same register, with some uses using 31 // the value of the register before the add and some using it after. In this 32 // example, the icmp is a post-increment user, since it uses %i.next, which is 33 // the value of the induction variable after the increment. The other common 34 // case of post-increment users is users outside the loop. 35 // 36 // TODO: More sophistication in the way Formulae are generated and filtered. 37 // 38 // TODO: Handle multiple loops at a time. 39 // 40 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead 41 // of a GlobalValue? 42 // 43 // TODO: When truncation is free, truncate ICmp users' operands to make it a 44 // smaller encoding (on x86 at least). 45 // 46 // TODO: When a negated register is used by an add (such as in a list of 47 // multiple base registers, or as the increment expression in an addrec), 48 // we may not actually need both reg and (-1 * reg) in registers; the 49 // negation can be implemented by using a sub instead of an add. The 50 // lack of support for taking this into consideration when making 51 // register pressure decisions is partly worked around by the "Special" 52 // use kind. 53 // 54 //===----------------------------------------------------------------------===// 55 56 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 57 #include "llvm/ADT/APInt.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/DenseSet.h" 60 #include "llvm/ADT/Hashing.h" 61 #include "llvm/ADT/PointerIntPair.h" 62 #include "llvm/ADT/STLExtras.h" 63 #include "llvm/ADT/SetVector.h" 64 #include "llvm/ADT/SmallBitVector.h" 65 #include "llvm/ADT/SmallPtrSet.h" 66 #include "llvm/ADT/SmallSet.h" 67 #include "llvm/ADT/SmallVector.h" 68 #include "llvm/Analysis/IVUsers.h" 69 #include "llvm/Analysis/LoopInfo.h" 70 #include "llvm/Analysis/LoopPass.h" 71 #include "llvm/Analysis/ScalarEvolution.h" 72 #include "llvm/Analysis/ScalarEvolutionExpander.h" 73 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 74 #include "llvm/Analysis/ScalarEvolutionNormalization.h" 75 #include "llvm/Analysis/TargetTransformInfo.h" 76 #include "llvm/IR/BasicBlock.h" 77 #include "llvm/IR/Constant.h" 78 #include "llvm/IR/Constants.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Dominators.h" 81 #include "llvm/IR/GlobalValue.h" 82 #include "llvm/IR/IRBuilder.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Module.h" 87 #include "llvm/IR/OperandTraits.h" 88 #include "llvm/IR/Operator.h" 89 #include "llvm/IR/Type.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/IR/ValueHandle.h" 92 #include "llvm/Pass.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Transforms/Scalar.h" 101 #include "llvm/Transforms/Scalar/LoopPassManager.h" 102 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 103 #include "llvm/Transforms/Utils/Local.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstddef> 107 #include <cstdint> 108 #include <cstdlib> 109 #include <iterator> 110 #include <map> 111 #include <tuple> 112 #include <utility> 113 114 using namespace llvm; 115 116 #define DEBUG_TYPE "loop-reduce" 117 118 /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for 119 /// bail out. This threshold is far beyond the number of users that LSR can 120 /// conceivably solve, so it should not affect generated code, but catches the 121 /// worst cases before LSR burns too much compile time and stack space. 122 static const unsigned MaxIVUsers = 200; 123 124 // Temporary flag to cleanup congruent phis after LSR phi expansion. 125 // It's currently disabled until we can determine whether it's truly useful or 126 // not. The flag should be removed after the v3.0 release. 127 // This is now needed for ivchains. 128 static cl::opt<bool> EnablePhiElim( 129 "enable-lsr-phielim", cl::Hidden, cl::init(true), 130 cl::desc("Enable LSR phi elimination")); 131 132 // The flag adds instruction count to solutions cost comparision. 133 static cl::opt<bool> InsnsCost( 134 "lsr-insns-cost", cl::Hidden, cl::init(true), 135 cl::desc("Add instruction count to a LSR cost model")); 136 137 // Flag to choose how to narrow complex lsr solution 138 static cl::opt<bool> LSRExpNarrow( 139 "lsr-exp-narrow", cl::Hidden, cl::init(false), 140 cl::desc("Narrow LSR complex solution using" 141 " expectation of registers number")); 142 143 #ifndef NDEBUG 144 // Stress test IV chain generation. 145 static cl::opt<bool> StressIVChain( 146 "stress-ivchain", cl::Hidden, cl::init(false), 147 cl::desc("Stress test LSR IV chains")); 148 #else 149 static bool StressIVChain = false; 150 #endif 151 152 namespace { 153 154 struct MemAccessTy { 155 /// Used in situations where the accessed memory type is unknown. 156 static const unsigned UnknownAddressSpace = ~0u; 157 158 Type *MemTy; 159 unsigned AddrSpace; 160 161 MemAccessTy() : MemTy(nullptr), AddrSpace(UnknownAddressSpace) {} 162 163 MemAccessTy(Type *Ty, unsigned AS) : 164 MemTy(Ty), AddrSpace(AS) {} 165 166 bool operator==(MemAccessTy Other) const { 167 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace; 168 } 169 170 bool operator!=(MemAccessTy Other) const { return !(*this == Other); } 171 172 static MemAccessTy getUnknown(LLVMContext &Ctx, 173 unsigned AS = UnknownAddressSpace) { 174 return MemAccessTy(Type::getVoidTy(Ctx), AS); 175 } 176 }; 177 178 /// This class holds data which is used to order reuse candidates. 179 class RegSortData { 180 public: 181 /// This represents the set of LSRUse indices which reference 182 /// a particular register. 183 SmallBitVector UsedByIndices; 184 185 void print(raw_ostream &OS) const; 186 void dump() const; 187 }; 188 189 } // end anonymous namespace 190 191 void RegSortData::print(raw_ostream &OS) const { 192 OS << "[NumUses=" << UsedByIndices.count() << ']'; 193 } 194 195 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 196 LLVM_DUMP_METHOD void RegSortData::dump() const { 197 print(errs()); errs() << '\n'; 198 } 199 #endif 200 201 namespace { 202 203 /// Map register candidates to information about how they are used. 204 class RegUseTracker { 205 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy; 206 207 RegUsesTy RegUsesMap; 208 SmallVector<const SCEV *, 16> RegSequence; 209 210 public: 211 void countRegister(const SCEV *Reg, size_t LUIdx); 212 void dropRegister(const SCEV *Reg, size_t LUIdx); 213 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx); 214 215 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const; 216 217 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const; 218 219 void clear(); 220 221 typedef SmallVectorImpl<const SCEV *>::iterator iterator; 222 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator; 223 iterator begin() { return RegSequence.begin(); } 224 iterator end() { return RegSequence.end(); } 225 const_iterator begin() const { return RegSequence.begin(); } 226 const_iterator end() const { return RegSequence.end(); } 227 }; 228 229 } // end anonymous namespace 230 231 void 232 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) { 233 std::pair<RegUsesTy::iterator, bool> Pair = 234 RegUsesMap.insert(std::make_pair(Reg, RegSortData())); 235 RegSortData &RSD = Pair.first->second; 236 if (Pair.second) 237 RegSequence.push_back(Reg); 238 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1)); 239 RSD.UsedByIndices.set(LUIdx); 240 } 241 242 void 243 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) { 244 RegUsesTy::iterator It = RegUsesMap.find(Reg); 245 assert(It != RegUsesMap.end()); 246 RegSortData &RSD = It->second; 247 assert(RSD.UsedByIndices.size() > LUIdx); 248 RSD.UsedByIndices.reset(LUIdx); 249 } 250 251 void 252 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) { 253 assert(LUIdx <= LastLUIdx); 254 255 // Update RegUses. The data structure is not optimized for this purpose; 256 // we must iterate through it and update each of the bit vectors. 257 for (auto &Pair : RegUsesMap) { 258 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices; 259 if (LUIdx < UsedByIndices.size()) 260 UsedByIndices[LUIdx] = 261 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false; 262 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx)); 263 } 264 } 265 266 bool 267 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const { 268 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 269 if (I == RegUsesMap.end()) 270 return false; 271 const SmallBitVector &UsedByIndices = I->second.UsedByIndices; 272 int i = UsedByIndices.find_first(); 273 if (i == -1) return false; 274 if ((size_t)i != LUIdx) return true; 275 return UsedByIndices.find_next(i) != -1; 276 } 277 278 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const { 279 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 280 assert(I != RegUsesMap.end() && "Unknown register!"); 281 return I->second.UsedByIndices; 282 } 283 284 void RegUseTracker::clear() { 285 RegUsesMap.clear(); 286 RegSequence.clear(); 287 } 288 289 namespace { 290 291 /// This class holds information that describes a formula for computing 292 /// satisfying a use. It may include broken-out immediates and scaled registers. 293 struct Formula { 294 /// Global base address used for complex addressing. 295 GlobalValue *BaseGV; 296 297 /// Base offset for complex addressing. 298 int64_t BaseOffset; 299 300 /// Whether any complex addressing has a base register. 301 bool HasBaseReg; 302 303 /// The scale of any complex addressing. 304 int64_t Scale; 305 306 /// The list of "base" registers for this use. When this is non-empty. The 307 /// canonical representation of a formula is 308 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and 309 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty(). 310 /// 3. The reg containing recurrent expr related with currect loop in the 311 /// formula should be put in the ScaledReg. 312 /// #1 enforces that the scaled register is always used when at least two 313 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2. 314 /// #2 enforces that 1 * reg is reg. 315 /// #3 ensures invariant regs with respect to current loop can be combined 316 /// together in LSR codegen. 317 /// This invariant can be temporarly broken while building a formula. 318 /// However, every formula inserted into the LSRInstance must be in canonical 319 /// form. 320 SmallVector<const SCEV *, 4> BaseRegs; 321 322 /// The 'scaled' register for this use. This should be non-null when Scale is 323 /// not zero. 324 const SCEV *ScaledReg; 325 326 /// An additional constant offset which added near the use. This requires a 327 /// temporary register, but the offset itself can live in an add immediate 328 /// field rather than a register. 329 int64_t UnfoldedOffset; 330 331 Formula() 332 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0), 333 ScaledReg(nullptr), UnfoldedOffset(0) {} 334 335 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE); 336 337 bool isCanonical(const Loop &L) const; 338 339 void canonicalize(const Loop &L); 340 341 bool unscale(); 342 343 bool hasZeroEnd() const; 344 345 size_t getNumRegs() const; 346 Type *getType() const; 347 348 void deleteBaseReg(const SCEV *&S); 349 350 bool referencesReg(const SCEV *S) const; 351 bool hasRegsUsedByUsesOtherThan(size_t LUIdx, 352 const RegUseTracker &RegUses) const; 353 354 void print(raw_ostream &OS) const; 355 void dump() const; 356 }; 357 358 } // end anonymous namespace 359 360 /// Recursion helper for initialMatch. 361 static void DoInitialMatch(const SCEV *S, Loop *L, 362 SmallVectorImpl<const SCEV *> &Good, 363 SmallVectorImpl<const SCEV *> &Bad, 364 ScalarEvolution &SE) { 365 // Collect expressions which properly dominate the loop header. 366 if (SE.properlyDominates(S, L->getHeader())) { 367 Good.push_back(S); 368 return; 369 } 370 371 // Look at add operands. 372 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 373 for (const SCEV *S : Add->operands()) 374 DoInitialMatch(S, L, Good, Bad, SE); 375 return; 376 } 377 378 // Look at addrec operands. 379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 380 if (!AR->getStart()->isZero() && AR->isAffine()) { 381 DoInitialMatch(AR->getStart(), L, Good, Bad, SE); 382 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0), 383 AR->getStepRecurrence(SE), 384 // FIXME: AR->getNoWrapFlags() 385 AR->getLoop(), SCEV::FlagAnyWrap), 386 L, Good, Bad, SE); 387 return; 388 } 389 390 // Handle a multiplication by -1 (negation) if it didn't fold. 391 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) 392 if (Mul->getOperand(0)->isAllOnesValue()) { 393 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end()); 394 const SCEV *NewMul = SE.getMulExpr(Ops); 395 396 SmallVector<const SCEV *, 4> MyGood; 397 SmallVector<const SCEV *, 4> MyBad; 398 DoInitialMatch(NewMul, L, MyGood, MyBad, SE); 399 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue( 400 SE.getEffectiveSCEVType(NewMul->getType()))); 401 for (const SCEV *S : MyGood) 402 Good.push_back(SE.getMulExpr(NegOne, S)); 403 for (const SCEV *S : MyBad) 404 Bad.push_back(SE.getMulExpr(NegOne, S)); 405 return; 406 } 407 408 // Ok, we can't do anything interesting. Just stuff the whole thing into a 409 // register and hope for the best. 410 Bad.push_back(S); 411 } 412 413 /// Incorporate loop-variant parts of S into this Formula, attempting to keep 414 /// all loop-invariant and loop-computable values in a single base register. 415 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) { 416 SmallVector<const SCEV *, 4> Good; 417 SmallVector<const SCEV *, 4> Bad; 418 DoInitialMatch(S, L, Good, Bad, SE); 419 if (!Good.empty()) { 420 const SCEV *Sum = SE.getAddExpr(Good); 421 if (!Sum->isZero()) 422 BaseRegs.push_back(Sum); 423 HasBaseReg = true; 424 } 425 if (!Bad.empty()) { 426 const SCEV *Sum = SE.getAddExpr(Bad); 427 if (!Sum->isZero()) 428 BaseRegs.push_back(Sum); 429 HasBaseReg = true; 430 } 431 canonicalize(*L); 432 } 433 434 /// \brief Check whether or not this formula statisfies the canonical 435 /// representation. 436 /// \see Formula::BaseRegs. 437 bool Formula::isCanonical(const Loop &L) const { 438 if (!ScaledReg) 439 return BaseRegs.size() <= 1; 440 441 if (Scale != 1) 442 return true; 443 444 if (Scale == 1 && BaseRegs.empty()) 445 return false; 446 447 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg); 448 if (SAR && SAR->getLoop() == &L) 449 return true; 450 451 // If ScaledReg is not a recurrent expr, or it is but its loop is not current 452 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current 453 // loop, we want to swap the reg in BaseRegs with ScaledReg. 454 auto I = 455 find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) { 456 return isa<const SCEVAddRecExpr>(S) && 457 (cast<SCEVAddRecExpr>(S)->getLoop() == &L); 458 }); 459 return I == BaseRegs.end(); 460 } 461 462 /// \brief Helper method to morph a formula into its canonical representation. 463 /// \see Formula::BaseRegs. 464 /// Every formula having more than one base register, must use the ScaledReg 465 /// field. Otherwise, we would have to do special cases everywhere in LSR 466 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ... 467 /// On the other hand, 1*reg should be canonicalized into reg. 468 void Formula::canonicalize(const Loop &L) { 469 if (isCanonical(L)) 470 return; 471 // So far we did not need this case. This is easy to implement but it is 472 // useless to maintain dead code. Beside it could hurt compile time. 473 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed."); 474 475 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg. 476 if (!ScaledReg) { 477 ScaledReg = BaseRegs.back(); 478 BaseRegs.pop_back(); 479 Scale = 1; 480 } 481 482 // If ScaledReg is an invariant with respect to L, find the reg from 483 // BaseRegs containing the recurrent expr related with Loop L. Swap the 484 // reg with ScaledReg. 485 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg); 486 if (!SAR || SAR->getLoop() != &L) { 487 auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()), 488 [&](const SCEV *S) { 489 return isa<const SCEVAddRecExpr>(S) && 490 (cast<SCEVAddRecExpr>(S)->getLoop() == &L); 491 }); 492 if (I != BaseRegs.end()) 493 std::swap(ScaledReg, *I); 494 } 495 } 496 497 /// \brief Get rid of the scale in the formula. 498 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2. 499 /// \return true if it was possible to get rid of the scale, false otherwise. 500 /// \note After this operation the formula may not be in the canonical form. 501 bool Formula::unscale() { 502 if (Scale != 1) 503 return false; 504 Scale = 0; 505 BaseRegs.push_back(ScaledReg); 506 ScaledReg = nullptr; 507 return true; 508 } 509 510 bool Formula::hasZeroEnd() const { 511 if (UnfoldedOffset || BaseOffset) 512 return false; 513 if (BaseRegs.size() != 1 || ScaledReg) 514 return false; 515 return true; 516 } 517 518 /// Return the total number of register operands used by this formula. This does 519 /// not include register uses implied by non-constant addrec strides. 520 size_t Formula::getNumRegs() const { 521 return !!ScaledReg + BaseRegs.size(); 522 } 523 524 /// Return the type of this formula, if it has one, or null otherwise. This type 525 /// is meaningless except for the bit size. 526 Type *Formula::getType() const { 527 return !BaseRegs.empty() ? BaseRegs.front()->getType() : 528 ScaledReg ? ScaledReg->getType() : 529 BaseGV ? BaseGV->getType() : 530 nullptr; 531 } 532 533 /// Delete the given base reg from the BaseRegs list. 534 void Formula::deleteBaseReg(const SCEV *&S) { 535 if (&S != &BaseRegs.back()) 536 std::swap(S, BaseRegs.back()); 537 BaseRegs.pop_back(); 538 } 539 540 /// Test if this formula references the given register. 541 bool Formula::referencesReg(const SCEV *S) const { 542 return S == ScaledReg || is_contained(BaseRegs, S); 543 } 544 545 /// Test whether this formula uses registers which are used by uses other than 546 /// the use with the given index. 547 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx, 548 const RegUseTracker &RegUses) const { 549 if (ScaledReg) 550 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx)) 551 return true; 552 for (const SCEV *BaseReg : BaseRegs) 553 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx)) 554 return true; 555 return false; 556 } 557 558 void Formula::print(raw_ostream &OS) const { 559 bool First = true; 560 if (BaseGV) { 561 if (!First) OS << " + "; else First = false; 562 BaseGV->printAsOperand(OS, /*PrintType=*/false); 563 } 564 if (BaseOffset != 0) { 565 if (!First) OS << " + "; else First = false; 566 OS << BaseOffset; 567 } 568 for (const SCEV *BaseReg : BaseRegs) { 569 if (!First) OS << " + "; else First = false; 570 OS << "reg(" << *BaseReg << ')'; 571 } 572 if (HasBaseReg && BaseRegs.empty()) { 573 if (!First) OS << " + "; else First = false; 574 OS << "**error: HasBaseReg**"; 575 } else if (!HasBaseReg && !BaseRegs.empty()) { 576 if (!First) OS << " + "; else First = false; 577 OS << "**error: !HasBaseReg**"; 578 } 579 if (Scale != 0) { 580 if (!First) OS << " + "; else First = false; 581 OS << Scale << "*reg("; 582 if (ScaledReg) 583 OS << *ScaledReg; 584 else 585 OS << "<unknown>"; 586 OS << ')'; 587 } 588 if (UnfoldedOffset != 0) { 589 if (!First) OS << " + "; 590 OS << "imm(" << UnfoldedOffset << ')'; 591 } 592 } 593 594 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 595 LLVM_DUMP_METHOD void Formula::dump() const { 596 print(errs()); errs() << '\n'; 597 } 598 #endif 599 600 /// Return true if the given addrec can be sign-extended without changing its 601 /// value. 602 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 603 Type *WideTy = 604 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1); 605 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 606 } 607 608 /// Return true if the given add can be sign-extended without changing its 609 /// value. 610 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) { 611 Type *WideTy = 612 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1); 613 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy)); 614 } 615 616 /// Return true if the given mul can be sign-extended without changing its 617 /// value. 618 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) { 619 Type *WideTy = 620 IntegerType::get(SE.getContext(), 621 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands()); 622 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy)); 623 } 624 625 /// Return an expression for LHS /s RHS, if it can be determined and if the 626 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits 627 /// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that 628 /// the multiplication may overflow, which is useful when the result will be 629 /// used in a context where the most significant bits are ignored. 630 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS, 631 ScalarEvolution &SE, 632 bool IgnoreSignificantBits = false) { 633 // Handle the trivial case, which works for any SCEV type. 634 if (LHS == RHS) 635 return SE.getConstant(LHS->getType(), 1); 636 637 // Handle a few RHS special cases. 638 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS); 639 if (RC) { 640 const APInt &RA = RC->getAPInt(); 641 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do 642 // some folding. 643 if (RA.isAllOnesValue()) 644 return SE.getMulExpr(LHS, RC); 645 // Handle x /s 1 as x. 646 if (RA == 1) 647 return LHS; 648 } 649 650 // Check for a division of a constant by a constant. 651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) { 652 if (!RC) 653 return nullptr; 654 const APInt &LA = C->getAPInt(); 655 const APInt &RA = RC->getAPInt(); 656 if (LA.srem(RA) != 0) 657 return nullptr; 658 return SE.getConstant(LA.sdiv(RA)); 659 } 660 661 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow. 662 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) { 663 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) { 664 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE, 665 IgnoreSignificantBits); 666 if (!Step) return nullptr; 667 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE, 668 IgnoreSignificantBits); 669 if (!Start) return nullptr; 670 // FlagNW is independent of the start value, step direction, and is 671 // preserved with smaller magnitude steps. 672 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 673 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap); 674 } 675 return nullptr; 676 } 677 678 // Distribute the sdiv over add operands, if the add doesn't overflow. 679 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) { 680 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) { 681 SmallVector<const SCEV *, 8> Ops; 682 for (const SCEV *S : Add->operands()) { 683 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits); 684 if (!Op) return nullptr; 685 Ops.push_back(Op); 686 } 687 return SE.getAddExpr(Ops); 688 } 689 return nullptr; 690 } 691 692 // Check for a multiply operand that we can pull RHS out of. 693 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) { 694 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) { 695 SmallVector<const SCEV *, 4> Ops; 696 bool Found = false; 697 for (const SCEV *S : Mul->operands()) { 698 if (!Found) 699 if (const SCEV *Q = getExactSDiv(S, RHS, SE, 700 IgnoreSignificantBits)) { 701 S = Q; 702 Found = true; 703 } 704 Ops.push_back(S); 705 } 706 return Found ? SE.getMulExpr(Ops) : nullptr; 707 } 708 return nullptr; 709 } 710 711 // Otherwise we don't know. 712 return nullptr; 713 } 714 715 /// If S involves the addition of a constant integer value, return that integer 716 /// value, and mutate S to point to a new SCEV with that value excluded. 717 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) { 718 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 719 if (C->getAPInt().getMinSignedBits() <= 64) { 720 S = SE.getConstant(C->getType(), 0); 721 return C->getValue()->getSExtValue(); 722 } 723 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 724 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end()); 725 int64_t Result = ExtractImmediate(NewOps.front(), SE); 726 if (Result != 0) 727 S = SE.getAddExpr(NewOps); 728 return Result; 729 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 730 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end()); 731 int64_t Result = ExtractImmediate(NewOps.front(), SE); 732 if (Result != 0) 733 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 734 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 735 SCEV::FlagAnyWrap); 736 return Result; 737 } 738 return 0; 739 } 740 741 /// If S involves the addition of a GlobalValue address, return that symbol, and 742 /// mutate S to point to a new SCEV with that value excluded. 743 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) { 744 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 745 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) { 746 S = SE.getConstant(GV->getType(), 0); 747 return GV; 748 } 749 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 750 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end()); 751 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE); 752 if (Result) 753 S = SE.getAddExpr(NewOps); 754 return Result; 755 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 756 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end()); 757 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE); 758 if (Result) 759 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 760 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 761 SCEV::FlagAnyWrap); 762 return Result; 763 } 764 return nullptr; 765 } 766 767 /// Returns true if the specified instruction is using the specified value as an 768 /// address. 769 static bool isAddressUse(Instruction *Inst, Value *OperandVal) { 770 bool isAddress = isa<LoadInst>(Inst); 771 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 772 if (SI->getPointerOperand() == OperandVal) 773 isAddress = true; 774 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 775 // Addressing modes can also be folded into prefetches and a variety 776 // of intrinsics. 777 switch (II->getIntrinsicID()) { 778 default: break; 779 case Intrinsic::prefetch: 780 if (II->getArgOperand(0) == OperandVal) 781 isAddress = true; 782 break; 783 } 784 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 785 if (RMW->getPointerOperand() == OperandVal) 786 isAddress = true; 787 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 788 if (CmpX->getPointerOperand() == OperandVal) 789 isAddress = true; 790 } 791 return isAddress; 792 } 793 794 /// Return the type of the memory being accessed. 795 static MemAccessTy getAccessType(const Instruction *Inst) { 796 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace); 797 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 798 AccessTy.MemTy = SI->getOperand(0)->getType(); 799 AccessTy.AddrSpace = SI->getPointerAddressSpace(); 800 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 801 AccessTy.AddrSpace = LI->getPointerAddressSpace(); 802 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 803 AccessTy.AddrSpace = RMW->getPointerAddressSpace(); 804 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 805 AccessTy.AddrSpace = CmpX->getPointerAddressSpace(); 806 } 807 808 // All pointers have the same requirements, so canonicalize them to an 809 // arbitrary pointer type to minimize variation. 810 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy)) 811 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1), 812 PTy->getAddressSpace()); 813 814 return AccessTy; 815 } 816 817 /// Return true if this AddRec is already a phi in its loop. 818 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 819 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin(); 820 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 821 if (SE.isSCEVable(PN->getType()) && 822 (SE.getEffectiveSCEVType(PN->getType()) == 823 SE.getEffectiveSCEVType(AR->getType())) && 824 SE.getSCEV(PN) == AR) 825 return true; 826 } 827 return false; 828 } 829 830 /// Check if expanding this expression is likely to incur significant cost. This 831 /// is tricky because SCEV doesn't track which expressions are actually computed 832 /// by the current IR. 833 /// 834 /// We currently allow expansion of IV increments that involve adds, 835 /// multiplication by constants, and AddRecs from existing phis. 836 /// 837 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an 838 /// obvious multiple of the UDivExpr. 839 static bool isHighCostExpansion(const SCEV *S, 840 SmallPtrSetImpl<const SCEV*> &Processed, 841 ScalarEvolution &SE) { 842 // Zero/One operand expressions 843 switch (S->getSCEVType()) { 844 case scUnknown: 845 case scConstant: 846 return false; 847 case scTruncate: 848 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(), 849 Processed, SE); 850 case scZeroExtend: 851 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(), 852 Processed, SE); 853 case scSignExtend: 854 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(), 855 Processed, SE); 856 } 857 858 if (!Processed.insert(S).second) 859 return false; 860 861 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 862 for (const SCEV *S : Add->operands()) { 863 if (isHighCostExpansion(S, Processed, SE)) 864 return true; 865 } 866 return false; 867 } 868 869 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 870 if (Mul->getNumOperands() == 2) { 871 // Multiplication by a constant is ok 872 if (isa<SCEVConstant>(Mul->getOperand(0))) 873 return isHighCostExpansion(Mul->getOperand(1), Processed, SE); 874 875 // If we have the value of one operand, check if an existing 876 // multiplication already generates this expression. 877 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) { 878 Value *UVal = U->getValue(); 879 for (User *UR : UVal->users()) { 880 // If U is a constant, it may be used by a ConstantExpr. 881 Instruction *UI = dyn_cast<Instruction>(UR); 882 if (UI && UI->getOpcode() == Instruction::Mul && 883 SE.isSCEVable(UI->getType())) { 884 return SE.getSCEV(UI) == Mul; 885 } 886 } 887 } 888 } 889 } 890 891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 892 if (isExistingPhi(AR, SE)) 893 return false; 894 } 895 896 // Fow now, consider any other type of expression (div/mul/min/max) high cost. 897 return true; 898 } 899 900 /// If any of the instructions is the specified set are trivially dead, delete 901 /// them and see if this makes any of their operands subsequently dead. 902 static bool 903 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 904 bool Changed = false; 905 906 while (!DeadInsts.empty()) { 907 Value *V = DeadInsts.pop_back_val(); 908 Instruction *I = dyn_cast_or_null<Instruction>(V); 909 910 if (!I || !isInstructionTriviallyDead(I)) 911 continue; 912 913 for (Use &O : I->operands()) 914 if (Instruction *U = dyn_cast<Instruction>(O)) { 915 O = nullptr; 916 if (U->use_empty()) 917 DeadInsts.emplace_back(U); 918 } 919 920 I->eraseFromParent(); 921 Changed = true; 922 } 923 924 return Changed; 925 } 926 927 namespace { 928 929 class LSRUse; 930 931 } // end anonymous namespace 932 933 /// \brief Check if the addressing mode defined by \p F is completely 934 /// folded in \p LU at isel time. 935 /// This includes address-mode folding and special icmp tricks. 936 /// This function returns true if \p LU can accommodate what \p F 937 /// defines and up to 1 base + 1 scaled + offset. 938 /// In other words, if \p F has several base registers, this function may 939 /// still return true. Therefore, users still need to account for 940 /// additional base registers and/or unfolded offsets to derive an 941 /// accurate cost model. 942 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 943 const LSRUse &LU, const Formula &F); 944 // Get the cost of the scaling factor used in F for LU. 945 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, 946 const LSRUse &LU, const Formula &F, 947 const Loop &L); 948 949 namespace { 950 951 /// This class is used to measure and compare candidate formulae. 952 class Cost { 953 TargetTransformInfo::LSRCost C; 954 955 public: 956 Cost() { 957 C.Insns = 0; 958 C.NumRegs = 0; 959 C.AddRecCost = 0; 960 C.NumIVMuls = 0; 961 C.NumBaseAdds = 0; 962 C.ImmCost = 0; 963 C.SetupCost = 0; 964 C.ScaleCost = 0; 965 } 966 967 bool isLess(Cost &Other, const TargetTransformInfo &TTI); 968 969 void Lose(); 970 971 #ifndef NDEBUG 972 // Once any of the metrics loses, they must all remain losers. 973 bool isValid() { 974 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds 975 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u) 976 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds 977 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u); 978 } 979 #endif 980 981 bool isLoser() { 982 assert(isValid() && "invalid cost"); 983 return C.NumRegs == ~0u; 984 } 985 986 void RateFormula(const TargetTransformInfo &TTI, 987 const Formula &F, 988 SmallPtrSetImpl<const SCEV *> &Regs, 989 const DenseSet<const SCEV *> &VisitedRegs, 990 const Loop *L, 991 ScalarEvolution &SE, DominatorTree &DT, 992 const LSRUse &LU, 993 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr); 994 995 void print(raw_ostream &OS) const; 996 void dump() const; 997 998 private: 999 void RateRegister(const SCEV *Reg, 1000 SmallPtrSetImpl<const SCEV *> &Regs, 1001 const Loop *L, 1002 ScalarEvolution &SE, DominatorTree &DT); 1003 void RatePrimaryRegister(const SCEV *Reg, 1004 SmallPtrSetImpl<const SCEV *> &Regs, 1005 const Loop *L, 1006 ScalarEvolution &SE, DominatorTree &DT, 1007 SmallPtrSetImpl<const SCEV *> *LoserRegs); 1008 }; 1009 1010 /// An operand value in an instruction which is to be replaced with some 1011 /// equivalent, possibly strength-reduced, replacement. 1012 struct LSRFixup { 1013 /// The instruction which will be updated. 1014 Instruction *UserInst; 1015 1016 /// The operand of the instruction which will be replaced. The operand may be 1017 /// used more than once; every instance will be replaced. 1018 Value *OperandValToReplace; 1019 1020 /// If this user is to use the post-incremented value of an induction 1021 /// variable, this variable is non-null and holds the loop associated with the 1022 /// induction variable. 1023 PostIncLoopSet PostIncLoops; 1024 1025 /// A constant offset to be added to the LSRUse expression. This allows 1026 /// multiple fixups to share the same LSRUse with different offsets, for 1027 /// example in an unrolled loop. 1028 int64_t Offset; 1029 1030 bool isUseFullyOutsideLoop(const Loop *L) const; 1031 1032 LSRFixup(); 1033 1034 void print(raw_ostream &OS) const; 1035 void dump() const; 1036 }; 1037 1038 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted 1039 /// SmallVectors of const SCEV*. 1040 struct UniquifierDenseMapInfo { 1041 static SmallVector<const SCEV *, 4> getEmptyKey() { 1042 SmallVector<const SCEV *, 4> V; 1043 V.push_back(reinterpret_cast<const SCEV *>(-1)); 1044 return V; 1045 } 1046 1047 static SmallVector<const SCEV *, 4> getTombstoneKey() { 1048 SmallVector<const SCEV *, 4> V; 1049 V.push_back(reinterpret_cast<const SCEV *>(-2)); 1050 return V; 1051 } 1052 1053 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) { 1054 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 1055 } 1056 1057 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS, 1058 const SmallVector<const SCEV *, 4> &RHS) { 1059 return LHS == RHS; 1060 } 1061 }; 1062 1063 /// This class holds the state that LSR keeps for each use in IVUsers, as well 1064 /// as uses invented by LSR itself. It includes information about what kinds of 1065 /// things can be folded into the user, information about the user itself, and 1066 /// information about how the use may be satisfied. TODO: Represent multiple 1067 /// users of the same expression in common? 1068 class LSRUse { 1069 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier; 1070 1071 public: 1072 /// An enum for a kind of use, indicating what types of scaled and immediate 1073 /// operands it might support. 1074 enum KindType { 1075 Basic, ///< A normal use, with no folding. 1076 Special, ///< A special case of basic, allowing -1 scales. 1077 Address, ///< An address use; folding according to TargetLowering 1078 ICmpZero ///< An equality icmp with both operands folded into one. 1079 // TODO: Add a generic icmp too? 1080 }; 1081 1082 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair; 1083 1084 KindType Kind; 1085 MemAccessTy AccessTy; 1086 1087 /// The list of operands which are to be replaced. 1088 SmallVector<LSRFixup, 8> Fixups; 1089 1090 /// Keep track of the min and max offsets of the fixups. 1091 int64_t MinOffset; 1092 int64_t MaxOffset; 1093 1094 /// This records whether all of the fixups using this LSRUse are outside of 1095 /// the loop, in which case some special-case heuristics may be used. 1096 bool AllFixupsOutsideLoop; 1097 1098 /// RigidFormula is set to true to guarantee that this use will be associated 1099 /// with a single formula--the one that initially matched. Some SCEV 1100 /// expressions cannot be expanded. This allows LSR to consider the registers 1101 /// used by those expressions without the need to expand them later after 1102 /// changing the formula. 1103 bool RigidFormula; 1104 1105 /// This records the widest use type for any fixup using this 1106 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max 1107 /// fixup widths to be equivalent, because the narrower one may be relying on 1108 /// the implicit truncation to truncate away bogus bits. 1109 Type *WidestFixupType; 1110 1111 /// A list of ways to build a value that can satisfy this user. After the 1112 /// list is populated, one of these is selected heuristically and used to 1113 /// formulate a replacement for OperandValToReplace in UserInst. 1114 SmallVector<Formula, 12> Formulae; 1115 1116 /// The set of register candidates used by all formulae in this LSRUse. 1117 SmallPtrSet<const SCEV *, 4> Regs; 1118 1119 LSRUse(KindType K, MemAccessTy AT) 1120 : Kind(K), AccessTy(AT), MinOffset(INT64_MAX), MaxOffset(INT64_MIN), 1121 AllFixupsOutsideLoop(true), RigidFormula(false), 1122 WidestFixupType(nullptr) {} 1123 1124 LSRFixup &getNewFixup() { 1125 Fixups.push_back(LSRFixup()); 1126 return Fixups.back(); 1127 } 1128 1129 void pushFixup(LSRFixup &f) { 1130 Fixups.push_back(f); 1131 if (f.Offset > MaxOffset) 1132 MaxOffset = f.Offset; 1133 if (f.Offset < MinOffset) 1134 MinOffset = f.Offset; 1135 } 1136 1137 bool HasFormulaWithSameRegs(const Formula &F) const; 1138 float getNotSelectedProbability(const SCEV *Reg) const; 1139 bool InsertFormula(const Formula &F, const Loop &L); 1140 void DeleteFormula(Formula &F); 1141 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses); 1142 1143 void print(raw_ostream &OS) const; 1144 void dump() const; 1145 }; 1146 1147 } // end anonymous namespace 1148 1149 /// Tally up interesting quantities from the given register. 1150 void Cost::RateRegister(const SCEV *Reg, 1151 SmallPtrSetImpl<const SCEV *> &Regs, 1152 const Loop *L, 1153 ScalarEvolution &SE, DominatorTree &DT) { 1154 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) { 1155 // If this is an addrec for another loop, it should be an invariant 1156 // with respect to L since L is the innermost loop (at least 1157 // for now LSR only handles innermost loops). 1158 if (AR->getLoop() != L) { 1159 // If the AddRec exists, consider it's register free and leave it alone. 1160 if (isExistingPhi(AR, SE)) 1161 return; 1162 1163 // It is bad to allow LSR for current loop to add induction variables 1164 // for its sibling loops. 1165 if (!AR->getLoop()->contains(L)) { 1166 Lose(); 1167 return; 1168 } 1169 1170 // Otherwise, it will be an invariant with respect to Loop L. 1171 ++C.NumRegs; 1172 return; 1173 } 1174 C.AddRecCost += 1; /// TODO: This should be a function of the stride. 1175 1176 // Add the step value register, if it needs one. 1177 // TODO: The non-affine case isn't precisely modeled here. 1178 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) { 1179 if (!Regs.count(AR->getOperand(1))) { 1180 RateRegister(AR->getOperand(1), Regs, L, SE, DT); 1181 if (isLoser()) 1182 return; 1183 } 1184 } 1185 } 1186 ++C.NumRegs; 1187 1188 // Rough heuristic; favor registers which don't require extra setup 1189 // instructions in the preheader. 1190 if (!isa<SCEVUnknown>(Reg) && 1191 !isa<SCEVConstant>(Reg) && 1192 !(isa<SCEVAddRecExpr>(Reg) && 1193 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) || 1194 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart())))) 1195 ++C.SetupCost; 1196 1197 C.NumIVMuls += isa<SCEVMulExpr>(Reg) && 1198 SE.hasComputableLoopEvolution(Reg, L); 1199 } 1200 1201 /// Record this register in the set. If we haven't seen it before, rate 1202 /// it. Optional LoserRegs provides a way to declare any formula that refers to 1203 /// one of those regs an instant loser. 1204 void Cost::RatePrimaryRegister(const SCEV *Reg, 1205 SmallPtrSetImpl<const SCEV *> &Regs, 1206 const Loop *L, 1207 ScalarEvolution &SE, DominatorTree &DT, 1208 SmallPtrSetImpl<const SCEV *> *LoserRegs) { 1209 if (LoserRegs && LoserRegs->count(Reg)) { 1210 Lose(); 1211 return; 1212 } 1213 if (Regs.insert(Reg).second) { 1214 RateRegister(Reg, Regs, L, SE, DT); 1215 if (LoserRegs && isLoser()) 1216 LoserRegs->insert(Reg); 1217 } 1218 } 1219 1220 void Cost::RateFormula(const TargetTransformInfo &TTI, 1221 const Formula &F, 1222 SmallPtrSetImpl<const SCEV *> &Regs, 1223 const DenseSet<const SCEV *> &VisitedRegs, 1224 const Loop *L, 1225 ScalarEvolution &SE, DominatorTree &DT, 1226 const LSRUse &LU, 1227 SmallPtrSetImpl<const SCEV *> *LoserRegs) { 1228 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula"); 1229 // Tally up the registers. 1230 unsigned PrevAddRecCost = C.AddRecCost; 1231 unsigned PrevNumRegs = C.NumRegs; 1232 unsigned PrevNumBaseAdds = C.NumBaseAdds; 1233 if (const SCEV *ScaledReg = F.ScaledReg) { 1234 if (VisitedRegs.count(ScaledReg)) { 1235 Lose(); 1236 return; 1237 } 1238 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs); 1239 if (isLoser()) 1240 return; 1241 } 1242 for (const SCEV *BaseReg : F.BaseRegs) { 1243 if (VisitedRegs.count(BaseReg)) { 1244 Lose(); 1245 return; 1246 } 1247 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs); 1248 if (isLoser()) 1249 return; 1250 } 1251 1252 // Determine how many (unfolded) adds we'll need inside the loop. 1253 size_t NumBaseParts = F.getNumRegs(); 1254 if (NumBaseParts > 1) 1255 // Do not count the base and a possible second register if the target 1256 // allows to fold 2 registers. 1257 C.NumBaseAdds += 1258 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F))); 1259 C.NumBaseAdds += (F.UnfoldedOffset != 0); 1260 1261 // Accumulate non-free scaling amounts. 1262 C.ScaleCost += getScalingFactorCost(TTI, LU, F, *L); 1263 1264 // Tally up the non-zero immediates. 1265 for (const LSRFixup &Fixup : LU.Fixups) { 1266 int64_t O = Fixup.Offset; 1267 int64_t Offset = (uint64_t)O + F.BaseOffset; 1268 if (F.BaseGV) 1269 C.ImmCost += 64; // Handle symbolic values conservatively. 1270 // TODO: This should probably be the pointer size. 1271 else if (Offset != 0) 1272 C.ImmCost += APInt(64, Offset, true).getMinSignedBits(); 1273 1274 // Check with target if this offset with this instruction is 1275 // specifically not supported. 1276 if ((isa<LoadInst>(Fixup.UserInst) || isa<StoreInst>(Fixup.UserInst)) && 1277 !TTI.isFoldableMemAccessOffset(Fixup.UserInst, Offset)) 1278 C.NumBaseAdds++; 1279 } 1280 1281 // If we don't count instruction cost exit here. 1282 if (!InsnsCost) { 1283 assert(isValid() && "invalid cost"); 1284 return; 1285 } 1286 1287 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as 1288 // additional instruction (at least fill). 1289 unsigned TTIRegNum = TTI.getNumberOfRegisters(false) - 1; 1290 if (C.NumRegs > TTIRegNum) { 1291 // Cost already exceeded TTIRegNum, then only newly added register can add 1292 // new instructions. 1293 if (PrevNumRegs > TTIRegNum) 1294 C.Insns += (C.NumRegs - PrevNumRegs); 1295 else 1296 C.Insns += (C.NumRegs - TTIRegNum); 1297 } 1298 1299 // If ICmpZero formula ends with not 0, it could not be replaced by 1300 // just add or sub. We'll need to compare final result of AddRec. 1301 // That means we'll need an additional instruction. 1302 // For -10 + {0, +, 1}: 1303 // i = i + 1; 1304 // cmp i, 10 1305 // 1306 // For {-10, +, 1}: 1307 // i = i + 1; 1308 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd()) 1309 C.Insns++; 1310 // Each new AddRec adds 1 instruction to calculation. 1311 C.Insns += (C.AddRecCost - PrevAddRecCost); 1312 1313 // BaseAdds adds instructions for unfolded registers. 1314 if (LU.Kind != LSRUse::ICmpZero) 1315 C.Insns += C.NumBaseAdds - PrevNumBaseAdds; 1316 assert(isValid() && "invalid cost"); 1317 } 1318 1319 /// Set this cost to a losing value. 1320 void Cost::Lose() { 1321 C.Insns = ~0u; 1322 C.NumRegs = ~0u; 1323 C.AddRecCost = ~0u; 1324 C.NumIVMuls = ~0u; 1325 C.NumBaseAdds = ~0u; 1326 C.ImmCost = ~0u; 1327 C.SetupCost = ~0u; 1328 C.ScaleCost = ~0u; 1329 } 1330 1331 /// Choose the lower cost. 1332 bool Cost::isLess(Cost &Other, const TargetTransformInfo &TTI) { 1333 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost && 1334 C.Insns != Other.C.Insns) 1335 return C.Insns < Other.C.Insns; 1336 return TTI.isLSRCostLess(C, Other.C); 1337 } 1338 1339 void Cost::print(raw_ostream &OS) const { 1340 if (InsnsCost) 1341 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s "); 1342 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s"); 1343 if (C.AddRecCost != 0) 1344 OS << ", with addrec cost " << C.AddRecCost; 1345 if (C.NumIVMuls != 0) 1346 OS << ", plus " << C.NumIVMuls << " IV mul" 1347 << (C.NumIVMuls == 1 ? "" : "s"); 1348 if (C.NumBaseAdds != 0) 1349 OS << ", plus " << C.NumBaseAdds << " base add" 1350 << (C.NumBaseAdds == 1 ? "" : "s"); 1351 if (C.ScaleCost != 0) 1352 OS << ", plus " << C.ScaleCost << " scale cost"; 1353 if (C.ImmCost != 0) 1354 OS << ", plus " << C.ImmCost << " imm cost"; 1355 if (C.SetupCost != 0) 1356 OS << ", plus " << C.SetupCost << " setup cost"; 1357 } 1358 1359 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1360 LLVM_DUMP_METHOD void Cost::dump() const { 1361 print(errs()); errs() << '\n'; 1362 } 1363 #endif 1364 1365 LSRFixup::LSRFixup() 1366 : UserInst(nullptr), OperandValToReplace(nullptr), 1367 Offset(0) {} 1368 1369 /// Test whether this fixup always uses its value outside of the given loop. 1370 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const { 1371 // PHI nodes use their value in their incoming blocks. 1372 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) { 1373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1374 if (PN->getIncomingValue(i) == OperandValToReplace && 1375 L->contains(PN->getIncomingBlock(i))) 1376 return false; 1377 return true; 1378 } 1379 1380 return !L->contains(UserInst); 1381 } 1382 1383 void LSRFixup::print(raw_ostream &OS) const { 1384 OS << "UserInst="; 1385 // Store is common and interesting enough to be worth special-casing. 1386 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) { 1387 OS << "store "; 1388 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false); 1389 } else if (UserInst->getType()->isVoidTy()) 1390 OS << UserInst->getOpcodeName(); 1391 else 1392 UserInst->printAsOperand(OS, /*PrintType=*/false); 1393 1394 OS << ", OperandValToReplace="; 1395 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false); 1396 1397 for (const Loop *PIL : PostIncLoops) { 1398 OS << ", PostIncLoop="; 1399 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 1400 } 1401 1402 if (Offset != 0) 1403 OS << ", Offset=" << Offset; 1404 } 1405 1406 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1407 LLVM_DUMP_METHOD void LSRFixup::dump() const { 1408 print(errs()); errs() << '\n'; 1409 } 1410 #endif 1411 1412 /// Test whether this use as a formula which has the same registers as the given 1413 /// formula. 1414 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const { 1415 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1416 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1417 // Unstable sort by host order ok, because this is only used for uniquifying. 1418 std::sort(Key.begin(), Key.end()); 1419 return Uniquifier.count(Key); 1420 } 1421 1422 /// The function returns a probability of selecting formula without Reg. 1423 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const { 1424 unsigned FNum = 0; 1425 for (const Formula &F : Formulae) 1426 if (F.referencesReg(Reg)) 1427 FNum++; 1428 return ((float)(Formulae.size() - FNum)) / Formulae.size(); 1429 } 1430 1431 /// If the given formula has not yet been inserted, add it to the list, and 1432 /// return true. Return false otherwise. The formula must be in canonical form. 1433 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) { 1434 assert(F.isCanonical(L) && "Invalid canonical representation"); 1435 1436 if (!Formulae.empty() && RigidFormula) 1437 return false; 1438 1439 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1440 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1441 // Unstable sort by host order ok, because this is only used for uniquifying. 1442 std::sort(Key.begin(), Key.end()); 1443 1444 if (!Uniquifier.insert(Key).second) 1445 return false; 1446 1447 // Using a register to hold the value of 0 is not profitable. 1448 assert((!F.ScaledReg || !F.ScaledReg->isZero()) && 1449 "Zero allocated in a scaled register!"); 1450 #ifndef NDEBUG 1451 for (const SCEV *BaseReg : F.BaseRegs) 1452 assert(!BaseReg->isZero() && "Zero allocated in a base register!"); 1453 #endif 1454 1455 // Add the formula to the list. 1456 Formulae.push_back(F); 1457 1458 // Record registers now being used by this use. 1459 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1460 if (F.ScaledReg) 1461 Regs.insert(F.ScaledReg); 1462 1463 return true; 1464 } 1465 1466 /// Remove the given formula from this use's list. 1467 void LSRUse::DeleteFormula(Formula &F) { 1468 if (&F != &Formulae.back()) 1469 std::swap(F, Formulae.back()); 1470 Formulae.pop_back(); 1471 } 1472 1473 /// Recompute the Regs field, and update RegUses. 1474 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) { 1475 // Now that we've filtered out some formulae, recompute the Regs set. 1476 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs); 1477 Regs.clear(); 1478 for (const Formula &F : Formulae) { 1479 if (F.ScaledReg) Regs.insert(F.ScaledReg); 1480 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1481 } 1482 1483 // Update the RegTracker. 1484 for (const SCEV *S : OldRegs) 1485 if (!Regs.count(S)) 1486 RegUses.dropRegister(S, LUIdx); 1487 } 1488 1489 void LSRUse::print(raw_ostream &OS) const { 1490 OS << "LSR Use: Kind="; 1491 switch (Kind) { 1492 case Basic: OS << "Basic"; break; 1493 case Special: OS << "Special"; break; 1494 case ICmpZero: OS << "ICmpZero"; break; 1495 case Address: 1496 OS << "Address of "; 1497 if (AccessTy.MemTy->isPointerTy()) 1498 OS << "pointer"; // the full pointer type could be really verbose 1499 else { 1500 OS << *AccessTy.MemTy; 1501 } 1502 1503 OS << " in addrspace(" << AccessTy.AddrSpace << ')'; 1504 } 1505 1506 OS << ", Offsets={"; 1507 bool NeedComma = false; 1508 for (const LSRFixup &Fixup : Fixups) { 1509 if (NeedComma) OS << ','; 1510 OS << Fixup.Offset; 1511 NeedComma = true; 1512 } 1513 OS << '}'; 1514 1515 if (AllFixupsOutsideLoop) 1516 OS << ", all-fixups-outside-loop"; 1517 1518 if (WidestFixupType) 1519 OS << ", widest fixup type: " << *WidestFixupType; 1520 } 1521 1522 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1523 LLVM_DUMP_METHOD void LSRUse::dump() const { 1524 print(errs()); errs() << '\n'; 1525 } 1526 #endif 1527 1528 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1529 LSRUse::KindType Kind, MemAccessTy AccessTy, 1530 GlobalValue *BaseGV, int64_t BaseOffset, 1531 bool HasBaseReg, int64_t Scale) { 1532 switch (Kind) { 1533 case LSRUse::Address: 1534 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset, 1535 HasBaseReg, Scale, AccessTy.AddrSpace); 1536 1537 case LSRUse::ICmpZero: 1538 // There's not even a target hook for querying whether it would be legal to 1539 // fold a GV into an ICmp. 1540 if (BaseGV) 1541 return false; 1542 1543 // ICmp only has two operands; don't allow more than two non-trivial parts. 1544 if (Scale != 0 && HasBaseReg && BaseOffset != 0) 1545 return false; 1546 1547 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by 1548 // putting the scaled register in the other operand of the icmp. 1549 if (Scale != 0 && Scale != -1) 1550 return false; 1551 1552 // If we have low-level target information, ask the target if it can fold an 1553 // integer immediate on an icmp. 1554 if (BaseOffset != 0) { 1555 // We have one of: 1556 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset 1557 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset 1558 // Offs is the ICmp immediate. 1559 if (Scale == 0) 1560 // The cast does the right thing with INT64_MIN. 1561 BaseOffset = -(uint64_t)BaseOffset; 1562 return TTI.isLegalICmpImmediate(BaseOffset); 1563 } 1564 1565 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg 1566 return true; 1567 1568 case LSRUse::Basic: 1569 // Only handle single-register values. 1570 return !BaseGV && Scale == 0 && BaseOffset == 0; 1571 1572 case LSRUse::Special: 1573 // Special case Basic to handle -1 scales. 1574 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0; 1575 } 1576 1577 llvm_unreachable("Invalid LSRUse Kind!"); 1578 } 1579 1580 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1581 int64_t MinOffset, int64_t MaxOffset, 1582 LSRUse::KindType Kind, MemAccessTy AccessTy, 1583 GlobalValue *BaseGV, int64_t BaseOffset, 1584 bool HasBaseReg, int64_t Scale) { 1585 // Check for overflow. 1586 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) != 1587 (MinOffset > 0)) 1588 return false; 1589 MinOffset = (uint64_t)BaseOffset + MinOffset; 1590 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) != 1591 (MaxOffset > 0)) 1592 return false; 1593 MaxOffset = (uint64_t)BaseOffset + MaxOffset; 1594 1595 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset, 1596 HasBaseReg, Scale) && 1597 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset, 1598 HasBaseReg, Scale); 1599 } 1600 1601 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1602 int64_t MinOffset, int64_t MaxOffset, 1603 LSRUse::KindType Kind, MemAccessTy AccessTy, 1604 const Formula &F, const Loop &L) { 1605 // For the purpose of isAMCompletelyFolded either having a canonical formula 1606 // or a scale not equal to zero is correct. 1607 // Problems may arise from non canonical formulae having a scale == 0. 1608 // Strictly speaking it would best to just rely on canonical formulae. 1609 // However, when we generate the scaled formulae, we first check that the 1610 // scaling factor is profitable before computing the actual ScaledReg for 1611 // compile time sake. 1612 assert((F.isCanonical(L) || F.Scale != 0)); 1613 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1614 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale); 1615 } 1616 1617 /// Test whether we know how to expand the current formula. 1618 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1619 int64_t MaxOffset, LSRUse::KindType Kind, 1620 MemAccessTy AccessTy, GlobalValue *BaseGV, 1621 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) { 1622 // We know how to expand completely foldable formulae. 1623 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1624 BaseOffset, HasBaseReg, Scale) || 1625 // Or formulae that use a base register produced by a sum of base 1626 // registers. 1627 (Scale == 1 && 1628 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1629 BaseGV, BaseOffset, true, 0)); 1630 } 1631 1632 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1633 int64_t MaxOffset, LSRUse::KindType Kind, 1634 MemAccessTy AccessTy, const Formula &F) { 1635 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV, 1636 F.BaseOffset, F.HasBaseReg, F.Scale); 1637 } 1638 1639 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1640 const LSRUse &LU, const Formula &F) { 1641 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1642 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg, 1643 F.Scale); 1644 } 1645 1646 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, 1647 const LSRUse &LU, const Formula &F, 1648 const Loop &L) { 1649 if (!F.Scale) 1650 return 0; 1651 1652 // If the use is not completely folded in that instruction, we will have to 1653 // pay an extra cost only for scale != 1. 1654 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1655 LU.AccessTy, F, L)) 1656 return F.Scale != 1; 1657 1658 switch (LU.Kind) { 1659 case LSRUse::Address: { 1660 // Check the scaling factor cost with both the min and max offsets. 1661 int ScaleCostMinOffset = TTI.getScalingFactorCost( 1662 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg, 1663 F.Scale, LU.AccessTy.AddrSpace); 1664 int ScaleCostMaxOffset = TTI.getScalingFactorCost( 1665 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg, 1666 F.Scale, LU.AccessTy.AddrSpace); 1667 1668 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 && 1669 "Legal addressing mode has an illegal cost!"); 1670 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset); 1671 } 1672 case LSRUse::ICmpZero: 1673 case LSRUse::Basic: 1674 case LSRUse::Special: 1675 // The use is completely folded, i.e., everything is folded into the 1676 // instruction. 1677 return 0; 1678 } 1679 1680 llvm_unreachable("Invalid LSRUse Kind!"); 1681 } 1682 1683 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1684 LSRUse::KindType Kind, MemAccessTy AccessTy, 1685 GlobalValue *BaseGV, int64_t BaseOffset, 1686 bool HasBaseReg) { 1687 // Fast-path: zero is always foldable. 1688 if (BaseOffset == 0 && !BaseGV) return true; 1689 1690 // Conservatively, create an address with an immediate and a 1691 // base and a scale. 1692 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1693 1694 // Canonicalize a scale of 1 to a base register if the formula doesn't 1695 // already have a base register. 1696 if (!HasBaseReg && Scale == 1) { 1697 Scale = 0; 1698 HasBaseReg = true; 1699 } 1700 1701 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset, 1702 HasBaseReg, Scale); 1703 } 1704 1705 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1706 ScalarEvolution &SE, int64_t MinOffset, 1707 int64_t MaxOffset, LSRUse::KindType Kind, 1708 MemAccessTy AccessTy, const SCEV *S, 1709 bool HasBaseReg) { 1710 // Fast-path: zero is always foldable. 1711 if (S->isZero()) return true; 1712 1713 // Conservatively, create an address with an immediate and a 1714 // base and a scale. 1715 int64_t BaseOffset = ExtractImmediate(S, SE); 1716 GlobalValue *BaseGV = ExtractSymbol(S, SE); 1717 1718 // If there's anything else involved, it's not foldable. 1719 if (!S->isZero()) return false; 1720 1721 // Fast-path: zero is always foldable. 1722 if (BaseOffset == 0 && !BaseGV) return true; 1723 1724 // Conservatively, create an address with an immediate and a 1725 // base and a scale. 1726 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1727 1728 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1729 BaseOffset, HasBaseReg, Scale); 1730 } 1731 1732 namespace { 1733 1734 /// An individual increment in a Chain of IV increments. Relate an IV user to 1735 /// an expression that computes the IV it uses from the IV used by the previous 1736 /// link in the Chain. 1737 /// 1738 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the 1739 /// original IVOperand. The head of the chain's IVOperand is only valid during 1740 /// chain collection, before LSR replaces IV users. During chain generation, 1741 /// IncExpr can be used to find the new IVOperand that computes the same 1742 /// expression. 1743 struct IVInc { 1744 Instruction *UserInst; 1745 Value* IVOperand; 1746 const SCEV *IncExpr; 1747 1748 IVInc(Instruction *U, Value *O, const SCEV *E): 1749 UserInst(U), IVOperand(O), IncExpr(E) {} 1750 }; 1751 1752 // The list of IV increments in program order. We typically add the head of a 1753 // chain without finding subsequent links. 1754 struct IVChain { 1755 SmallVector<IVInc,1> Incs; 1756 const SCEV *ExprBase; 1757 1758 IVChain() : ExprBase(nullptr) {} 1759 1760 IVChain(const IVInc &Head, const SCEV *Base) 1761 : Incs(1, Head), ExprBase(Base) {} 1762 1763 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator; 1764 1765 // Return the first increment in the chain. 1766 const_iterator begin() const { 1767 assert(!Incs.empty()); 1768 return std::next(Incs.begin()); 1769 } 1770 const_iterator end() const { 1771 return Incs.end(); 1772 } 1773 1774 // Returns true if this chain contains any increments. 1775 bool hasIncs() const { return Incs.size() >= 2; } 1776 1777 // Add an IVInc to the end of this chain. 1778 void add(const IVInc &X) { Incs.push_back(X); } 1779 1780 // Returns the last UserInst in the chain. 1781 Instruction *tailUserInst() const { return Incs.back().UserInst; } 1782 1783 // Returns true if IncExpr can be profitably added to this chain. 1784 bool isProfitableIncrement(const SCEV *OperExpr, 1785 const SCEV *IncExpr, 1786 ScalarEvolution&); 1787 }; 1788 1789 /// Helper for CollectChains to track multiple IV increment uses. Distinguish 1790 /// between FarUsers that definitely cross IV increments and NearUsers that may 1791 /// be used between IV increments. 1792 struct ChainUsers { 1793 SmallPtrSet<Instruction*, 4> FarUsers; 1794 SmallPtrSet<Instruction*, 4> NearUsers; 1795 }; 1796 1797 /// This class holds state for the main loop strength reduction logic. 1798 class LSRInstance { 1799 IVUsers &IU; 1800 ScalarEvolution &SE; 1801 DominatorTree &DT; 1802 LoopInfo &LI; 1803 const TargetTransformInfo &TTI; 1804 Loop *const L; 1805 bool Changed; 1806 1807 /// This is the insert position that the current loop's induction variable 1808 /// increment should be placed. In simple loops, this is the latch block's 1809 /// terminator. But in more complicated cases, this is a position which will 1810 /// dominate all the in-loop post-increment users. 1811 Instruction *IVIncInsertPos; 1812 1813 /// Interesting factors between use strides. 1814 /// 1815 /// We explicitly use a SetVector which contains a SmallSet, instead of the 1816 /// default, a SmallDenseSet, because we need to use the full range of 1817 /// int64_ts, and there's currently no good way of doing that with 1818 /// SmallDenseSet. 1819 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors; 1820 1821 /// Interesting use types, to facilitate truncation reuse. 1822 SmallSetVector<Type *, 4> Types; 1823 1824 /// The list of interesting uses. 1825 SmallVector<LSRUse, 16> Uses; 1826 1827 /// Track which uses use which register candidates. 1828 RegUseTracker RegUses; 1829 1830 // Limit the number of chains to avoid quadratic behavior. We don't expect to 1831 // have more than a few IV increment chains in a loop. Missing a Chain falls 1832 // back to normal LSR behavior for those uses. 1833 static const unsigned MaxChains = 8; 1834 1835 /// IV users can form a chain of IV increments. 1836 SmallVector<IVChain, MaxChains> IVChainVec; 1837 1838 /// IV users that belong to profitable IVChains. 1839 SmallPtrSet<Use*, MaxChains> IVIncSet; 1840 1841 void OptimizeShadowIV(); 1842 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse); 1843 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse); 1844 void OptimizeLoopTermCond(); 1845 1846 void ChainInstruction(Instruction *UserInst, Instruction *IVOper, 1847 SmallVectorImpl<ChainUsers> &ChainUsersVec); 1848 void FinalizeChain(IVChain &Chain); 1849 void CollectChains(); 1850 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 1851 SmallVectorImpl<WeakTrackingVH> &DeadInsts); 1852 1853 void CollectInterestingTypesAndFactors(); 1854 void CollectFixupsAndInitialFormulae(); 1855 1856 // Support for sharing of LSRUses between LSRFixups. 1857 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy; 1858 UseMapTy UseMap; 1859 1860 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg, 1861 LSRUse::KindType Kind, MemAccessTy AccessTy); 1862 1863 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind, 1864 MemAccessTy AccessTy); 1865 1866 void DeleteUse(LSRUse &LU, size_t LUIdx); 1867 1868 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU); 1869 1870 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 1871 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 1872 void CountRegisters(const Formula &F, size_t LUIdx); 1873 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F); 1874 1875 void CollectLoopInvariantFixupsAndFormulae(); 1876 1877 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base, 1878 unsigned Depth = 0); 1879 1880 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 1881 const Formula &Base, unsigned Depth, 1882 size_t Idx, bool IsScaledReg = false); 1883 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base); 1884 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 1885 const Formula &Base, size_t Idx, 1886 bool IsScaledReg = false); 1887 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 1888 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx, 1889 const Formula &Base, 1890 const SmallVectorImpl<int64_t> &Worklist, 1891 size_t Idx, bool IsScaledReg = false); 1892 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 1893 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base); 1894 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base); 1895 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base); 1896 void GenerateCrossUseConstantOffsets(); 1897 void GenerateAllReuseFormulae(); 1898 1899 void FilterOutUndesirableDedicatedRegisters(); 1900 1901 size_t EstimateSearchSpaceComplexity() const; 1902 void NarrowSearchSpaceByDetectingSupersets(); 1903 void NarrowSearchSpaceByCollapsingUnrolledCode(); 1904 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 1905 void NarrowSearchSpaceByDeletingCostlyFormulas(); 1906 void NarrowSearchSpaceByPickingWinnerRegs(); 1907 void NarrowSearchSpaceUsingHeuristics(); 1908 1909 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 1910 Cost &SolutionCost, 1911 SmallVectorImpl<const Formula *> &Workspace, 1912 const Cost &CurCost, 1913 const SmallPtrSet<const SCEV *, 16> &CurRegs, 1914 DenseSet<const SCEV *> &VisitedRegs) const; 1915 void Solve(SmallVectorImpl<const Formula *> &Solution) const; 1916 1917 BasicBlock::iterator 1918 HoistInsertPosition(BasicBlock::iterator IP, 1919 const SmallVectorImpl<Instruction *> &Inputs) const; 1920 BasicBlock::iterator 1921 AdjustInsertPositionForExpand(BasicBlock::iterator IP, 1922 const LSRFixup &LF, 1923 const LSRUse &LU, 1924 SCEVExpander &Rewriter) const; 1925 1926 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 1927 BasicBlock::iterator IP, SCEVExpander &Rewriter, 1928 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 1929 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF, 1930 const Formula &F, SCEVExpander &Rewriter, 1931 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 1932 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 1933 SCEVExpander &Rewriter, 1934 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 1935 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution); 1936 1937 public: 1938 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, 1939 LoopInfo &LI, const TargetTransformInfo &TTI); 1940 1941 bool getChanged() const { return Changed; } 1942 1943 void print_factors_and_types(raw_ostream &OS) const; 1944 void print_fixups(raw_ostream &OS) const; 1945 void print_uses(raw_ostream &OS) const; 1946 void print(raw_ostream &OS) const; 1947 void dump() const; 1948 }; 1949 1950 } // end anonymous namespace 1951 1952 /// If IV is used in a int-to-float cast inside the loop then try to eliminate 1953 /// the cast operation. 1954 void LSRInstance::OptimizeShadowIV() { 1955 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 1956 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 1957 return; 1958 1959 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); 1960 UI != E; /* empty */) { 1961 IVUsers::const_iterator CandidateUI = UI; 1962 ++UI; 1963 Instruction *ShadowUse = CandidateUI->getUser(); 1964 Type *DestTy = nullptr; 1965 bool IsSigned = false; 1966 1967 /* If shadow use is a int->float cast then insert a second IV 1968 to eliminate this cast. 1969 1970 for (unsigned i = 0; i < n; ++i) 1971 foo((double)i); 1972 1973 is transformed into 1974 1975 double d = 0.0; 1976 for (unsigned i = 0; i < n; ++i, ++d) 1977 foo(d); 1978 */ 1979 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) { 1980 IsSigned = false; 1981 DestTy = UCast->getDestTy(); 1982 } 1983 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) { 1984 IsSigned = true; 1985 DestTy = SCast->getDestTy(); 1986 } 1987 if (!DestTy) continue; 1988 1989 // If target does not support DestTy natively then do not apply 1990 // this transformation. 1991 if (!TTI.isTypeLegal(DestTy)) continue; 1992 1993 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0)); 1994 if (!PH) continue; 1995 if (PH->getNumIncomingValues() != 2) continue; 1996 1997 Type *SrcTy = PH->getType(); 1998 int Mantissa = DestTy->getFPMantissaWidth(); 1999 if (Mantissa == -1) continue; 2000 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa) 2001 continue; 2002 2003 unsigned Entry, Latch; 2004 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) { 2005 Entry = 0; 2006 Latch = 1; 2007 } else { 2008 Entry = 1; 2009 Latch = 0; 2010 } 2011 2012 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry)); 2013 if (!Init) continue; 2014 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ? 2015 (double)Init->getSExtValue() : 2016 (double)Init->getZExtValue()); 2017 2018 BinaryOperator *Incr = 2019 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch)); 2020 if (!Incr) continue; 2021 if (Incr->getOpcode() != Instruction::Add 2022 && Incr->getOpcode() != Instruction::Sub) 2023 continue; 2024 2025 /* Initialize new IV, double d = 0.0 in above example. */ 2026 ConstantInt *C = nullptr; 2027 if (Incr->getOperand(0) == PH) 2028 C = dyn_cast<ConstantInt>(Incr->getOperand(1)); 2029 else if (Incr->getOperand(1) == PH) 2030 C = dyn_cast<ConstantInt>(Incr->getOperand(0)); 2031 else 2032 continue; 2033 2034 if (!C) continue; 2035 2036 // Ignore negative constants, as the code below doesn't handle them 2037 // correctly. TODO: Remove this restriction. 2038 if (!C->getValue().isStrictlyPositive()) continue; 2039 2040 /* Add new PHINode. */ 2041 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH); 2042 2043 /* create new increment. '++d' in above example. */ 2044 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue()); 2045 BinaryOperator *NewIncr = 2046 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ? 2047 Instruction::FAdd : Instruction::FSub, 2048 NewPH, CFP, "IV.S.next.", Incr); 2049 2050 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry)); 2051 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch)); 2052 2053 /* Remove cast operation */ 2054 ShadowUse->replaceAllUsesWith(NewPH); 2055 ShadowUse->eraseFromParent(); 2056 Changed = true; 2057 break; 2058 } 2059 } 2060 2061 /// If Cond has an operand that is an expression of an IV, set the IV user and 2062 /// stride information and return true, otherwise return false. 2063 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) { 2064 for (IVStrideUse &U : IU) 2065 if (U.getUser() == Cond) { 2066 // NOTE: we could handle setcc instructions with multiple uses here, but 2067 // InstCombine does it as well for simple uses, it's not clear that it 2068 // occurs enough in real life to handle. 2069 CondUse = &U; 2070 return true; 2071 } 2072 return false; 2073 } 2074 2075 /// Rewrite the loop's terminating condition if it uses a max computation. 2076 /// 2077 /// This is a narrow solution to a specific, but acute, problem. For loops 2078 /// like this: 2079 /// 2080 /// i = 0; 2081 /// do { 2082 /// p[i] = 0.0; 2083 /// } while (++i < n); 2084 /// 2085 /// the trip count isn't just 'n', because 'n' might not be positive. And 2086 /// unfortunately this can come up even for loops where the user didn't use 2087 /// a C do-while loop. For example, seemingly well-behaved top-test loops 2088 /// will commonly be lowered like this: 2089 // 2090 /// if (n > 0) { 2091 /// i = 0; 2092 /// do { 2093 /// p[i] = 0.0; 2094 /// } while (++i < n); 2095 /// } 2096 /// 2097 /// and then it's possible for subsequent optimization to obscure the if 2098 /// test in such a way that indvars can't find it. 2099 /// 2100 /// When indvars can't find the if test in loops like this, it creates a 2101 /// max expression, which allows it to give the loop a canonical 2102 /// induction variable: 2103 /// 2104 /// i = 0; 2105 /// max = n < 1 ? 1 : n; 2106 /// do { 2107 /// p[i] = 0.0; 2108 /// } while (++i != max); 2109 /// 2110 /// Canonical induction variables are necessary because the loop passes 2111 /// are designed around them. The most obvious example of this is the 2112 /// LoopInfo analysis, which doesn't remember trip count values. It 2113 /// expects to be able to rediscover the trip count each time it is 2114 /// needed, and it does this using a simple analysis that only succeeds if 2115 /// the loop has a canonical induction variable. 2116 /// 2117 /// However, when it comes time to generate code, the maximum operation 2118 /// can be quite costly, especially if it's inside of an outer loop. 2119 /// 2120 /// This function solves this problem by detecting this type of loop and 2121 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting 2122 /// the instructions for the maximum computation. 2123 /// 2124 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) { 2125 // Check that the loop matches the pattern we're looking for. 2126 if (Cond->getPredicate() != CmpInst::ICMP_EQ && 2127 Cond->getPredicate() != CmpInst::ICMP_NE) 2128 return Cond; 2129 2130 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1)); 2131 if (!Sel || !Sel->hasOneUse()) return Cond; 2132 2133 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 2134 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2135 return Cond; 2136 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1); 2137 2138 // Add one to the backedge-taken count to get the trip count. 2139 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount); 2140 if (IterationCount != SE.getSCEV(Sel)) return Cond; 2141 2142 // Check for a max calculation that matches the pattern. There's no check 2143 // for ICMP_ULE here because the comparison would be with zero, which 2144 // isn't interesting. 2145 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 2146 const SCEVNAryExpr *Max = nullptr; 2147 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) { 2148 Pred = ICmpInst::ICMP_SLE; 2149 Max = S; 2150 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) { 2151 Pred = ICmpInst::ICMP_SLT; 2152 Max = S; 2153 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) { 2154 Pred = ICmpInst::ICMP_ULT; 2155 Max = U; 2156 } else { 2157 // No match; bail. 2158 return Cond; 2159 } 2160 2161 // To handle a max with more than two operands, this optimization would 2162 // require additional checking and setup. 2163 if (Max->getNumOperands() != 2) 2164 return Cond; 2165 2166 const SCEV *MaxLHS = Max->getOperand(0); 2167 const SCEV *MaxRHS = Max->getOperand(1); 2168 2169 // ScalarEvolution canonicalizes constants to the left. For < and >, look 2170 // for a comparison with 1. For <= and >=, a comparison with zero. 2171 if (!MaxLHS || 2172 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One))) 2173 return Cond; 2174 2175 // Check the relevant induction variable for conformance to 2176 // the pattern. 2177 const SCEV *IV = SE.getSCEV(Cond->getOperand(0)); 2178 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV); 2179 if (!AR || !AR->isAffine() || 2180 AR->getStart() != One || 2181 AR->getStepRecurrence(SE) != One) 2182 return Cond; 2183 2184 assert(AR->getLoop() == L && 2185 "Loop condition operand is an addrec in a different loop!"); 2186 2187 // Check the right operand of the select, and remember it, as it will 2188 // be used in the new comparison instruction. 2189 Value *NewRHS = nullptr; 2190 if (ICmpInst::isTrueWhenEqual(Pred)) { 2191 // Look for n+1, and grab n. 2192 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1))) 2193 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2194 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2195 NewRHS = BO->getOperand(0); 2196 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2))) 2197 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2198 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2199 NewRHS = BO->getOperand(0); 2200 if (!NewRHS) 2201 return Cond; 2202 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS) 2203 NewRHS = Sel->getOperand(1); 2204 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS) 2205 NewRHS = Sel->getOperand(2); 2206 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS)) 2207 NewRHS = SU->getValue(); 2208 else 2209 // Max doesn't match expected pattern. 2210 return Cond; 2211 2212 // Determine the new comparison opcode. It may be signed or unsigned, 2213 // and the original comparison may be either equality or inequality. 2214 if (Cond->getPredicate() == CmpInst::ICMP_EQ) 2215 Pred = CmpInst::getInversePredicate(Pred); 2216 2217 // Ok, everything looks ok to change the condition into an SLT or SGE and 2218 // delete the max calculation. 2219 ICmpInst *NewCond = 2220 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp"); 2221 2222 // Delete the max calculation instructions. 2223 Cond->replaceAllUsesWith(NewCond); 2224 CondUse->setUser(NewCond); 2225 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0)); 2226 Cond->eraseFromParent(); 2227 Sel->eraseFromParent(); 2228 if (Cmp->use_empty()) 2229 Cmp->eraseFromParent(); 2230 return NewCond; 2231 } 2232 2233 /// Change loop terminating condition to use the postinc iv when possible. 2234 void 2235 LSRInstance::OptimizeLoopTermCond() { 2236 SmallPtrSet<Instruction *, 4> PostIncs; 2237 2238 // We need a different set of heuristics for rotated and non-rotated loops. 2239 // If a loop is rotated then the latch is also the backedge, so inserting 2240 // post-inc expressions just before the latch is ideal. To reduce live ranges 2241 // it also makes sense to rewrite terminating conditions to use post-inc 2242 // expressions. 2243 // 2244 // If the loop is not rotated then the latch is not a backedge; the latch 2245 // check is done in the loop head. Adding post-inc expressions before the 2246 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions 2247 // in the loop body. In this case we do *not* want to use post-inc expressions 2248 // in the latch check, and we want to insert post-inc expressions before 2249 // the backedge. 2250 BasicBlock *LatchBlock = L->getLoopLatch(); 2251 SmallVector<BasicBlock*, 8> ExitingBlocks; 2252 L->getExitingBlocks(ExitingBlocks); 2253 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) { 2254 return LatchBlock != BB; 2255 })) { 2256 // The backedge doesn't exit the loop; treat this as a head-tested loop. 2257 IVIncInsertPos = LatchBlock->getTerminator(); 2258 return; 2259 } 2260 2261 // Otherwise treat this as a rotated loop. 2262 for (BasicBlock *ExitingBlock : ExitingBlocks) { 2263 2264 // Get the terminating condition for the loop if possible. If we 2265 // can, we want to change it to use a post-incremented version of its 2266 // induction variable, to allow coalescing the live ranges for the IV into 2267 // one register value. 2268 2269 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2270 if (!TermBr) 2271 continue; 2272 // FIXME: Overly conservative, termination condition could be an 'or' etc.. 2273 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition())) 2274 continue; 2275 2276 // Search IVUsesByStride to find Cond's IVUse if there is one. 2277 IVStrideUse *CondUse = nullptr; 2278 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition()); 2279 if (!FindIVUserForCond(Cond, CondUse)) 2280 continue; 2281 2282 // If the trip count is computed in terms of a max (due to ScalarEvolution 2283 // being unable to find a sufficient guard, for example), change the loop 2284 // comparison to use SLT or ULT instead of NE. 2285 // One consequence of doing this now is that it disrupts the count-down 2286 // optimization. That's not always a bad thing though, because in such 2287 // cases it may still be worthwhile to avoid a max. 2288 Cond = OptimizeMax(Cond, CondUse); 2289 2290 // If this exiting block dominates the latch block, it may also use 2291 // the post-inc value if it won't be shared with other uses. 2292 // Check for dominance. 2293 if (!DT.dominates(ExitingBlock, LatchBlock)) 2294 continue; 2295 2296 // Conservatively avoid trying to use the post-inc value in non-latch 2297 // exits if there may be pre-inc users in intervening blocks. 2298 if (LatchBlock != ExitingBlock) 2299 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) 2300 // Test if the use is reachable from the exiting block. This dominator 2301 // query is a conservative approximation of reachability. 2302 if (&*UI != CondUse && 2303 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) { 2304 // Conservatively assume there may be reuse if the quotient of their 2305 // strides could be a legal scale. 2306 const SCEV *A = IU.getStride(*CondUse, L); 2307 const SCEV *B = IU.getStride(*UI, L); 2308 if (!A || !B) continue; 2309 if (SE.getTypeSizeInBits(A->getType()) != 2310 SE.getTypeSizeInBits(B->getType())) { 2311 if (SE.getTypeSizeInBits(A->getType()) > 2312 SE.getTypeSizeInBits(B->getType())) 2313 B = SE.getSignExtendExpr(B, A->getType()); 2314 else 2315 A = SE.getSignExtendExpr(A, B->getType()); 2316 } 2317 if (const SCEVConstant *D = 2318 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) { 2319 const ConstantInt *C = D->getValue(); 2320 // Stride of one or negative one can have reuse with non-addresses. 2321 if (C->isOne() || C->isAllOnesValue()) 2322 goto decline_post_inc; 2323 // Avoid weird situations. 2324 if (C->getValue().getMinSignedBits() >= 64 || 2325 C->getValue().isMinSignedValue()) 2326 goto decline_post_inc; 2327 // Check for possible scaled-address reuse. 2328 MemAccessTy AccessTy = getAccessType(UI->getUser()); 2329 int64_t Scale = C->getSExtValue(); 2330 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2331 /*BaseOffset=*/0, 2332 /*HasBaseReg=*/false, Scale, 2333 AccessTy.AddrSpace)) 2334 goto decline_post_inc; 2335 Scale = -Scale; 2336 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2337 /*BaseOffset=*/0, 2338 /*HasBaseReg=*/false, Scale, 2339 AccessTy.AddrSpace)) 2340 goto decline_post_inc; 2341 } 2342 } 2343 2344 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: " 2345 << *Cond << '\n'); 2346 2347 // It's possible for the setcc instruction to be anywhere in the loop, and 2348 // possible for it to have multiple users. If it is not immediately before 2349 // the exiting block branch, move it. 2350 if (&*++BasicBlock::iterator(Cond) != TermBr) { 2351 if (Cond->hasOneUse()) { 2352 Cond->moveBefore(TermBr); 2353 } else { 2354 // Clone the terminating condition and insert into the loopend. 2355 ICmpInst *OldCond = Cond; 2356 Cond = cast<ICmpInst>(Cond->clone()); 2357 Cond->setName(L->getHeader()->getName() + ".termcond"); 2358 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond); 2359 2360 // Clone the IVUse, as the old use still exists! 2361 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace()); 2362 TermBr->replaceUsesOfWith(OldCond, Cond); 2363 } 2364 } 2365 2366 // If we get to here, we know that we can transform the setcc instruction to 2367 // use the post-incremented version of the IV, allowing us to coalesce the 2368 // live ranges for the IV correctly. 2369 CondUse->transformToPostInc(L); 2370 Changed = true; 2371 2372 PostIncs.insert(Cond); 2373 decline_post_inc:; 2374 } 2375 2376 // Determine an insertion point for the loop induction variable increment. It 2377 // must dominate all the post-inc comparisons we just set up, and it must 2378 // dominate the loop latch edge. 2379 IVIncInsertPos = L->getLoopLatch()->getTerminator(); 2380 for (Instruction *Inst : PostIncs) { 2381 BasicBlock *BB = 2382 DT.findNearestCommonDominator(IVIncInsertPos->getParent(), 2383 Inst->getParent()); 2384 if (BB == Inst->getParent()) 2385 IVIncInsertPos = Inst; 2386 else if (BB != IVIncInsertPos->getParent()) 2387 IVIncInsertPos = BB->getTerminator(); 2388 } 2389 } 2390 2391 /// Determine if the given use can accommodate a fixup at the given offset and 2392 /// other details. If so, update the use and return true. 2393 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, 2394 bool HasBaseReg, LSRUse::KindType Kind, 2395 MemAccessTy AccessTy) { 2396 int64_t NewMinOffset = LU.MinOffset; 2397 int64_t NewMaxOffset = LU.MaxOffset; 2398 MemAccessTy NewAccessTy = AccessTy; 2399 2400 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to 2401 // something conservative, however this can pessimize in the case that one of 2402 // the uses will have all its uses outside the loop, for example. 2403 if (LU.Kind != Kind) 2404 return false; 2405 2406 // Check for a mismatched access type, and fall back conservatively as needed. 2407 // TODO: Be less conservative when the type is similar and can use the same 2408 // addressing modes. 2409 if (Kind == LSRUse::Address) { 2410 if (AccessTy.MemTy != LU.AccessTy.MemTy) { 2411 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(), 2412 AccessTy.AddrSpace); 2413 } 2414 } 2415 2416 // Conservatively assume HasBaseReg is true for now. 2417 if (NewOffset < LU.MinOffset) { 2418 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2419 LU.MaxOffset - NewOffset, HasBaseReg)) 2420 return false; 2421 NewMinOffset = NewOffset; 2422 } else if (NewOffset > LU.MaxOffset) { 2423 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2424 NewOffset - LU.MinOffset, HasBaseReg)) 2425 return false; 2426 NewMaxOffset = NewOffset; 2427 } 2428 2429 // Update the use. 2430 LU.MinOffset = NewMinOffset; 2431 LU.MaxOffset = NewMaxOffset; 2432 LU.AccessTy = NewAccessTy; 2433 return true; 2434 } 2435 2436 /// Return an LSRUse index and an offset value for a fixup which needs the given 2437 /// expression, with the given kind and optional access type. Either reuse an 2438 /// existing use or create a new one, as needed. 2439 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr, 2440 LSRUse::KindType Kind, 2441 MemAccessTy AccessTy) { 2442 const SCEV *Copy = Expr; 2443 int64_t Offset = ExtractImmediate(Expr, SE); 2444 2445 // Basic uses can't accept any offset, for example. 2446 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr, 2447 Offset, /*HasBaseReg=*/ true)) { 2448 Expr = Copy; 2449 Offset = 0; 2450 } 2451 2452 std::pair<UseMapTy::iterator, bool> P = 2453 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0)); 2454 if (!P.second) { 2455 // A use already existed with this base. 2456 size_t LUIdx = P.first->second; 2457 LSRUse &LU = Uses[LUIdx]; 2458 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy)) 2459 // Reuse this use. 2460 return std::make_pair(LUIdx, Offset); 2461 } 2462 2463 // Create a new use. 2464 size_t LUIdx = Uses.size(); 2465 P.first->second = LUIdx; 2466 Uses.push_back(LSRUse(Kind, AccessTy)); 2467 LSRUse &LU = Uses[LUIdx]; 2468 2469 LU.MinOffset = Offset; 2470 LU.MaxOffset = Offset; 2471 return std::make_pair(LUIdx, Offset); 2472 } 2473 2474 /// Delete the given use from the Uses list. 2475 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) { 2476 if (&LU != &Uses.back()) 2477 std::swap(LU, Uses.back()); 2478 Uses.pop_back(); 2479 2480 // Update RegUses. 2481 RegUses.swapAndDropUse(LUIdx, Uses.size()); 2482 } 2483 2484 /// Look for a use distinct from OrigLU which is has a formula that has the same 2485 /// registers as the given formula. 2486 LSRUse * 2487 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF, 2488 const LSRUse &OrigLU) { 2489 // Search all uses for the formula. This could be more clever. 2490 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 2491 LSRUse &LU = Uses[LUIdx]; 2492 // Check whether this use is close enough to OrigLU, to see whether it's 2493 // worthwhile looking through its formulae. 2494 // Ignore ICmpZero uses because they may contain formulae generated by 2495 // GenerateICmpZeroScales, in which case adding fixup offsets may 2496 // be invalid. 2497 if (&LU != &OrigLU && 2498 LU.Kind != LSRUse::ICmpZero && 2499 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy && 2500 LU.WidestFixupType == OrigLU.WidestFixupType && 2501 LU.HasFormulaWithSameRegs(OrigF)) { 2502 // Scan through this use's formulae. 2503 for (const Formula &F : LU.Formulae) { 2504 // Check to see if this formula has the same registers and symbols 2505 // as OrigF. 2506 if (F.BaseRegs == OrigF.BaseRegs && 2507 F.ScaledReg == OrigF.ScaledReg && 2508 F.BaseGV == OrigF.BaseGV && 2509 F.Scale == OrigF.Scale && 2510 F.UnfoldedOffset == OrigF.UnfoldedOffset) { 2511 if (F.BaseOffset == 0) 2512 return &LU; 2513 // This is the formula where all the registers and symbols matched; 2514 // there aren't going to be any others. Since we declined it, we 2515 // can skip the rest of the formulae and proceed to the next LSRUse. 2516 break; 2517 } 2518 } 2519 } 2520 } 2521 2522 // Nothing looked good. 2523 return nullptr; 2524 } 2525 2526 void LSRInstance::CollectInterestingTypesAndFactors() { 2527 SmallSetVector<const SCEV *, 4> Strides; 2528 2529 // Collect interesting types and strides. 2530 SmallVector<const SCEV *, 4> Worklist; 2531 for (const IVStrideUse &U : IU) { 2532 const SCEV *Expr = IU.getExpr(U); 2533 2534 // Collect interesting types. 2535 Types.insert(SE.getEffectiveSCEVType(Expr->getType())); 2536 2537 // Add strides for mentioned loops. 2538 Worklist.push_back(Expr); 2539 do { 2540 const SCEV *S = Worklist.pop_back_val(); 2541 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 2542 if (AR->getLoop() == L) 2543 Strides.insert(AR->getStepRecurrence(SE)); 2544 Worklist.push_back(AR->getStart()); 2545 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 2546 Worklist.append(Add->op_begin(), Add->op_end()); 2547 } 2548 } while (!Worklist.empty()); 2549 } 2550 2551 // Compute interesting factors from the set of interesting strides. 2552 for (SmallSetVector<const SCEV *, 4>::const_iterator 2553 I = Strides.begin(), E = Strides.end(); I != E; ++I) 2554 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter = 2555 std::next(I); NewStrideIter != E; ++NewStrideIter) { 2556 const SCEV *OldStride = *I; 2557 const SCEV *NewStride = *NewStrideIter; 2558 2559 if (SE.getTypeSizeInBits(OldStride->getType()) != 2560 SE.getTypeSizeInBits(NewStride->getType())) { 2561 if (SE.getTypeSizeInBits(OldStride->getType()) > 2562 SE.getTypeSizeInBits(NewStride->getType())) 2563 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType()); 2564 else 2565 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType()); 2566 } 2567 if (const SCEVConstant *Factor = 2568 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride, 2569 SE, true))) { 2570 if (Factor->getAPInt().getMinSignedBits() <= 64) 2571 Factors.insert(Factor->getAPInt().getSExtValue()); 2572 } else if (const SCEVConstant *Factor = 2573 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride, 2574 NewStride, 2575 SE, true))) { 2576 if (Factor->getAPInt().getMinSignedBits() <= 64) 2577 Factors.insert(Factor->getAPInt().getSExtValue()); 2578 } 2579 } 2580 2581 // If all uses use the same type, don't bother looking for truncation-based 2582 // reuse. 2583 if (Types.size() == 1) 2584 Types.clear(); 2585 2586 DEBUG(print_factors_and_types(dbgs())); 2587 } 2588 2589 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in 2590 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to 2591 /// IVStrideUses, we could partially skip this. 2592 static User::op_iterator 2593 findIVOperand(User::op_iterator OI, User::op_iterator OE, 2594 Loop *L, ScalarEvolution &SE) { 2595 for(; OI != OE; ++OI) { 2596 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) { 2597 if (!SE.isSCEVable(Oper->getType())) 2598 continue; 2599 2600 if (const SCEVAddRecExpr *AR = 2601 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) { 2602 if (AR->getLoop() == L) 2603 break; 2604 } 2605 } 2606 } 2607 return OI; 2608 } 2609 2610 /// IVChain logic must consistenctly peek base TruncInst operands, so wrap it in 2611 /// a convenient helper. 2612 static Value *getWideOperand(Value *Oper) { 2613 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper)) 2614 return Trunc->getOperand(0); 2615 return Oper; 2616 } 2617 2618 /// Return true if we allow an IV chain to include both types. 2619 static bool isCompatibleIVType(Value *LVal, Value *RVal) { 2620 Type *LType = LVal->getType(); 2621 Type *RType = RVal->getType(); 2622 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() && 2623 // Different address spaces means (possibly) 2624 // different types of the pointer implementation, 2625 // e.g. i16 vs i32 so disallow that. 2626 (LType->getPointerAddressSpace() == 2627 RType->getPointerAddressSpace())); 2628 } 2629 2630 /// Return an approximation of this SCEV expression's "base", or NULL for any 2631 /// constant. Returning the expression itself is conservative. Returning a 2632 /// deeper subexpression is more precise and valid as long as it isn't less 2633 /// complex than another subexpression. For expressions involving multiple 2634 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids 2635 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i], 2636 /// IVInc==b-a. 2637 /// 2638 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost 2639 /// SCEVUnknown, we simply return the rightmost SCEV operand. 2640 static const SCEV *getExprBase(const SCEV *S) { 2641 switch (S->getSCEVType()) { 2642 default: // uncluding scUnknown. 2643 return S; 2644 case scConstant: 2645 return nullptr; 2646 case scTruncate: 2647 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand()); 2648 case scZeroExtend: 2649 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand()); 2650 case scSignExtend: 2651 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand()); 2652 case scAddExpr: { 2653 // Skip over scaled operands (scMulExpr) to follow add operands as long as 2654 // there's nothing more complex. 2655 // FIXME: not sure if we want to recognize negation. 2656 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S); 2657 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()), 2658 E(Add->op_begin()); I != E; ++I) { 2659 const SCEV *SubExpr = *I; 2660 if (SubExpr->getSCEVType() == scAddExpr) 2661 return getExprBase(SubExpr); 2662 2663 if (SubExpr->getSCEVType() != scMulExpr) 2664 return SubExpr; 2665 } 2666 return S; // all operands are scaled, be conservative. 2667 } 2668 case scAddRecExpr: 2669 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart()); 2670 } 2671 } 2672 2673 /// Return true if the chain increment is profitable to expand into a loop 2674 /// invariant value, which may require its own register. A profitable chain 2675 /// increment will be an offset relative to the same base. We allow such offsets 2676 /// to potentially be used as chain increment as long as it's not obviously 2677 /// expensive to expand using real instructions. 2678 bool IVChain::isProfitableIncrement(const SCEV *OperExpr, 2679 const SCEV *IncExpr, 2680 ScalarEvolution &SE) { 2681 // Aggressively form chains when -stress-ivchain. 2682 if (StressIVChain) 2683 return true; 2684 2685 // Do not replace a constant offset from IV head with a nonconstant IV 2686 // increment. 2687 if (!isa<SCEVConstant>(IncExpr)) { 2688 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand)); 2689 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr))) 2690 return false; 2691 } 2692 2693 SmallPtrSet<const SCEV*, 8> Processed; 2694 return !isHighCostExpansion(IncExpr, Processed, SE); 2695 } 2696 2697 /// Return true if the number of registers needed for the chain is estimated to 2698 /// be less than the number required for the individual IV users. First prohibit 2699 /// any IV users that keep the IV live across increments (the Users set should 2700 /// be empty). Next count the number and type of increments in the chain. 2701 /// 2702 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't 2703 /// effectively use postinc addressing modes. Only consider it profitable it the 2704 /// increments can be computed in fewer registers when chained. 2705 /// 2706 /// TODO: Consider IVInc free if it's already used in another chains. 2707 static bool 2708 isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users, 2709 ScalarEvolution &SE, const TargetTransformInfo &TTI) { 2710 if (StressIVChain) 2711 return true; 2712 2713 if (!Chain.hasIncs()) 2714 return false; 2715 2716 if (!Users.empty()) { 2717 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n"; 2718 for (Instruction *Inst : Users) { 2719 dbgs() << " " << *Inst << "\n"; 2720 }); 2721 return false; 2722 } 2723 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 2724 2725 // The chain itself may require a register, so intialize cost to 1. 2726 int cost = 1; 2727 2728 // A complete chain likely eliminates the need for keeping the original IV in 2729 // a register. LSR does not currently know how to form a complete chain unless 2730 // the header phi already exists. 2731 if (isa<PHINode>(Chain.tailUserInst()) 2732 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) { 2733 --cost; 2734 } 2735 const SCEV *LastIncExpr = nullptr; 2736 unsigned NumConstIncrements = 0; 2737 unsigned NumVarIncrements = 0; 2738 unsigned NumReusedIncrements = 0; 2739 for (const IVInc &Inc : Chain) { 2740 if (Inc.IncExpr->isZero()) 2741 continue; 2742 2743 // Incrementing by zero or some constant is neutral. We assume constants can 2744 // be folded into an addressing mode or an add's immediate operand. 2745 if (isa<SCEVConstant>(Inc.IncExpr)) { 2746 ++NumConstIncrements; 2747 continue; 2748 } 2749 2750 if (Inc.IncExpr == LastIncExpr) 2751 ++NumReusedIncrements; 2752 else 2753 ++NumVarIncrements; 2754 2755 LastIncExpr = Inc.IncExpr; 2756 } 2757 // An IV chain with a single increment is handled by LSR's postinc 2758 // uses. However, a chain with multiple increments requires keeping the IV's 2759 // value live longer than it needs to be if chained. 2760 if (NumConstIncrements > 1) 2761 --cost; 2762 2763 // Materializing increment expressions in the preheader that didn't exist in 2764 // the original code may cost a register. For example, sign-extended array 2765 // indices can produce ridiculous increments like this: 2766 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64))) 2767 cost += NumVarIncrements; 2768 2769 // Reusing variable increments likely saves a register to hold the multiple of 2770 // the stride. 2771 cost -= NumReusedIncrements; 2772 2773 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost 2774 << "\n"); 2775 2776 return cost < 0; 2777 } 2778 2779 /// Add this IV user to an existing chain or make it the head of a new chain. 2780 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper, 2781 SmallVectorImpl<ChainUsers> &ChainUsersVec) { 2782 // When IVs are used as types of varying widths, they are generally converted 2783 // to a wider type with some uses remaining narrow under a (free) trunc. 2784 Value *const NextIV = getWideOperand(IVOper); 2785 const SCEV *const OperExpr = SE.getSCEV(NextIV); 2786 const SCEV *const OperExprBase = getExprBase(OperExpr); 2787 2788 // Visit all existing chains. Check if its IVOper can be computed as a 2789 // profitable loop invariant increment from the last link in the Chain. 2790 unsigned ChainIdx = 0, NChains = IVChainVec.size(); 2791 const SCEV *LastIncExpr = nullptr; 2792 for (; ChainIdx < NChains; ++ChainIdx) { 2793 IVChain &Chain = IVChainVec[ChainIdx]; 2794 2795 // Prune the solution space aggressively by checking that both IV operands 2796 // are expressions that operate on the same unscaled SCEVUnknown. This 2797 // "base" will be canceled by the subsequent getMinusSCEV call. Checking 2798 // first avoids creating extra SCEV expressions. 2799 if (!StressIVChain && Chain.ExprBase != OperExprBase) 2800 continue; 2801 2802 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand); 2803 if (!isCompatibleIVType(PrevIV, NextIV)) 2804 continue; 2805 2806 // A phi node terminates a chain. 2807 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst())) 2808 continue; 2809 2810 // The increment must be loop-invariant so it can be kept in a register. 2811 const SCEV *PrevExpr = SE.getSCEV(PrevIV); 2812 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr); 2813 if (!SE.isLoopInvariant(IncExpr, L)) 2814 continue; 2815 2816 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) { 2817 LastIncExpr = IncExpr; 2818 break; 2819 } 2820 } 2821 // If we haven't found a chain, create a new one, unless we hit the max. Don't 2822 // bother for phi nodes, because they must be last in the chain. 2823 if (ChainIdx == NChains) { 2824 if (isa<PHINode>(UserInst)) 2825 return; 2826 if (NChains >= MaxChains && !StressIVChain) { 2827 DEBUG(dbgs() << "IV Chain Limit\n"); 2828 return; 2829 } 2830 LastIncExpr = OperExpr; 2831 // IVUsers may have skipped over sign/zero extensions. We don't currently 2832 // attempt to form chains involving extensions unless they can be hoisted 2833 // into this loop's AddRec. 2834 if (!isa<SCEVAddRecExpr>(LastIncExpr)) 2835 return; 2836 ++NChains; 2837 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr), 2838 OperExprBase)); 2839 ChainUsersVec.resize(NChains); 2840 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst 2841 << ") IV=" << *LastIncExpr << "\n"); 2842 } else { 2843 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst 2844 << ") IV+" << *LastIncExpr << "\n"); 2845 // Add this IV user to the end of the chain. 2846 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr)); 2847 } 2848 IVChain &Chain = IVChainVec[ChainIdx]; 2849 2850 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers; 2851 // This chain's NearUsers become FarUsers. 2852 if (!LastIncExpr->isZero()) { 2853 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(), 2854 NearUsers.end()); 2855 NearUsers.clear(); 2856 } 2857 2858 // All other uses of IVOperand become near uses of the chain. 2859 // We currently ignore intermediate values within SCEV expressions, assuming 2860 // they will eventually be used be the current chain, or can be computed 2861 // from one of the chain increments. To be more precise we could 2862 // transitively follow its user and only add leaf IV users to the set. 2863 for (User *U : IVOper->users()) { 2864 Instruction *OtherUse = dyn_cast<Instruction>(U); 2865 if (!OtherUse) 2866 continue; 2867 // Uses in the chain will no longer be uses if the chain is formed. 2868 // Include the head of the chain in this iteration (not Chain.begin()). 2869 IVChain::const_iterator IncIter = Chain.Incs.begin(); 2870 IVChain::const_iterator IncEnd = Chain.Incs.end(); 2871 for( ; IncIter != IncEnd; ++IncIter) { 2872 if (IncIter->UserInst == OtherUse) 2873 break; 2874 } 2875 if (IncIter != IncEnd) 2876 continue; 2877 2878 if (SE.isSCEVable(OtherUse->getType()) 2879 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse)) 2880 && IU.isIVUserOrOperand(OtherUse)) { 2881 continue; 2882 } 2883 NearUsers.insert(OtherUse); 2884 } 2885 2886 // Since this user is part of the chain, it's no longer considered a use 2887 // of the chain. 2888 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst); 2889 } 2890 2891 /// Populate the vector of Chains. 2892 /// 2893 /// This decreases ILP at the architecture level. Targets with ample registers, 2894 /// multiple memory ports, and no register renaming probably don't want 2895 /// this. However, such targets should probably disable LSR altogether. 2896 /// 2897 /// The job of LSR is to make a reasonable choice of induction variables across 2898 /// the loop. Subsequent passes can easily "unchain" computation exposing more 2899 /// ILP *within the loop* if the target wants it. 2900 /// 2901 /// Finding the best IV chain is potentially a scheduling problem. Since LSR 2902 /// will not reorder memory operations, it will recognize this as a chain, but 2903 /// will generate redundant IV increments. Ideally this would be corrected later 2904 /// by a smart scheduler: 2905 /// = A[i] 2906 /// = A[i+x] 2907 /// A[i] = 2908 /// A[i+x] = 2909 /// 2910 /// TODO: Walk the entire domtree within this loop, not just the path to the 2911 /// loop latch. This will discover chains on side paths, but requires 2912 /// maintaining multiple copies of the Chains state. 2913 void LSRInstance::CollectChains() { 2914 DEBUG(dbgs() << "Collecting IV Chains.\n"); 2915 SmallVector<ChainUsers, 8> ChainUsersVec; 2916 2917 SmallVector<BasicBlock *,8> LatchPath; 2918 BasicBlock *LoopHeader = L->getHeader(); 2919 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch()); 2920 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) { 2921 LatchPath.push_back(Rung->getBlock()); 2922 } 2923 LatchPath.push_back(LoopHeader); 2924 2925 // Walk the instruction stream from the loop header to the loop latch. 2926 for (BasicBlock *BB : reverse(LatchPath)) { 2927 for (Instruction &I : *BB) { 2928 // Skip instructions that weren't seen by IVUsers analysis. 2929 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I)) 2930 continue; 2931 2932 // Ignore users that are part of a SCEV expression. This way we only 2933 // consider leaf IV Users. This effectively rediscovers a portion of 2934 // IVUsers analysis but in program order this time. 2935 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I))) 2936 continue; 2937 2938 // Remove this instruction from any NearUsers set it may be in. 2939 for (unsigned ChainIdx = 0, NChains = IVChainVec.size(); 2940 ChainIdx < NChains; ++ChainIdx) { 2941 ChainUsersVec[ChainIdx].NearUsers.erase(&I); 2942 } 2943 // Search for operands that can be chained. 2944 SmallPtrSet<Instruction*, 4> UniqueOperands; 2945 User::op_iterator IVOpEnd = I.op_end(); 2946 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE); 2947 while (IVOpIter != IVOpEnd) { 2948 Instruction *IVOpInst = cast<Instruction>(*IVOpIter); 2949 if (UniqueOperands.insert(IVOpInst).second) 2950 ChainInstruction(&I, IVOpInst, ChainUsersVec); 2951 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 2952 } 2953 } // Continue walking down the instructions. 2954 } // Continue walking down the domtree. 2955 // Visit phi backedges to determine if the chain can generate the IV postinc. 2956 for (BasicBlock::iterator I = L->getHeader()->begin(); 2957 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 2958 if (!SE.isSCEVable(PN->getType())) 2959 continue; 2960 2961 Instruction *IncV = 2962 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch())); 2963 if (IncV) 2964 ChainInstruction(PN, IncV, ChainUsersVec); 2965 } 2966 // Remove any unprofitable chains. 2967 unsigned ChainIdx = 0; 2968 for (unsigned UsersIdx = 0, NChains = IVChainVec.size(); 2969 UsersIdx < NChains; ++UsersIdx) { 2970 if (!isProfitableChain(IVChainVec[UsersIdx], 2971 ChainUsersVec[UsersIdx].FarUsers, SE, TTI)) 2972 continue; 2973 // Preserve the chain at UsesIdx. 2974 if (ChainIdx != UsersIdx) 2975 IVChainVec[ChainIdx] = IVChainVec[UsersIdx]; 2976 FinalizeChain(IVChainVec[ChainIdx]); 2977 ++ChainIdx; 2978 } 2979 IVChainVec.resize(ChainIdx); 2980 } 2981 2982 void LSRInstance::FinalizeChain(IVChain &Chain) { 2983 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 2984 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n"); 2985 2986 for (const IVInc &Inc : Chain) { 2987 DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n"); 2988 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand); 2989 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand"); 2990 IVIncSet.insert(UseI); 2991 } 2992 } 2993 2994 /// Return true if the IVInc can be folded into an addressing mode. 2995 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst, 2996 Value *Operand, const TargetTransformInfo &TTI) { 2997 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr); 2998 if (!IncConst || !isAddressUse(UserInst, Operand)) 2999 return false; 3000 3001 if (IncConst->getAPInt().getMinSignedBits() > 64) 3002 return false; 3003 3004 MemAccessTy AccessTy = getAccessType(UserInst); 3005 int64_t IncOffset = IncConst->getValue()->getSExtValue(); 3006 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr, 3007 IncOffset, /*HaseBaseReg=*/false)) 3008 return false; 3009 3010 return true; 3011 } 3012 3013 /// Generate an add or subtract for each IVInc in a chain to materialize the IV 3014 /// user's operand from the previous IV user's operand. 3015 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 3016 SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 3017 // Find the new IVOperand for the head of the chain. It may have been replaced 3018 // by LSR. 3019 const IVInc &Head = Chain.Incs[0]; 3020 User::op_iterator IVOpEnd = Head.UserInst->op_end(); 3021 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user. 3022 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(), 3023 IVOpEnd, L, SE); 3024 Value *IVSrc = nullptr; 3025 while (IVOpIter != IVOpEnd) { 3026 IVSrc = getWideOperand(*IVOpIter); 3027 3028 // If this operand computes the expression that the chain needs, we may use 3029 // it. (Check this after setting IVSrc which is used below.) 3030 // 3031 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too 3032 // narrow for the chain, so we can no longer use it. We do allow using a 3033 // wider phi, assuming the LSR checked for free truncation. In that case we 3034 // should already have a truncate on this operand such that 3035 // getSCEV(IVSrc) == IncExpr. 3036 if (SE.getSCEV(*IVOpIter) == Head.IncExpr 3037 || SE.getSCEV(IVSrc) == Head.IncExpr) { 3038 break; 3039 } 3040 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 3041 } 3042 if (IVOpIter == IVOpEnd) { 3043 // Gracefully give up on this chain. 3044 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n"); 3045 return; 3046 } 3047 3048 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n"); 3049 Type *IVTy = IVSrc->getType(); 3050 Type *IntTy = SE.getEffectiveSCEVType(IVTy); 3051 const SCEV *LeftOverExpr = nullptr; 3052 for (const IVInc &Inc : Chain) { 3053 Instruction *InsertPt = Inc.UserInst; 3054 if (isa<PHINode>(InsertPt)) 3055 InsertPt = L->getLoopLatch()->getTerminator(); 3056 3057 // IVOper will replace the current IV User's operand. IVSrc is the IV 3058 // value currently held in a register. 3059 Value *IVOper = IVSrc; 3060 if (!Inc.IncExpr->isZero()) { 3061 // IncExpr was the result of subtraction of two narrow values, so must 3062 // be signed. 3063 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy); 3064 LeftOverExpr = LeftOverExpr ? 3065 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr; 3066 } 3067 if (LeftOverExpr && !LeftOverExpr->isZero()) { 3068 // Expand the IV increment. 3069 Rewriter.clearPostInc(); 3070 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt); 3071 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc), 3072 SE.getUnknown(IncV)); 3073 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt); 3074 3075 // If an IV increment can't be folded, use it as the next IV value. 3076 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) { 3077 assert(IVTy == IVOper->getType() && "inconsistent IV increment type"); 3078 IVSrc = IVOper; 3079 LeftOverExpr = nullptr; 3080 } 3081 } 3082 Type *OperTy = Inc.IVOperand->getType(); 3083 if (IVTy != OperTy) { 3084 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) && 3085 "cannot extend a chained IV"); 3086 IRBuilder<> Builder(InsertPt); 3087 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain"); 3088 } 3089 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper); 3090 DeadInsts.emplace_back(Inc.IVOperand); 3091 } 3092 // If LSR created a new, wider phi, we may also replace its postinc. We only 3093 // do this if we also found a wide value for the head of the chain. 3094 if (isa<PHINode>(Chain.tailUserInst())) { 3095 for (BasicBlock::iterator I = L->getHeader()->begin(); 3096 PHINode *Phi = dyn_cast<PHINode>(I); ++I) { 3097 if (!isCompatibleIVType(Phi, IVSrc)) 3098 continue; 3099 Instruction *PostIncV = dyn_cast<Instruction>( 3100 Phi->getIncomingValueForBlock(L->getLoopLatch())); 3101 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc))) 3102 continue; 3103 Value *IVOper = IVSrc; 3104 Type *PostIncTy = PostIncV->getType(); 3105 if (IVTy != PostIncTy) { 3106 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types"); 3107 IRBuilder<> Builder(L->getLoopLatch()->getTerminator()); 3108 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc()); 3109 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain"); 3110 } 3111 Phi->replaceUsesOfWith(PostIncV, IVOper); 3112 DeadInsts.emplace_back(PostIncV); 3113 } 3114 } 3115 } 3116 3117 void LSRInstance::CollectFixupsAndInitialFormulae() { 3118 for (const IVStrideUse &U : IU) { 3119 Instruction *UserInst = U.getUser(); 3120 // Skip IV users that are part of profitable IV Chains. 3121 User::op_iterator UseI = 3122 find(UserInst->operands(), U.getOperandValToReplace()); 3123 assert(UseI != UserInst->op_end() && "cannot find IV operand"); 3124 if (IVIncSet.count(UseI)) { 3125 DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n'); 3126 continue; 3127 } 3128 3129 LSRUse::KindType Kind = LSRUse::Basic; 3130 MemAccessTy AccessTy; 3131 if (isAddressUse(UserInst, U.getOperandValToReplace())) { 3132 Kind = LSRUse::Address; 3133 AccessTy = getAccessType(UserInst); 3134 } 3135 3136 const SCEV *S = IU.getExpr(U); 3137 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops(); 3138 3139 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as 3140 // (N - i == 0), and this allows (N - i) to be the expression that we work 3141 // with rather than just N or i, so we can consider the register 3142 // requirements for both N and i at the same time. Limiting this code to 3143 // equality icmps is not a problem because all interesting loops use 3144 // equality icmps, thanks to IndVarSimplify. 3145 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) 3146 if (CI->isEquality()) { 3147 // Swap the operands if needed to put the OperandValToReplace on the 3148 // left, for consistency. 3149 Value *NV = CI->getOperand(1); 3150 if (NV == U.getOperandValToReplace()) { 3151 CI->setOperand(1, CI->getOperand(0)); 3152 CI->setOperand(0, NV); 3153 NV = CI->getOperand(1); 3154 Changed = true; 3155 } 3156 3157 // x == y --> x - y == 0 3158 const SCEV *N = SE.getSCEV(NV); 3159 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) { 3160 // S is normalized, so normalize N before folding it into S 3161 // to keep the result normalized. 3162 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE); 3163 Kind = LSRUse::ICmpZero; 3164 S = SE.getMinusSCEV(N, S); 3165 } 3166 3167 // -1 and the negations of all interesting strides (except the negation 3168 // of -1) are now also interesting. 3169 for (size_t i = 0, e = Factors.size(); i != e; ++i) 3170 if (Factors[i] != -1) 3171 Factors.insert(-(uint64_t)Factors[i]); 3172 Factors.insert(-1); 3173 } 3174 3175 // Get or create an LSRUse. 3176 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy); 3177 size_t LUIdx = P.first; 3178 int64_t Offset = P.second; 3179 LSRUse &LU = Uses[LUIdx]; 3180 3181 // Record the fixup. 3182 LSRFixup &LF = LU.getNewFixup(); 3183 LF.UserInst = UserInst; 3184 LF.OperandValToReplace = U.getOperandValToReplace(); 3185 LF.PostIncLoops = TmpPostIncLoops; 3186 LF.Offset = Offset; 3187 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3188 3189 if (!LU.WidestFixupType || 3190 SE.getTypeSizeInBits(LU.WidestFixupType) < 3191 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3192 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3193 3194 // If this is the first use of this LSRUse, give it a formula. 3195 if (LU.Formulae.empty()) { 3196 InsertInitialFormula(S, LU, LUIdx); 3197 CountRegisters(LU.Formulae.back(), LUIdx); 3198 } 3199 } 3200 3201 DEBUG(print_fixups(dbgs())); 3202 } 3203 3204 /// Insert a formula for the given expression into the given use, separating out 3205 /// loop-variant portions from loop-invariant and loop-computable portions. 3206 void 3207 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) { 3208 // Mark uses whose expressions cannot be expanded. 3209 if (!isSafeToExpand(S, SE)) 3210 LU.RigidFormula = true; 3211 3212 Formula F; 3213 F.initialMatch(S, L, SE); 3214 bool Inserted = InsertFormula(LU, LUIdx, F); 3215 assert(Inserted && "Initial formula already exists!"); (void)Inserted; 3216 } 3217 3218 /// Insert a simple single-register formula for the given expression into the 3219 /// given use. 3220 void 3221 LSRInstance::InsertSupplementalFormula(const SCEV *S, 3222 LSRUse &LU, size_t LUIdx) { 3223 Formula F; 3224 F.BaseRegs.push_back(S); 3225 F.HasBaseReg = true; 3226 bool Inserted = InsertFormula(LU, LUIdx, F); 3227 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted; 3228 } 3229 3230 /// Note which registers are used by the given formula, updating RegUses. 3231 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) { 3232 if (F.ScaledReg) 3233 RegUses.countRegister(F.ScaledReg, LUIdx); 3234 for (const SCEV *BaseReg : F.BaseRegs) 3235 RegUses.countRegister(BaseReg, LUIdx); 3236 } 3237 3238 /// If the given formula has not yet been inserted, add it to the list, and 3239 /// return true. Return false otherwise. 3240 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) { 3241 // Do not insert formula that we will not be able to expand. 3242 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) && 3243 "Formula is illegal"); 3244 3245 if (!LU.InsertFormula(F, *L)) 3246 return false; 3247 3248 CountRegisters(F, LUIdx); 3249 return true; 3250 } 3251 3252 /// Check for other uses of loop-invariant values which we're tracking. These 3253 /// other uses will pin these values in registers, making them less profitable 3254 /// for elimination. 3255 /// TODO: This currently misses non-constant addrec step registers. 3256 /// TODO: Should this give more weight to users inside the loop? 3257 void 3258 LSRInstance::CollectLoopInvariantFixupsAndFormulae() { 3259 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end()); 3260 SmallPtrSet<const SCEV *, 32> Visited; 3261 3262 while (!Worklist.empty()) { 3263 const SCEV *S = Worklist.pop_back_val(); 3264 3265 // Don't process the same SCEV twice 3266 if (!Visited.insert(S).second) 3267 continue; 3268 3269 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) 3270 Worklist.append(N->op_begin(), N->op_end()); 3271 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) 3272 Worklist.push_back(C->getOperand()); 3273 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { 3274 Worklist.push_back(D->getLHS()); 3275 Worklist.push_back(D->getRHS()); 3276 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) { 3277 const Value *V = US->getValue(); 3278 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 3279 // Look for instructions defined outside the loop. 3280 if (L->contains(Inst)) continue; 3281 } else if (isa<UndefValue>(V)) 3282 // Undef doesn't have a live range, so it doesn't matter. 3283 continue; 3284 for (const Use &U : V->uses()) { 3285 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser()); 3286 // Ignore non-instructions. 3287 if (!UserInst) 3288 continue; 3289 // Ignore instructions in other functions (as can happen with 3290 // Constants). 3291 if (UserInst->getParent()->getParent() != L->getHeader()->getParent()) 3292 continue; 3293 // Ignore instructions not dominated by the loop. 3294 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ? 3295 UserInst->getParent() : 3296 cast<PHINode>(UserInst)->getIncomingBlock( 3297 PHINode::getIncomingValueNumForOperand(U.getOperandNo())); 3298 if (!DT.dominates(L->getHeader(), UseBB)) 3299 continue; 3300 // Don't bother if the instruction is in a BB which ends in an EHPad. 3301 if (UseBB->getTerminator()->isEHPad()) 3302 continue; 3303 // Don't bother rewriting PHIs in catchswitch blocks. 3304 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator())) 3305 continue; 3306 // Ignore uses which are part of other SCEV expressions, to avoid 3307 // analyzing them multiple times. 3308 if (SE.isSCEVable(UserInst->getType())) { 3309 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst)); 3310 // If the user is a no-op, look through to its uses. 3311 if (!isa<SCEVUnknown>(UserS)) 3312 continue; 3313 if (UserS == US) { 3314 Worklist.push_back( 3315 SE.getUnknown(const_cast<Instruction *>(UserInst))); 3316 continue; 3317 } 3318 } 3319 // Ignore icmp instructions which are already being analyzed. 3320 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) { 3321 unsigned OtherIdx = !U.getOperandNo(); 3322 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx)); 3323 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L)) 3324 continue; 3325 } 3326 3327 std::pair<size_t, int64_t> P = getUse( 3328 S, LSRUse::Basic, MemAccessTy()); 3329 size_t LUIdx = P.first; 3330 int64_t Offset = P.second; 3331 LSRUse &LU = Uses[LUIdx]; 3332 LSRFixup &LF = LU.getNewFixup(); 3333 LF.UserInst = const_cast<Instruction *>(UserInst); 3334 LF.OperandValToReplace = U; 3335 LF.Offset = Offset; 3336 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3337 if (!LU.WidestFixupType || 3338 SE.getTypeSizeInBits(LU.WidestFixupType) < 3339 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3340 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3341 InsertSupplementalFormula(US, LU, LUIdx); 3342 CountRegisters(LU.Formulae.back(), Uses.size() - 1); 3343 break; 3344 } 3345 } 3346 } 3347 } 3348 3349 /// Split S into subexpressions which can be pulled out into separate 3350 /// registers. If C is non-null, multiply each subexpression by C. 3351 /// 3352 /// Return remainder expression after factoring the subexpressions captured by 3353 /// Ops. If Ops is complete, return NULL. 3354 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C, 3355 SmallVectorImpl<const SCEV *> &Ops, 3356 const Loop *L, 3357 ScalarEvolution &SE, 3358 unsigned Depth = 0) { 3359 // Arbitrarily cap recursion to protect compile time. 3360 if (Depth >= 3) 3361 return S; 3362 3363 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3364 // Break out add operands. 3365 for (const SCEV *S : Add->operands()) { 3366 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1); 3367 if (Remainder) 3368 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3369 } 3370 return nullptr; 3371 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 3372 // Split a non-zero base out of an addrec. 3373 if (AR->getStart()->isZero() || !AR->isAffine()) 3374 return S; 3375 3376 const SCEV *Remainder = CollectSubexprs(AR->getStart(), 3377 C, Ops, L, SE, Depth+1); 3378 // Split the non-zero AddRec unless it is part of a nested recurrence that 3379 // does not pertain to this loop. 3380 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) { 3381 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3382 Remainder = nullptr; 3383 } 3384 if (Remainder != AR->getStart()) { 3385 if (!Remainder) 3386 Remainder = SE.getConstant(AR->getType(), 0); 3387 return SE.getAddRecExpr(Remainder, 3388 AR->getStepRecurrence(SE), 3389 AR->getLoop(), 3390 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 3391 SCEV::FlagAnyWrap); 3392 } 3393 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3394 // Break (C * (a + b + c)) into C*a + C*b + C*c. 3395 if (Mul->getNumOperands() != 2) 3396 return S; 3397 if (const SCEVConstant *Op0 = 3398 dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3399 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0; 3400 const SCEV *Remainder = 3401 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1); 3402 if (Remainder) 3403 Ops.push_back(SE.getMulExpr(C, Remainder)); 3404 return nullptr; 3405 } 3406 } 3407 return S; 3408 } 3409 3410 /// \brief Helper function for LSRInstance::GenerateReassociations. 3411 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 3412 const Formula &Base, 3413 unsigned Depth, size_t Idx, 3414 bool IsScaledReg) { 3415 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3416 SmallVector<const SCEV *, 8> AddOps; 3417 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE); 3418 if (Remainder) 3419 AddOps.push_back(Remainder); 3420 3421 if (AddOps.size() == 1) 3422 return; 3423 3424 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(), 3425 JE = AddOps.end(); 3426 J != JE; ++J) { 3427 3428 // Loop-variant "unknown" values are uninteresting; we won't be able to 3429 // do anything meaningful with them. 3430 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L)) 3431 continue; 3432 3433 // Don't pull a constant into a register if the constant could be folded 3434 // into an immediate field. 3435 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3436 LU.AccessTy, *J, Base.getNumRegs() > 1)) 3437 continue; 3438 3439 // Collect all operands except *J. 3440 SmallVector<const SCEV *, 8> InnerAddOps( 3441 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J); 3442 InnerAddOps.append(std::next(J), 3443 ((const SmallVector<const SCEV *, 8> &)AddOps).end()); 3444 3445 // Don't leave just a constant behind in a register if the constant could 3446 // be folded into an immediate field. 3447 if (InnerAddOps.size() == 1 && 3448 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3449 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1)) 3450 continue; 3451 3452 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps); 3453 if (InnerSum->isZero()) 3454 continue; 3455 Formula F = Base; 3456 3457 // Add the remaining pieces of the add back into the new formula. 3458 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum); 3459 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 && 3460 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3461 InnerSumSC->getValue()->getZExtValue())) { 3462 F.UnfoldedOffset = 3463 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue(); 3464 if (IsScaledReg) 3465 F.ScaledReg = nullptr; 3466 else 3467 F.BaseRegs.erase(F.BaseRegs.begin() + Idx); 3468 } else if (IsScaledReg) 3469 F.ScaledReg = InnerSum; 3470 else 3471 F.BaseRegs[Idx] = InnerSum; 3472 3473 // Add J as its own register, or an unfolded immediate. 3474 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J); 3475 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 && 3476 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3477 SC->getValue()->getZExtValue())) 3478 F.UnfoldedOffset = 3479 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue(); 3480 else 3481 F.BaseRegs.push_back(*J); 3482 // We may have changed the number of register in base regs, adjust the 3483 // formula accordingly. 3484 F.canonicalize(*L); 3485 3486 if (InsertFormula(LU, LUIdx, F)) 3487 // If that formula hadn't been seen before, recurse to find more like 3488 // it. 3489 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1); 3490 } 3491 } 3492 3493 /// Split out subexpressions from adds and the bases of addrecs. 3494 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx, 3495 Formula Base, unsigned Depth) { 3496 assert(Base.isCanonical(*L) && "Input must be in the canonical form"); 3497 // Arbitrarily cap recursion to protect compile time. 3498 if (Depth >= 3) 3499 return; 3500 3501 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3502 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i); 3503 3504 if (Base.Scale == 1) 3505 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, 3506 /* Idx */ -1, /* IsScaledReg */ true); 3507 } 3508 3509 /// Generate a formula consisting of all of the loop-dominating registers added 3510 /// into a single register. 3511 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx, 3512 Formula Base) { 3513 // This method is only interesting on a plurality of registers. 3514 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1) 3515 return; 3516 3517 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before 3518 // processing the formula. 3519 Base.unscale(); 3520 Formula F = Base; 3521 F.BaseRegs.clear(); 3522 SmallVector<const SCEV *, 4> Ops; 3523 for (const SCEV *BaseReg : Base.BaseRegs) { 3524 if (SE.properlyDominates(BaseReg, L->getHeader()) && 3525 !SE.hasComputableLoopEvolution(BaseReg, L)) 3526 Ops.push_back(BaseReg); 3527 else 3528 F.BaseRegs.push_back(BaseReg); 3529 } 3530 if (Ops.size() > 1) { 3531 const SCEV *Sum = SE.getAddExpr(Ops); 3532 // TODO: If Sum is zero, it probably means ScalarEvolution missed an 3533 // opportunity to fold something. For now, just ignore such cases 3534 // rather than proceed with zero in a register. 3535 if (!Sum->isZero()) { 3536 F.BaseRegs.push_back(Sum); 3537 F.canonicalize(*L); 3538 (void)InsertFormula(LU, LUIdx, F); 3539 } 3540 } 3541 } 3542 3543 /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets. 3544 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 3545 const Formula &Base, size_t Idx, 3546 bool IsScaledReg) { 3547 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3548 GlobalValue *GV = ExtractSymbol(G, SE); 3549 if (G->isZero() || !GV) 3550 return; 3551 Formula F = Base; 3552 F.BaseGV = GV; 3553 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3554 return; 3555 if (IsScaledReg) 3556 F.ScaledReg = G; 3557 else 3558 F.BaseRegs[Idx] = G; 3559 (void)InsertFormula(LU, LUIdx, F); 3560 } 3561 3562 /// Generate reuse formulae using symbolic offsets. 3563 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, 3564 Formula Base) { 3565 // We can't add a symbolic offset if the address already contains one. 3566 if (Base.BaseGV) return; 3567 3568 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3569 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i); 3570 if (Base.Scale == 1) 3571 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1, 3572 /* IsScaledReg */ true); 3573 } 3574 3575 /// \brief Helper function for LSRInstance::GenerateConstantOffsets. 3576 void LSRInstance::GenerateConstantOffsetsImpl( 3577 LSRUse &LU, unsigned LUIdx, const Formula &Base, 3578 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) { 3579 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3580 for (int64_t Offset : Worklist) { 3581 Formula F = Base; 3582 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset; 3583 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind, 3584 LU.AccessTy, F)) { 3585 // Add the offset to the base register. 3586 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G); 3587 // If it cancelled out, drop the base register, otherwise update it. 3588 if (NewG->isZero()) { 3589 if (IsScaledReg) { 3590 F.Scale = 0; 3591 F.ScaledReg = nullptr; 3592 } else 3593 F.deleteBaseReg(F.BaseRegs[Idx]); 3594 F.canonicalize(*L); 3595 } else if (IsScaledReg) 3596 F.ScaledReg = NewG; 3597 else 3598 F.BaseRegs[Idx] = NewG; 3599 3600 (void)InsertFormula(LU, LUIdx, F); 3601 } 3602 } 3603 3604 int64_t Imm = ExtractImmediate(G, SE); 3605 if (G->isZero() || Imm == 0) 3606 return; 3607 Formula F = Base; 3608 F.BaseOffset = (uint64_t)F.BaseOffset + Imm; 3609 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3610 return; 3611 if (IsScaledReg) 3612 F.ScaledReg = G; 3613 else 3614 F.BaseRegs[Idx] = G; 3615 (void)InsertFormula(LU, LUIdx, F); 3616 } 3617 3618 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets. 3619 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, 3620 Formula Base) { 3621 // TODO: For now, just add the min and max offset, because it usually isn't 3622 // worthwhile looking at everything inbetween. 3623 SmallVector<int64_t, 2> Worklist; 3624 Worklist.push_back(LU.MinOffset); 3625 if (LU.MaxOffset != LU.MinOffset) 3626 Worklist.push_back(LU.MaxOffset); 3627 3628 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3629 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i); 3630 if (Base.Scale == 1) 3631 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1, 3632 /* IsScaledReg */ true); 3633 } 3634 3635 /// For ICmpZero, check to see if we can scale up the comparison. For example, x 3636 /// == y -> x*c == y*c. 3637 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, 3638 Formula Base) { 3639 if (LU.Kind != LSRUse::ICmpZero) return; 3640 3641 // Determine the integer type for the base formula. 3642 Type *IntTy = Base.getType(); 3643 if (!IntTy) return; 3644 if (SE.getTypeSizeInBits(IntTy) > 64) return; 3645 3646 // Don't do this if there is more than one offset. 3647 if (LU.MinOffset != LU.MaxOffset) return; 3648 3649 assert(!Base.BaseGV && "ICmpZero use is not legal!"); 3650 3651 // Check each interesting stride. 3652 for (int64_t Factor : Factors) { 3653 // Check that the multiplication doesn't overflow. 3654 if (Base.BaseOffset == INT64_MIN && Factor == -1) 3655 continue; 3656 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor; 3657 if (NewBaseOffset / Factor != Base.BaseOffset) 3658 continue; 3659 // If the offset will be truncated at this use, check that it is in bounds. 3660 if (!IntTy->isPointerTy() && 3661 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset)) 3662 continue; 3663 3664 // Check that multiplying with the use offset doesn't overflow. 3665 int64_t Offset = LU.MinOffset; 3666 if (Offset == INT64_MIN && Factor == -1) 3667 continue; 3668 Offset = (uint64_t)Offset * Factor; 3669 if (Offset / Factor != LU.MinOffset) 3670 continue; 3671 // If the offset will be truncated at this use, check that it is in bounds. 3672 if (!IntTy->isPointerTy() && 3673 !ConstantInt::isValueValidForType(IntTy, Offset)) 3674 continue; 3675 3676 Formula F = Base; 3677 F.BaseOffset = NewBaseOffset; 3678 3679 // Check that this scale is legal. 3680 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F)) 3681 continue; 3682 3683 // Compensate for the use having MinOffset built into it. 3684 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset; 3685 3686 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 3687 3688 // Check that multiplying with each base register doesn't overflow. 3689 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) { 3690 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS); 3691 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i]) 3692 goto next; 3693 } 3694 3695 // Check that multiplying with the scaled register doesn't overflow. 3696 if (F.ScaledReg) { 3697 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS); 3698 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg) 3699 continue; 3700 } 3701 3702 // Check that multiplying with the unfolded offset doesn't overflow. 3703 if (F.UnfoldedOffset != 0) { 3704 if (F.UnfoldedOffset == INT64_MIN && Factor == -1) 3705 continue; 3706 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor; 3707 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset) 3708 continue; 3709 // If the offset will be truncated, check that it is in bounds. 3710 if (!IntTy->isPointerTy() && 3711 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset)) 3712 continue; 3713 } 3714 3715 // If we make it here and it's legal, add it. 3716 (void)InsertFormula(LU, LUIdx, F); 3717 next:; 3718 } 3719 } 3720 3721 /// Generate stride factor reuse formulae by making use of scaled-offset address 3722 /// modes, for example. 3723 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) { 3724 // Determine the integer type for the base formula. 3725 Type *IntTy = Base.getType(); 3726 if (!IntTy) return; 3727 3728 // If this Formula already has a scaled register, we can't add another one. 3729 // Try to unscale the formula to generate a better scale. 3730 if (Base.Scale != 0 && !Base.unscale()) 3731 return; 3732 3733 assert(Base.Scale == 0 && "unscale did not did its job!"); 3734 3735 // Check each interesting stride. 3736 for (int64_t Factor : Factors) { 3737 Base.Scale = Factor; 3738 Base.HasBaseReg = Base.BaseRegs.size() > 1; 3739 // Check whether this scale is going to be legal. 3740 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 3741 Base)) { 3742 // As a special-case, handle special out-of-loop Basic users specially. 3743 // TODO: Reconsider this special case. 3744 if (LU.Kind == LSRUse::Basic && 3745 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special, 3746 LU.AccessTy, Base) && 3747 LU.AllFixupsOutsideLoop) 3748 LU.Kind = LSRUse::Special; 3749 else 3750 continue; 3751 } 3752 // For an ICmpZero, negating a solitary base register won't lead to 3753 // new solutions. 3754 if (LU.Kind == LSRUse::ICmpZero && 3755 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV) 3756 continue; 3757 // For each addrec base reg, if its loop is current loop, apply the scale. 3758 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) { 3759 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]); 3760 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) { 3761 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 3762 if (FactorS->isZero()) 3763 continue; 3764 // Divide out the factor, ignoring high bits, since we'll be 3765 // scaling the value back up in the end. 3766 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) { 3767 // TODO: This could be optimized to avoid all the copying. 3768 Formula F = Base; 3769 F.ScaledReg = Quotient; 3770 F.deleteBaseReg(F.BaseRegs[i]); 3771 // The canonical representation of 1*reg is reg, which is already in 3772 // Base. In that case, do not try to insert the formula, it will be 3773 // rejected anyway. 3774 if (F.Scale == 1 && (F.BaseRegs.empty() || 3775 (AR->getLoop() != L && LU.AllFixupsOutsideLoop))) 3776 continue; 3777 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate 3778 // non canonical Formula with ScaledReg's loop not being L. 3779 if (F.Scale == 1 && LU.AllFixupsOutsideLoop) 3780 F.canonicalize(*L); 3781 (void)InsertFormula(LU, LUIdx, F); 3782 } 3783 } 3784 } 3785 } 3786 } 3787 3788 /// Generate reuse formulae from different IV types. 3789 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) { 3790 // Don't bother truncating symbolic values. 3791 if (Base.BaseGV) return; 3792 3793 // Determine the integer type for the base formula. 3794 Type *DstTy = Base.getType(); 3795 if (!DstTy) return; 3796 DstTy = SE.getEffectiveSCEVType(DstTy); 3797 3798 for (Type *SrcTy : Types) { 3799 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) { 3800 Formula F = Base; 3801 3802 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy); 3803 for (const SCEV *&BaseReg : F.BaseRegs) 3804 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy); 3805 3806 // TODO: This assumes we've done basic processing on all uses and 3807 // have an idea what the register usage is. 3808 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses)) 3809 continue; 3810 3811 F.canonicalize(*L); 3812 (void)InsertFormula(LU, LUIdx, F); 3813 } 3814 } 3815 } 3816 3817 namespace { 3818 3819 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer 3820 /// modifications so that the search phase doesn't have to worry about the data 3821 /// structures moving underneath it. 3822 struct WorkItem { 3823 size_t LUIdx; 3824 int64_t Imm; 3825 const SCEV *OrigReg; 3826 3827 WorkItem(size_t LI, int64_t I, const SCEV *R) 3828 : LUIdx(LI), Imm(I), OrigReg(R) {} 3829 3830 void print(raw_ostream &OS) const; 3831 void dump() const; 3832 }; 3833 3834 } // end anonymous namespace 3835 3836 void WorkItem::print(raw_ostream &OS) const { 3837 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx 3838 << " , add offset " << Imm; 3839 } 3840 3841 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3842 LLVM_DUMP_METHOD void WorkItem::dump() const { 3843 print(errs()); errs() << '\n'; 3844 } 3845 #endif 3846 3847 /// Look for registers which are a constant distance apart and try to form reuse 3848 /// opportunities between them. 3849 void LSRInstance::GenerateCrossUseConstantOffsets() { 3850 // Group the registers by their value without any added constant offset. 3851 typedef std::map<int64_t, const SCEV *> ImmMapTy; 3852 DenseMap<const SCEV *, ImmMapTy> Map; 3853 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap; 3854 SmallVector<const SCEV *, 8> Sequence; 3855 for (const SCEV *Use : RegUses) { 3856 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify. 3857 int64_t Imm = ExtractImmediate(Reg, SE); 3858 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy())); 3859 if (Pair.second) 3860 Sequence.push_back(Reg); 3861 Pair.first->second.insert(std::make_pair(Imm, Use)); 3862 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use); 3863 } 3864 3865 // Now examine each set of registers with the same base value. Build up 3866 // a list of work to do and do the work in a separate step so that we're 3867 // not adding formulae and register counts while we're searching. 3868 SmallVector<WorkItem, 32> WorkItems; 3869 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems; 3870 for (const SCEV *Reg : Sequence) { 3871 const ImmMapTy &Imms = Map.find(Reg)->second; 3872 3873 // It's not worthwhile looking for reuse if there's only one offset. 3874 if (Imms.size() == 1) 3875 continue; 3876 3877 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':'; 3878 for (const auto &Entry : Imms) 3879 dbgs() << ' ' << Entry.first; 3880 dbgs() << '\n'); 3881 3882 // Examine each offset. 3883 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end(); 3884 J != JE; ++J) { 3885 const SCEV *OrigReg = J->second; 3886 3887 int64_t JImm = J->first; 3888 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg); 3889 3890 if (!isa<SCEVConstant>(OrigReg) && 3891 UsedByIndicesMap[Reg].count() == 1) { 3892 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n'); 3893 continue; 3894 } 3895 3896 // Conservatively examine offsets between this orig reg a few selected 3897 // other orig regs. 3898 ImmMapTy::const_iterator OtherImms[] = { 3899 Imms.begin(), std::prev(Imms.end()), 3900 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) / 3901 2) 3902 }; 3903 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) { 3904 ImmMapTy::const_iterator M = OtherImms[i]; 3905 if (M == J || M == JE) continue; 3906 3907 // Compute the difference between the two. 3908 int64_t Imm = (uint64_t)JImm - M->first; 3909 for (unsigned LUIdx : UsedByIndices.set_bits()) 3910 // Make a memo of this use, offset, and register tuple. 3911 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second) 3912 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg)); 3913 } 3914 } 3915 } 3916 3917 Map.clear(); 3918 Sequence.clear(); 3919 UsedByIndicesMap.clear(); 3920 UniqueItems.clear(); 3921 3922 // Now iterate through the worklist and add new formulae. 3923 for (const WorkItem &WI : WorkItems) { 3924 size_t LUIdx = WI.LUIdx; 3925 LSRUse &LU = Uses[LUIdx]; 3926 int64_t Imm = WI.Imm; 3927 const SCEV *OrigReg = WI.OrigReg; 3928 3929 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType()); 3930 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm)); 3931 unsigned BitWidth = SE.getTypeSizeInBits(IntTy); 3932 3933 // TODO: Use a more targeted data structure. 3934 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) { 3935 Formula F = LU.Formulae[L]; 3936 // FIXME: The code for the scaled and unscaled registers looks 3937 // very similar but slightly different. Investigate if they 3938 // could be merged. That way, we would not have to unscale the 3939 // Formula. 3940 F.unscale(); 3941 // Use the immediate in the scaled register. 3942 if (F.ScaledReg == OrigReg) { 3943 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale; 3944 // Don't create 50 + reg(-50). 3945 if (F.referencesReg(SE.getSCEV( 3946 ConstantInt::get(IntTy, -(uint64_t)Offset)))) 3947 continue; 3948 Formula NewF = F; 3949 NewF.BaseOffset = Offset; 3950 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 3951 NewF)) 3952 continue; 3953 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg); 3954 3955 // If the new scale is a constant in a register, and adding the constant 3956 // value to the immediate would produce a value closer to zero than the 3957 // immediate itself, then the formula isn't worthwhile. 3958 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) 3959 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) && 3960 (C->getAPInt().abs() * APInt(BitWidth, F.Scale)) 3961 .ule(std::abs(NewF.BaseOffset))) 3962 continue; 3963 3964 // OK, looks good. 3965 NewF.canonicalize(*this->L); 3966 (void)InsertFormula(LU, LUIdx, NewF); 3967 } else { 3968 // Use the immediate in a base register. 3969 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) { 3970 const SCEV *BaseReg = F.BaseRegs[N]; 3971 if (BaseReg != OrigReg) 3972 continue; 3973 Formula NewF = F; 3974 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm; 3975 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, 3976 LU.Kind, LU.AccessTy, NewF)) { 3977 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm)) 3978 continue; 3979 NewF = F; 3980 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm; 3981 } 3982 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg); 3983 3984 // If the new formula has a constant in a register, and adding the 3985 // constant value to the immediate would produce a value closer to 3986 // zero than the immediate itself, then the formula isn't worthwhile. 3987 for (const SCEV *NewReg : NewF.BaseRegs) 3988 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) 3989 if ((C->getAPInt() + NewF.BaseOffset) 3990 .abs() 3991 .slt(std::abs(NewF.BaseOffset)) && 3992 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >= 3993 countTrailingZeros<uint64_t>(NewF.BaseOffset)) 3994 goto skip_formula; 3995 3996 // Ok, looks good. 3997 NewF.canonicalize(*this->L); 3998 (void)InsertFormula(LU, LUIdx, NewF); 3999 break; 4000 skip_formula:; 4001 } 4002 } 4003 } 4004 } 4005 } 4006 4007 /// Generate formulae for each use. 4008 void 4009 LSRInstance::GenerateAllReuseFormulae() { 4010 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan 4011 // queries are more precise. 4012 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4013 LSRUse &LU = Uses[LUIdx]; 4014 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4015 GenerateReassociations(LU, LUIdx, LU.Formulae[i]); 4016 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4017 GenerateCombinations(LU, LUIdx, LU.Formulae[i]); 4018 } 4019 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4020 LSRUse &LU = Uses[LUIdx]; 4021 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4022 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]); 4023 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4024 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]); 4025 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4026 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]); 4027 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4028 GenerateScales(LU, LUIdx, LU.Formulae[i]); 4029 } 4030 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4031 LSRUse &LU = Uses[LUIdx]; 4032 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4033 GenerateTruncates(LU, LUIdx, LU.Formulae[i]); 4034 } 4035 4036 GenerateCrossUseConstantOffsets(); 4037 4038 DEBUG(dbgs() << "\n" 4039 "After generating reuse formulae:\n"; 4040 print_uses(dbgs())); 4041 } 4042 4043 /// If there are multiple formulae with the same set of registers used 4044 /// by other uses, pick the best one and delete the others. 4045 void LSRInstance::FilterOutUndesirableDedicatedRegisters() { 4046 DenseSet<const SCEV *> VisitedRegs; 4047 SmallPtrSet<const SCEV *, 16> Regs; 4048 SmallPtrSet<const SCEV *, 16> LoserRegs; 4049 #ifndef NDEBUG 4050 bool ChangedFormulae = false; 4051 #endif 4052 4053 // Collect the best formula for each unique set of shared registers. This 4054 // is reset for each use. 4055 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo> 4056 BestFormulaeTy; 4057 BestFormulaeTy BestFormulae; 4058 4059 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4060 LSRUse &LU = Uses[LUIdx]; 4061 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n'); 4062 4063 bool Any = false; 4064 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); 4065 FIdx != NumForms; ++FIdx) { 4066 Formula &F = LU.Formulae[FIdx]; 4067 4068 // Some formulas are instant losers. For example, they may depend on 4069 // nonexistent AddRecs from other loops. These need to be filtered 4070 // immediately, otherwise heuristics could choose them over others leading 4071 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here 4072 // avoids the need to recompute this information across formulae using the 4073 // same bad AddRec. Passing LoserRegs is also essential unless we remove 4074 // the corresponding bad register from the Regs set. 4075 Cost CostF; 4076 Regs.clear(); 4077 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs); 4078 if (CostF.isLoser()) { 4079 // During initial formula generation, undesirable formulae are generated 4080 // by uses within other loops that have some non-trivial address mode or 4081 // use the postinc form of the IV. LSR needs to provide these formulae 4082 // as the basis of rediscovering the desired formula that uses an AddRec 4083 // corresponding to the existing phi. Once all formulae have been 4084 // generated, these initial losers may be pruned. 4085 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs()); 4086 dbgs() << "\n"); 4087 } 4088 else { 4089 SmallVector<const SCEV *, 4> Key; 4090 for (const SCEV *Reg : F.BaseRegs) { 4091 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx)) 4092 Key.push_back(Reg); 4093 } 4094 if (F.ScaledReg && 4095 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx)) 4096 Key.push_back(F.ScaledReg); 4097 // Unstable sort by host order ok, because this is only used for 4098 // uniquifying. 4099 std::sort(Key.begin(), Key.end()); 4100 4101 std::pair<BestFormulaeTy::const_iterator, bool> P = 4102 BestFormulae.insert(std::make_pair(Key, FIdx)); 4103 if (P.second) 4104 continue; 4105 4106 Formula &Best = LU.Formulae[P.first->second]; 4107 4108 Cost CostBest; 4109 Regs.clear(); 4110 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU); 4111 if (CostF.isLess(CostBest, TTI)) 4112 std::swap(F, Best); 4113 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4114 dbgs() << "\n" 4115 " in favor of formula "; Best.print(dbgs()); 4116 dbgs() << '\n'); 4117 } 4118 #ifndef NDEBUG 4119 ChangedFormulae = true; 4120 #endif 4121 LU.DeleteFormula(F); 4122 --FIdx; 4123 --NumForms; 4124 Any = true; 4125 } 4126 4127 // Now that we've filtered out some formulae, recompute the Regs set. 4128 if (Any) 4129 LU.RecomputeRegs(LUIdx, RegUses); 4130 4131 // Reset this to prepare for the next use. 4132 BestFormulae.clear(); 4133 } 4134 4135 DEBUG(if (ChangedFormulae) { 4136 dbgs() << "\n" 4137 "After filtering out undesirable candidates:\n"; 4138 print_uses(dbgs()); 4139 }); 4140 } 4141 4142 // This is a rough guess that seems to work fairly well. 4143 static const size_t ComplexityLimit = UINT16_MAX; 4144 4145 /// Estimate the worst-case number of solutions the solver might have to 4146 /// consider. It almost never considers this many solutions because it prune the 4147 /// search space, but the pruning isn't always sufficient. 4148 size_t LSRInstance::EstimateSearchSpaceComplexity() const { 4149 size_t Power = 1; 4150 for (const LSRUse &LU : Uses) { 4151 size_t FSize = LU.Formulae.size(); 4152 if (FSize >= ComplexityLimit) { 4153 Power = ComplexityLimit; 4154 break; 4155 } 4156 Power *= FSize; 4157 if (Power >= ComplexityLimit) 4158 break; 4159 } 4160 return Power; 4161 } 4162 4163 /// When one formula uses a superset of the registers of another formula, it 4164 /// won't help reduce register pressure (though it may not necessarily hurt 4165 /// register pressure); remove it to simplify the system. 4166 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() { 4167 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4168 DEBUG(dbgs() << "The search space is too complex.\n"); 4169 4170 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae " 4171 "which use a superset of registers used by other " 4172 "formulae.\n"); 4173 4174 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4175 LSRUse &LU = Uses[LUIdx]; 4176 bool Any = false; 4177 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4178 Formula &F = LU.Formulae[i]; 4179 // Look for a formula with a constant or GV in a register. If the use 4180 // also has a formula with that same value in an immediate field, 4181 // delete the one that uses a register. 4182 for (SmallVectorImpl<const SCEV *>::const_iterator 4183 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) { 4184 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) { 4185 Formula NewF = F; 4186 NewF.BaseOffset += C->getValue()->getSExtValue(); 4187 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4188 (I - F.BaseRegs.begin())); 4189 if (LU.HasFormulaWithSameRegs(NewF)) { 4190 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4191 LU.DeleteFormula(F); 4192 --i; 4193 --e; 4194 Any = true; 4195 break; 4196 } 4197 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) { 4198 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) 4199 if (!F.BaseGV) { 4200 Formula NewF = F; 4201 NewF.BaseGV = GV; 4202 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4203 (I - F.BaseRegs.begin())); 4204 if (LU.HasFormulaWithSameRegs(NewF)) { 4205 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4206 dbgs() << '\n'); 4207 LU.DeleteFormula(F); 4208 --i; 4209 --e; 4210 Any = true; 4211 break; 4212 } 4213 } 4214 } 4215 } 4216 } 4217 if (Any) 4218 LU.RecomputeRegs(LUIdx, RegUses); 4219 } 4220 4221 DEBUG(dbgs() << "After pre-selection:\n"; 4222 print_uses(dbgs())); 4223 } 4224 } 4225 4226 /// When there are many registers for expressions like A, A+1, A+2, etc., 4227 /// allocate a single register for them. 4228 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() { 4229 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4230 return; 4231 4232 DEBUG(dbgs() << "The search space is too complex.\n" 4233 "Narrowing the search space by assuming that uses separated " 4234 "by a constant offset will use the same registers.\n"); 4235 4236 // This is especially useful for unrolled loops. 4237 4238 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4239 LSRUse &LU = Uses[LUIdx]; 4240 for (const Formula &F : LU.Formulae) { 4241 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1)) 4242 continue; 4243 4244 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU); 4245 if (!LUThatHas) 4246 continue; 4247 4248 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false, 4249 LU.Kind, LU.AccessTy)) 4250 continue; 4251 4252 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n'); 4253 4254 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop; 4255 4256 // Transfer the fixups of LU to LUThatHas. 4257 for (LSRFixup &Fixup : LU.Fixups) { 4258 Fixup.Offset += F.BaseOffset; 4259 LUThatHas->pushFixup(Fixup); 4260 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n'); 4261 } 4262 4263 // Delete formulae from the new use which are no longer legal. 4264 bool Any = false; 4265 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) { 4266 Formula &F = LUThatHas->Formulae[i]; 4267 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset, 4268 LUThatHas->Kind, LUThatHas->AccessTy, F)) { 4269 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4270 dbgs() << '\n'); 4271 LUThatHas->DeleteFormula(F); 4272 --i; 4273 --e; 4274 Any = true; 4275 } 4276 } 4277 4278 if (Any) 4279 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses); 4280 4281 // Delete the old use. 4282 DeleteUse(LU, LUIdx); 4283 --LUIdx; 4284 --NumUses; 4285 break; 4286 } 4287 } 4288 4289 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4290 } 4291 4292 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that 4293 /// we've done more filtering, as it may be able to find more formulae to 4294 /// eliminate. 4295 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){ 4296 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4297 DEBUG(dbgs() << "The search space is too complex.\n"); 4298 4299 DEBUG(dbgs() << "Narrowing the search space by re-filtering out " 4300 "undesirable dedicated registers.\n"); 4301 4302 FilterOutUndesirableDedicatedRegisters(); 4303 4304 DEBUG(dbgs() << "After pre-selection:\n"; 4305 print_uses(dbgs())); 4306 } 4307 } 4308 4309 /// The function delete formulas with high registers number expectation. 4310 /// Assuming we don't know the value of each formula (already delete 4311 /// all inefficient), generate probability of not selecting for each 4312 /// register. 4313 /// For example, 4314 /// Use1: 4315 /// reg(a) + reg({0,+,1}) 4316 /// reg(a) + reg({-1,+,1}) + 1 4317 /// reg({a,+,1}) 4318 /// Use2: 4319 /// reg(b) + reg({0,+,1}) 4320 /// reg(b) + reg({-1,+,1}) + 1 4321 /// reg({b,+,1}) 4322 /// Use3: 4323 /// reg(c) + reg(b) + reg({0,+,1}) 4324 /// reg(c) + reg({b,+,1}) 4325 /// 4326 /// Probability of not selecting 4327 /// Use1 Use2 Use3 4328 /// reg(a) (1/3) * 1 * 1 4329 /// reg(b) 1 * (1/3) * (1/2) 4330 /// reg({0,+,1}) (2/3) * (2/3) * (1/2) 4331 /// reg({-1,+,1}) (2/3) * (2/3) * 1 4332 /// reg({a,+,1}) (2/3) * 1 * 1 4333 /// reg({b,+,1}) 1 * (2/3) * (2/3) 4334 /// reg(c) 1 * 1 * 0 4335 /// 4336 /// Now count registers number mathematical expectation for each formula: 4337 /// Note that for each use we exclude probability if not selecting for the use. 4338 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding 4339 /// probabilty 1/3 of not selecting for Use1). 4340 /// Use1: 4341 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted 4342 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted 4343 /// reg({a,+,1}) 1 4344 /// Use2: 4345 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted 4346 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted 4347 /// reg({b,+,1}) 2/3 4348 /// Use3: 4349 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted 4350 /// reg(c) + reg({b,+,1}) 1 + 2/3 4351 4352 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() { 4353 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4354 return; 4355 // Ok, we have too many of formulae on our hands to conveniently handle. 4356 // Use a rough heuristic to thin out the list. 4357 4358 // Set of Regs wich will be 100% used in final solution. 4359 // Used in each formula of a solution (in example above this is reg(c)). 4360 // We can skip them in calculations. 4361 SmallPtrSet<const SCEV *, 4> UniqRegs; 4362 DEBUG(dbgs() << "The search space is too complex.\n"); 4363 4364 // Map each register to probability of not selecting 4365 DenseMap <const SCEV *, float> RegNumMap; 4366 for (const SCEV *Reg : RegUses) { 4367 if (UniqRegs.count(Reg)) 4368 continue; 4369 float PNotSel = 1; 4370 for (const LSRUse &LU : Uses) { 4371 if (!LU.Regs.count(Reg)) 4372 continue; 4373 float P = LU.getNotSelectedProbability(Reg); 4374 if (P != 0.0) 4375 PNotSel *= P; 4376 else 4377 UniqRegs.insert(Reg); 4378 } 4379 RegNumMap.insert(std::make_pair(Reg, PNotSel)); 4380 } 4381 4382 DEBUG(dbgs() << "Narrowing the search space by deleting costly formulas\n"); 4383 4384 // Delete formulas where registers number expectation is high. 4385 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4386 LSRUse &LU = Uses[LUIdx]; 4387 // If nothing to delete - continue. 4388 if (LU.Formulae.size() < 2) 4389 continue; 4390 // This is temporary solution to test performance. Float should be 4391 // replaced with round independent type (based on integers) to avoid 4392 // different results for different target builds. 4393 float FMinRegNum = LU.Formulae[0].getNumRegs(); 4394 float FMinARegNum = LU.Formulae[0].getNumRegs(); 4395 size_t MinIdx = 0; 4396 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4397 Formula &F = LU.Formulae[i]; 4398 float FRegNum = 0; 4399 float FARegNum = 0; 4400 for (const SCEV *BaseReg : F.BaseRegs) { 4401 if (UniqRegs.count(BaseReg)) 4402 continue; 4403 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4404 if (isa<SCEVAddRecExpr>(BaseReg)) 4405 FARegNum += 4406 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4407 } 4408 if (const SCEV *ScaledReg = F.ScaledReg) { 4409 if (!UniqRegs.count(ScaledReg)) { 4410 FRegNum += 4411 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4412 if (isa<SCEVAddRecExpr>(ScaledReg)) 4413 FARegNum += 4414 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4415 } 4416 } 4417 if (FMinRegNum > FRegNum || 4418 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) { 4419 FMinRegNum = FRegNum; 4420 FMinARegNum = FARegNum; 4421 MinIdx = i; 4422 } 4423 } 4424 DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs()); 4425 dbgs() << " with min reg num " << FMinRegNum << '\n'); 4426 if (MinIdx != 0) 4427 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]); 4428 while (LU.Formulae.size() != 1) { 4429 DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs()); 4430 dbgs() << '\n'); 4431 LU.Formulae.pop_back(); 4432 } 4433 LU.RecomputeRegs(LUIdx, RegUses); 4434 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula"); 4435 Formula &F = LU.Formulae[0]; 4436 DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n'); 4437 // When we choose the formula, the regs become unique. 4438 UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 4439 if (F.ScaledReg) 4440 UniqRegs.insert(F.ScaledReg); 4441 } 4442 DEBUG(dbgs() << "After pre-selection:\n"; 4443 print_uses(dbgs())); 4444 } 4445 4446 4447 /// Pick a register which seems likely to be profitable, and then in any use 4448 /// which has any reference to that register, delete all formulae which do not 4449 /// reference that register. 4450 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() { 4451 // With all other options exhausted, loop until the system is simple 4452 // enough to handle. 4453 SmallPtrSet<const SCEV *, 4> Taken; 4454 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4455 // Ok, we have too many of formulae on our hands to conveniently handle. 4456 // Use a rough heuristic to thin out the list. 4457 DEBUG(dbgs() << "The search space is too complex.\n"); 4458 4459 // Pick the register which is used by the most LSRUses, which is likely 4460 // to be a good reuse register candidate. 4461 const SCEV *Best = nullptr; 4462 unsigned BestNum = 0; 4463 for (const SCEV *Reg : RegUses) { 4464 if (Taken.count(Reg)) 4465 continue; 4466 if (!Best) { 4467 Best = Reg; 4468 BestNum = RegUses.getUsedByIndices(Reg).count(); 4469 } else { 4470 unsigned Count = RegUses.getUsedByIndices(Reg).count(); 4471 if (Count > BestNum) { 4472 Best = Reg; 4473 BestNum = Count; 4474 } 4475 } 4476 } 4477 4478 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best 4479 << " will yield profitable reuse.\n"); 4480 Taken.insert(Best); 4481 4482 // In any use with formulae which references this register, delete formulae 4483 // which don't reference it. 4484 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4485 LSRUse &LU = Uses[LUIdx]; 4486 if (!LU.Regs.count(Best)) continue; 4487 4488 bool Any = false; 4489 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4490 Formula &F = LU.Formulae[i]; 4491 if (!F.referencesReg(Best)) { 4492 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4493 LU.DeleteFormula(F); 4494 --e; 4495 --i; 4496 Any = true; 4497 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?"); 4498 continue; 4499 } 4500 } 4501 4502 if (Any) 4503 LU.RecomputeRegs(LUIdx, RegUses); 4504 } 4505 4506 DEBUG(dbgs() << "After pre-selection:\n"; 4507 print_uses(dbgs())); 4508 } 4509 } 4510 4511 /// If there are an extraordinary number of formulae to choose from, use some 4512 /// rough heuristics to prune down the number of formulae. This keeps the main 4513 /// solver from taking an extraordinary amount of time in some worst-case 4514 /// scenarios. 4515 void LSRInstance::NarrowSearchSpaceUsingHeuristics() { 4516 NarrowSearchSpaceByDetectingSupersets(); 4517 NarrowSearchSpaceByCollapsingUnrolledCode(); 4518 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 4519 if (LSRExpNarrow) 4520 NarrowSearchSpaceByDeletingCostlyFormulas(); 4521 else 4522 NarrowSearchSpaceByPickingWinnerRegs(); 4523 } 4524 4525 /// This is the recursive solver. 4526 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 4527 Cost &SolutionCost, 4528 SmallVectorImpl<const Formula *> &Workspace, 4529 const Cost &CurCost, 4530 const SmallPtrSet<const SCEV *, 16> &CurRegs, 4531 DenseSet<const SCEV *> &VisitedRegs) const { 4532 // Some ideas: 4533 // - prune more: 4534 // - use more aggressive filtering 4535 // - sort the formula so that the most profitable solutions are found first 4536 // - sort the uses too 4537 // - search faster: 4538 // - don't compute a cost, and then compare. compare while computing a cost 4539 // and bail early. 4540 // - track register sets with SmallBitVector 4541 4542 const LSRUse &LU = Uses[Workspace.size()]; 4543 4544 // If this use references any register that's already a part of the 4545 // in-progress solution, consider it a requirement that a formula must 4546 // reference that register in order to be considered. This prunes out 4547 // unprofitable searching. 4548 SmallSetVector<const SCEV *, 4> ReqRegs; 4549 for (const SCEV *S : CurRegs) 4550 if (LU.Regs.count(S)) 4551 ReqRegs.insert(S); 4552 4553 SmallPtrSet<const SCEV *, 16> NewRegs; 4554 Cost NewCost; 4555 for (const Formula &F : LU.Formulae) { 4556 // Ignore formulae which may not be ideal in terms of register reuse of 4557 // ReqRegs. The formula should use all required registers before 4558 // introducing new ones. 4559 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size()); 4560 for (const SCEV *Reg : ReqRegs) { 4561 if ((F.ScaledReg && F.ScaledReg == Reg) || 4562 is_contained(F.BaseRegs, Reg)) { 4563 --NumReqRegsToFind; 4564 if (NumReqRegsToFind == 0) 4565 break; 4566 } 4567 } 4568 if (NumReqRegsToFind != 0) { 4569 // If none of the formulae satisfied the required registers, then we could 4570 // clear ReqRegs and try again. Currently, we simply give up in this case. 4571 continue; 4572 } 4573 4574 // Evaluate the cost of the current formula. If it's already worse than 4575 // the current best, prune the search at that point. 4576 NewCost = CurCost; 4577 NewRegs = CurRegs; 4578 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU); 4579 if (NewCost.isLess(SolutionCost, TTI)) { 4580 Workspace.push_back(&F); 4581 if (Workspace.size() != Uses.size()) { 4582 SolveRecurse(Solution, SolutionCost, Workspace, NewCost, 4583 NewRegs, VisitedRegs); 4584 if (F.getNumRegs() == 1 && Workspace.size() == 1) 4585 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]); 4586 } else { 4587 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs()); 4588 dbgs() << ".\n Regs:"; 4589 for (const SCEV *S : NewRegs) 4590 dbgs() << ' ' << *S; 4591 dbgs() << '\n'); 4592 4593 SolutionCost = NewCost; 4594 Solution = Workspace; 4595 } 4596 Workspace.pop_back(); 4597 } 4598 } 4599 } 4600 4601 /// Choose one formula from each use. Return the results in the given Solution 4602 /// vector. 4603 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const { 4604 SmallVector<const Formula *, 8> Workspace; 4605 Cost SolutionCost; 4606 SolutionCost.Lose(); 4607 Cost CurCost; 4608 SmallPtrSet<const SCEV *, 16> CurRegs; 4609 DenseSet<const SCEV *> VisitedRegs; 4610 Workspace.reserve(Uses.size()); 4611 4612 // SolveRecurse does all the work. 4613 SolveRecurse(Solution, SolutionCost, Workspace, CurCost, 4614 CurRegs, VisitedRegs); 4615 if (Solution.empty()) { 4616 DEBUG(dbgs() << "\nNo Satisfactory Solution\n"); 4617 return; 4618 } 4619 4620 // Ok, we've now made all our decisions. 4621 DEBUG(dbgs() << "\n" 4622 "The chosen solution requires "; SolutionCost.print(dbgs()); 4623 dbgs() << ":\n"; 4624 for (size_t i = 0, e = Uses.size(); i != e; ++i) { 4625 dbgs() << " "; 4626 Uses[i].print(dbgs()); 4627 dbgs() << "\n" 4628 " "; 4629 Solution[i]->print(dbgs()); 4630 dbgs() << '\n'; 4631 }); 4632 4633 assert(Solution.size() == Uses.size() && "Malformed solution!"); 4634 } 4635 4636 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as 4637 /// we can go while still being dominated by the input positions. This helps 4638 /// canonicalize the insert position, which encourages sharing. 4639 BasicBlock::iterator 4640 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP, 4641 const SmallVectorImpl<Instruction *> &Inputs) 4642 const { 4643 Instruction *Tentative = &*IP; 4644 while (true) { 4645 bool AllDominate = true; 4646 Instruction *BetterPos = nullptr; 4647 // Don't bother attempting to insert before a catchswitch, their basic block 4648 // cannot have other non-PHI instructions. 4649 if (isa<CatchSwitchInst>(Tentative)) 4650 return IP; 4651 4652 for (Instruction *Inst : Inputs) { 4653 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) { 4654 AllDominate = false; 4655 break; 4656 } 4657 // Attempt to find an insert position in the middle of the block, 4658 // instead of at the end, so that it can be used for other expansions. 4659 if (Tentative->getParent() == Inst->getParent() && 4660 (!BetterPos || !DT.dominates(Inst, BetterPos))) 4661 BetterPos = &*std::next(BasicBlock::iterator(Inst)); 4662 } 4663 if (!AllDominate) 4664 break; 4665 if (BetterPos) 4666 IP = BetterPos->getIterator(); 4667 else 4668 IP = Tentative->getIterator(); 4669 4670 const Loop *IPLoop = LI.getLoopFor(IP->getParent()); 4671 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0; 4672 4673 BasicBlock *IDom; 4674 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) { 4675 if (!Rung) return IP; 4676 Rung = Rung->getIDom(); 4677 if (!Rung) return IP; 4678 IDom = Rung->getBlock(); 4679 4680 // Don't climb into a loop though. 4681 const Loop *IDomLoop = LI.getLoopFor(IDom); 4682 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0; 4683 if (IDomDepth <= IPLoopDepth && 4684 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop)) 4685 break; 4686 } 4687 4688 Tentative = IDom->getTerminator(); 4689 } 4690 4691 return IP; 4692 } 4693 4694 /// Determine an input position which will be dominated by the operands and 4695 /// which will dominate the result. 4696 BasicBlock::iterator 4697 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP, 4698 const LSRFixup &LF, 4699 const LSRUse &LU, 4700 SCEVExpander &Rewriter) const { 4701 // Collect some instructions which must be dominated by the 4702 // expanding replacement. These must be dominated by any operands that 4703 // will be required in the expansion. 4704 SmallVector<Instruction *, 4> Inputs; 4705 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace)) 4706 Inputs.push_back(I); 4707 if (LU.Kind == LSRUse::ICmpZero) 4708 if (Instruction *I = 4709 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1))) 4710 Inputs.push_back(I); 4711 if (LF.PostIncLoops.count(L)) { 4712 if (LF.isUseFullyOutsideLoop(L)) 4713 Inputs.push_back(L->getLoopLatch()->getTerminator()); 4714 else 4715 Inputs.push_back(IVIncInsertPos); 4716 } 4717 // The expansion must also be dominated by the increment positions of any 4718 // loops it for which it is using post-inc mode. 4719 for (const Loop *PIL : LF.PostIncLoops) { 4720 if (PIL == L) continue; 4721 4722 // Be dominated by the loop exit. 4723 SmallVector<BasicBlock *, 4> ExitingBlocks; 4724 PIL->getExitingBlocks(ExitingBlocks); 4725 if (!ExitingBlocks.empty()) { 4726 BasicBlock *BB = ExitingBlocks[0]; 4727 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i) 4728 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]); 4729 Inputs.push_back(BB->getTerminator()); 4730 } 4731 } 4732 4733 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() 4734 && !isa<DbgInfoIntrinsic>(LowestIP) && 4735 "Insertion point must be a normal instruction"); 4736 4737 // Then, climb up the immediate dominator tree as far as we can go while 4738 // still being dominated by the input positions. 4739 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs); 4740 4741 // Don't insert instructions before PHI nodes. 4742 while (isa<PHINode>(IP)) ++IP; 4743 4744 // Ignore landingpad instructions. 4745 while (IP->isEHPad()) ++IP; 4746 4747 // Ignore debug intrinsics. 4748 while (isa<DbgInfoIntrinsic>(IP)) ++IP; 4749 4750 // Set IP below instructions recently inserted by SCEVExpander. This keeps the 4751 // IP consistent across expansions and allows the previously inserted 4752 // instructions to be reused by subsequent expansion. 4753 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP) 4754 ++IP; 4755 4756 return IP; 4757 } 4758 4759 /// Emit instructions for the leading candidate expression for this LSRUse (this 4760 /// is called "expanding"). 4761 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF, 4762 const Formula &F, BasicBlock::iterator IP, 4763 SCEVExpander &Rewriter, 4764 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 4765 if (LU.RigidFormula) 4766 return LF.OperandValToReplace; 4767 4768 // Determine an input position which will be dominated by the operands and 4769 // which will dominate the result. 4770 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter); 4771 Rewriter.setInsertPoint(&*IP); 4772 4773 // Inform the Rewriter if we have a post-increment use, so that it can 4774 // perform an advantageous expansion. 4775 Rewriter.setPostInc(LF.PostIncLoops); 4776 4777 // This is the type that the user actually needs. 4778 Type *OpTy = LF.OperandValToReplace->getType(); 4779 // This will be the type that we'll initially expand to. 4780 Type *Ty = F.getType(); 4781 if (!Ty) 4782 // No type known; just expand directly to the ultimate type. 4783 Ty = OpTy; 4784 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy)) 4785 // Expand directly to the ultimate type if it's the right size. 4786 Ty = OpTy; 4787 // This is the type to do integer arithmetic in. 4788 Type *IntTy = SE.getEffectiveSCEVType(Ty); 4789 4790 // Build up a list of operands to add together to form the full base. 4791 SmallVector<const SCEV *, 8> Ops; 4792 4793 // Expand the BaseRegs portion. 4794 for (const SCEV *Reg : F.BaseRegs) { 4795 assert(!Reg->isZero() && "Zero allocated in a base register!"); 4796 4797 // If we're expanding for a post-inc user, make the post-inc adjustment. 4798 Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE); 4799 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr))); 4800 } 4801 4802 // Expand the ScaledReg portion. 4803 Value *ICmpScaledV = nullptr; 4804 if (F.Scale != 0) { 4805 const SCEV *ScaledS = F.ScaledReg; 4806 4807 // If we're expanding for a post-inc user, make the post-inc adjustment. 4808 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops); 4809 ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE); 4810 4811 if (LU.Kind == LSRUse::ICmpZero) { 4812 // Expand ScaleReg as if it was part of the base regs. 4813 if (F.Scale == 1) 4814 Ops.push_back( 4815 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr))); 4816 else { 4817 // An interesting way of "folding" with an icmp is to use a negated 4818 // scale, which we'll implement by inserting it into the other operand 4819 // of the icmp. 4820 assert(F.Scale == -1 && 4821 "The only scale supported by ICmpZero uses is -1!"); 4822 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr); 4823 } 4824 } else { 4825 // Otherwise just expand the scaled register and an explicit scale, 4826 // which is expected to be matched as part of the address. 4827 4828 // Flush the operand list to suppress SCEVExpander hoisting address modes. 4829 // Unless the addressing mode will not be folded. 4830 if (!Ops.empty() && LU.Kind == LSRUse::Address && 4831 isAMCompletelyFolded(TTI, LU, F)) { 4832 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 4833 Ops.clear(); 4834 Ops.push_back(SE.getUnknown(FullV)); 4835 } 4836 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)); 4837 if (F.Scale != 1) 4838 ScaledS = 4839 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale)); 4840 Ops.push_back(ScaledS); 4841 } 4842 } 4843 4844 // Expand the GV portion. 4845 if (F.BaseGV) { 4846 // Flush the operand list to suppress SCEVExpander hoisting. 4847 if (!Ops.empty()) { 4848 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 4849 Ops.clear(); 4850 Ops.push_back(SE.getUnknown(FullV)); 4851 } 4852 Ops.push_back(SE.getUnknown(F.BaseGV)); 4853 } 4854 4855 // Flush the operand list to suppress SCEVExpander hoisting of both folded and 4856 // unfolded offsets. LSR assumes they both live next to their uses. 4857 if (!Ops.empty()) { 4858 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 4859 Ops.clear(); 4860 Ops.push_back(SE.getUnknown(FullV)); 4861 } 4862 4863 // Expand the immediate portion. 4864 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset; 4865 if (Offset != 0) { 4866 if (LU.Kind == LSRUse::ICmpZero) { 4867 // The other interesting way of "folding" with an ICmpZero is to use a 4868 // negated immediate. 4869 if (!ICmpScaledV) 4870 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset); 4871 else { 4872 Ops.push_back(SE.getUnknown(ICmpScaledV)); 4873 ICmpScaledV = ConstantInt::get(IntTy, Offset); 4874 } 4875 } else { 4876 // Just add the immediate values. These again are expected to be matched 4877 // as part of the address. 4878 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset))); 4879 } 4880 } 4881 4882 // Expand the unfolded offset portion. 4883 int64_t UnfoldedOffset = F.UnfoldedOffset; 4884 if (UnfoldedOffset != 0) { 4885 // Just add the immediate values. 4886 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, 4887 UnfoldedOffset))); 4888 } 4889 4890 // Emit instructions summing all the operands. 4891 const SCEV *FullS = Ops.empty() ? 4892 SE.getConstant(IntTy, 0) : 4893 SE.getAddExpr(Ops); 4894 Value *FullV = Rewriter.expandCodeFor(FullS, Ty); 4895 4896 // We're done expanding now, so reset the rewriter. 4897 Rewriter.clearPostInc(); 4898 4899 // An ICmpZero Formula represents an ICmp which we're handling as a 4900 // comparison against zero. Now that we've expanded an expression for that 4901 // form, update the ICmp's other operand. 4902 if (LU.Kind == LSRUse::ICmpZero) { 4903 ICmpInst *CI = cast<ICmpInst>(LF.UserInst); 4904 DeadInsts.emplace_back(CI->getOperand(1)); 4905 assert(!F.BaseGV && "ICmp does not support folding a global value and " 4906 "a scale at the same time!"); 4907 if (F.Scale == -1) { 4908 if (ICmpScaledV->getType() != OpTy) { 4909 Instruction *Cast = 4910 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false, 4911 OpTy, false), 4912 ICmpScaledV, OpTy, "tmp", CI); 4913 ICmpScaledV = Cast; 4914 } 4915 CI->setOperand(1, ICmpScaledV); 4916 } else { 4917 // A scale of 1 means that the scale has been expanded as part of the 4918 // base regs. 4919 assert((F.Scale == 0 || F.Scale == 1) && 4920 "ICmp does not support folding a global value and " 4921 "a scale at the same time!"); 4922 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy), 4923 -(uint64_t)Offset); 4924 if (C->getType() != OpTy) 4925 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 4926 OpTy, false), 4927 C, OpTy); 4928 4929 CI->setOperand(1, C); 4930 } 4931 } 4932 4933 return FullV; 4934 } 4935 4936 /// Helper for Rewrite. PHI nodes are special because the use of their operands 4937 /// effectively happens in their predecessor blocks, so the expression may need 4938 /// to be expanded in multiple places. 4939 void LSRInstance::RewriteForPHI( 4940 PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F, 4941 SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 4942 DenseMap<BasicBlock *, Value *> Inserted; 4943 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 4944 if (PN->getIncomingValue(i) == LF.OperandValToReplace) { 4945 BasicBlock *BB = PN->getIncomingBlock(i); 4946 4947 // If this is a critical edge, split the edge so that we do not insert 4948 // the code on all predecessor/successor paths. We do this unless this 4949 // is the canonical backedge for this loop, which complicates post-inc 4950 // users. 4951 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 && 4952 !isa<IndirectBrInst>(BB->getTerminator()) && 4953 !isa<CatchSwitchInst>(BB->getTerminator())) { 4954 BasicBlock *Parent = PN->getParent(); 4955 Loop *PNLoop = LI.getLoopFor(Parent); 4956 if (!PNLoop || Parent != PNLoop->getHeader()) { 4957 // Split the critical edge. 4958 BasicBlock *NewBB = nullptr; 4959 if (!Parent->isLandingPad()) { 4960 NewBB = SplitCriticalEdge(BB, Parent, 4961 CriticalEdgeSplittingOptions(&DT, &LI) 4962 .setMergeIdenticalEdges() 4963 .setDontDeleteUselessPHIs()); 4964 } else { 4965 SmallVector<BasicBlock*, 2> NewBBs; 4966 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI); 4967 NewBB = NewBBs[0]; 4968 } 4969 // If NewBB==NULL, then SplitCriticalEdge refused to split because all 4970 // phi predecessors are identical. The simple thing to do is skip 4971 // splitting in this case rather than complicate the API. 4972 if (NewBB) { 4973 // If PN is outside of the loop and BB is in the loop, we want to 4974 // move the block to be immediately before the PHI block, not 4975 // immediately after BB. 4976 if (L->contains(BB) && !L->contains(PN)) 4977 NewBB->moveBefore(PN->getParent()); 4978 4979 // Splitting the edge can reduce the number of PHI entries we have. 4980 e = PN->getNumIncomingValues(); 4981 BB = NewBB; 4982 i = PN->getBasicBlockIndex(BB); 4983 } 4984 } 4985 } 4986 4987 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair = 4988 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr))); 4989 if (!Pair.second) 4990 PN->setIncomingValue(i, Pair.first->second); 4991 else { 4992 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(), 4993 Rewriter, DeadInsts); 4994 4995 // If this is reuse-by-noop-cast, insert the noop cast. 4996 Type *OpTy = LF.OperandValToReplace->getType(); 4997 if (FullV->getType() != OpTy) 4998 FullV = 4999 CastInst::Create(CastInst::getCastOpcode(FullV, false, 5000 OpTy, false), 5001 FullV, LF.OperandValToReplace->getType(), 5002 "tmp", BB->getTerminator()); 5003 5004 PN->setIncomingValue(i, FullV); 5005 Pair.first->second = FullV; 5006 } 5007 } 5008 } 5009 5010 /// Emit instructions for the leading candidate expression for this LSRUse (this 5011 /// is called "expanding"), and update the UserInst to reference the newly 5012 /// expanded value. 5013 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF, 5014 const Formula &F, SCEVExpander &Rewriter, 5015 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5016 // First, find an insertion point that dominates UserInst. For PHI nodes, 5017 // find the nearest block which dominates all the relevant uses. 5018 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) { 5019 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts); 5020 } else { 5021 Value *FullV = 5022 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts); 5023 5024 // If this is reuse-by-noop-cast, insert the noop cast. 5025 Type *OpTy = LF.OperandValToReplace->getType(); 5026 if (FullV->getType() != OpTy) { 5027 Instruction *Cast = 5028 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false), 5029 FullV, OpTy, "tmp", LF.UserInst); 5030 FullV = Cast; 5031 } 5032 5033 // Update the user. ICmpZero is handled specially here (for now) because 5034 // Expand may have updated one of the operands of the icmp already, and 5035 // its new value may happen to be equal to LF.OperandValToReplace, in 5036 // which case doing replaceUsesOfWith leads to replacing both operands 5037 // with the same value. TODO: Reorganize this. 5038 if (LU.Kind == LSRUse::ICmpZero) 5039 LF.UserInst->setOperand(0, FullV); 5040 else 5041 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV); 5042 } 5043 5044 DeadInsts.emplace_back(LF.OperandValToReplace); 5045 } 5046 5047 /// Rewrite all the fixup locations with new values, following the chosen 5048 /// solution. 5049 void LSRInstance::ImplementSolution( 5050 const SmallVectorImpl<const Formula *> &Solution) { 5051 // Keep track of instructions we may have made dead, so that 5052 // we can remove them after we are done working. 5053 SmallVector<WeakTrackingVH, 16> DeadInsts; 5054 5055 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(), 5056 "lsr"); 5057 #ifndef NDEBUG 5058 Rewriter.setDebugType(DEBUG_TYPE); 5059 #endif 5060 Rewriter.disableCanonicalMode(); 5061 Rewriter.enableLSRMode(); 5062 Rewriter.setIVIncInsertPos(L, IVIncInsertPos); 5063 5064 // Mark phi nodes that terminate chains so the expander tries to reuse them. 5065 for (const IVChain &Chain : IVChainVec) { 5066 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst())) 5067 Rewriter.setChainedPhi(PN); 5068 } 5069 5070 // Expand the new value definitions and update the users. 5071 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) 5072 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) { 5073 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts); 5074 Changed = true; 5075 } 5076 5077 for (const IVChain &Chain : IVChainVec) { 5078 GenerateIVChain(Chain, Rewriter, DeadInsts); 5079 Changed = true; 5080 } 5081 // Clean up after ourselves. This must be done before deleting any 5082 // instructions. 5083 Rewriter.clear(); 5084 5085 Changed |= DeleteTriviallyDeadInstructions(DeadInsts); 5086 } 5087 5088 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, 5089 DominatorTree &DT, LoopInfo &LI, 5090 const TargetTransformInfo &TTI) 5091 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L), Changed(false), 5092 IVIncInsertPos(nullptr) { 5093 // If LoopSimplify form is not available, stay out of trouble. 5094 if (!L->isLoopSimplifyForm()) 5095 return; 5096 5097 // If there's no interesting work to be done, bail early. 5098 if (IU.empty()) return; 5099 5100 // If there's too much analysis to be done, bail early. We won't be able to 5101 // model the problem anyway. 5102 unsigned NumUsers = 0; 5103 for (const IVStrideUse &U : IU) { 5104 if (++NumUsers > MaxIVUsers) { 5105 (void)U; 5106 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n"); 5107 return; 5108 } 5109 // Bail out if we have a PHI on an EHPad that gets a value from a 5110 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is 5111 // no good place to stick any instructions. 5112 if (auto *PN = dyn_cast<PHINode>(U.getUser())) { 5113 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI(); 5114 if (isa<FuncletPadInst>(FirstNonPHI) || 5115 isa<CatchSwitchInst>(FirstNonPHI)) 5116 for (BasicBlock *PredBB : PN->blocks()) 5117 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI())) 5118 return; 5119 } 5120 } 5121 5122 #ifndef NDEBUG 5123 // All dominating loops must have preheaders, or SCEVExpander may not be able 5124 // to materialize an AddRecExpr whose Start is an outer AddRecExpr. 5125 // 5126 // IVUsers analysis should only create users that are dominated by simple loop 5127 // headers. Since this loop should dominate all of its users, its user list 5128 // should be empty if this loop itself is not within a simple loop nest. 5129 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader()); 5130 Rung; Rung = Rung->getIDom()) { 5131 BasicBlock *BB = Rung->getBlock(); 5132 const Loop *DomLoop = LI.getLoopFor(BB); 5133 if (DomLoop && DomLoop->getHeader() == BB) { 5134 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest"); 5135 } 5136 } 5137 #endif // DEBUG 5138 5139 DEBUG(dbgs() << "\nLSR on loop "; 5140 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false); 5141 dbgs() << ":\n"); 5142 5143 // First, perform some low-level loop optimizations. 5144 OptimizeShadowIV(); 5145 OptimizeLoopTermCond(); 5146 5147 // If loop preparation eliminates all interesting IV users, bail. 5148 if (IU.empty()) return; 5149 5150 // Skip nested loops until we can model them better with formulae. 5151 if (!L->empty()) { 5152 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n"); 5153 return; 5154 } 5155 5156 // Start collecting data and preparing for the solver. 5157 CollectChains(); 5158 CollectInterestingTypesAndFactors(); 5159 CollectFixupsAndInitialFormulae(); 5160 CollectLoopInvariantFixupsAndFormulae(); 5161 5162 assert(!Uses.empty() && "IVUsers reported at least one use"); 5163 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n"; 5164 print_uses(dbgs())); 5165 5166 // Now use the reuse data to generate a bunch of interesting ways 5167 // to formulate the values needed for the uses. 5168 GenerateAllReuseFormulae(); 5169 5170 FilterOutUndesirableDedicatedRegisters(); 5171 NarrowSearchSpaceUsingHeuristics(); 5172 5173 SmallVector<const Formula *, 8> Solution; 5174 Solve(Solution); 5175 5176 // Release memory that is no longer needed. 5177 Factors.clear(); 5178 Types.clear(); 5179 RegUses.clear(); 5180 5181 if (Solution.empty()) 5182 return; 5183 5184 #ifndef NDEBUG 5185 // Formulae should be legal. 5186 for (const LSRUse &LU : Uses) { 5187 for (const Formula &F : LU.Formulae) 5188 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 5189 F) && "Illegal formula generated!"); 5190 }; 5191 #endif 5192 5193 // Now that we've decided what we want, make it so. 5194 ImplementSolution(Solution); 5195 } 5196 5197 void LSRInstance::print_factors_and_types(raw_ostream &OS) const { 5198 if (Factors.empty() && Types.empty()) return; 5199 5200 OS << "LSR has identified the following interesting factors and types: "; 5201 bool First = true; 5202 5203 for (int64_t Factor : Factors) { 5204 if (!First) OS << ", "; 5205 First = false; 5206 OS << '*' << Factor; 5207 } 5208 5209 for (Type *Ty : Types) { 5210 if (!First) OS << ", "; 5211 First = false; 5212 OS << '(' << *Ty << ')'; 5213 } 5214 OS << '\n'; 5215 } 5216 5217 void LSRInstance::print_fixups(raw_ostream &OS) const { 5218 OS << "LSR is examining the following fixup sites:\n"; 5219 for (const LSRUse &LU : Uses) 5220 for (const LSRFixup &LF : LU.Fixups) { 5221 dbgs() << " "; 5222 LF.print(OS); 5223 OS << '\n'; 5224 } 5225 } 5226 5227 void LSRInstance::print_uses(raw_ostream &OS) const { 5228 OS << "LSR is examining the following uses:\n"; 5229 for (const LSRUse &LU : Uses) { 5230 dbgs() << " "; 5231 LU.print(OS); 5232 OS << '\n'; 5233 for (const Formula &F : LU.Formulae) { 5234 OS << " "; 5235 F.print(OS); 5236 OS << '\n'; 5237 } 5238 } 5239 } 5240 5241 void LSRInstance::print(raw_ostream &OS) const { 5242 print_factors_and_types(OS); 5243 print_fixups(OS); 5244 print_uses(OS); 5245 } 5246 5247 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5248 LLVM_DUMP_METHOD void LSRInstance::dump() const { 5249 print(errs()); errs() << '\n'; 5250 } 5251 #endif 5252 5253 namespace { 5254 5255 class LoopStrengthReduce : public LoopPass { 5256 public: 5257 static char ID; // Pass ID, replacement for typeid 5258 5259 LoopStrengthReduce(); 5260 5261 private: 5262 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 5263 void getAnalysisUsage(AnalysisUsage &AU) const override; 5264 }; 5265 5266 } // end anonymous namespace 5267 5268 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) { 5269 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry()); 5270 } 5271 5272 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const { 5273 // We split critical edges, so we change the CFG. However, we do update 5274 // many analyses if they are around. 5275 AU.addPreservedID(LoopSimplifyID); 5276 5277 AU.addRequired<LoopInfoWrapperPass>(); 5278 AU.addPreserved<LoopInfoWrapperPass>(); 5279 AU.addRequiredID(LoopSimplifyID); 5280 AU.addRequired<DominatorTreeWrapperPass>(); 5281 AU.addPreserved<DominatorTreeWrapperPass>(); 5282 AU.addRequired<ScalarEvolutionWrapperPass>(); 5283 AU.addPreserved<ScalarEvolutionWrapperPass>(); 5284 // Requiring LoopSimplify a second time here prevents IVUsers from running 5285 // twice, since LoopSimplify was invalidated by running ScalarEvolution. 5286 AU.addRequiredID(LoopSimplifyID); 5287 AU.addRequired<IVUsersWrapperPass>(); 5288 AU.addPreserved<IVUsersWrapperPass>(); 5289 AU.addRequired<TargetTransformInfoWrapperPass>(); 5290 } 5291 5292 static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, 5293 DominatorTree &DT, LoopInfo &LI, 5294 const TargetTransformInfo &TTI) { 5295 bool Changed = false; 5296 5297 // Run the main LSR transformation. 5298 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged(); 5299 5300 // Remove any extra phis created by processing inner loops. 5301 Changed |= DeleteDeadPHIs(L->getHeader()); 5302 if (EnablePhiElim && L->isLoopSimplifyForm()) { 5303 SmallVector<WeakTrackingVH, 16> DeadInsts; 5304 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 5305 SCEVExpander Rewriter(SE, DL, "lsr"); 5306 #ifndef NDEBUG 5307 Rewriter.setDebugType(DEBUG_TYPE); 5308 #endif 5309 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI); 5310 if (numFolded) { 5311 Changed = true; 5312 DeleteTriviallyDeadInstructions(DeadInsts); 5313 DeleteDeadPHIs(L->getHeader()); 5314 } 5315 } 5316 return Changed; 5317 } 5318 5319 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) { 5320 if (skipLoop(L)) 5321 return false; 5322 5323 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU(); 5324 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 5325 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 5326 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 5327 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 5328 *L->getHeader()->getParent()); 5329 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI); 5330 } 5331 5332 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM, 5333 LoopStandardAnalysisResults &AR, 5334 LPMUpdater &) { 5335 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE, 5336 AR.DT, AR.LI, AR.TTI)) 5337 return PreservedAnalyses::all(); 5338 5339 return getLoopPassPreservedAnalyses(); 5340 } 5341 5342 char LoopStrengthReduce::ID = 0; 5343 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce", 5344 "Loop Strength Reduction", false, false) 5345 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 5346 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 5347 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 5348 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass) 5349 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 5350 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 5351 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce", 5352 "Loop Strength Reduction", false, false) 5353 5354 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); } 5355