1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
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.
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:
24 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
26 // %i.next = add %i, 1
27 // %c = icmp eq %i.next, %n
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.
36 // TODO: More sophistication in the way Formulae are generated and filtered.
38 // TODO: Handle multiple loops at a time.
40 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41 // instead of a GlobalValue?
43 // TODO: When truncation is free, truncate ICmp users' operands to make it a
44 // smaller encoding (on x86 at least).
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"
54 //===----------------------------------------------------------------------===//
56 #define DEBUG_TYPE "loop-reduce"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Constants.h"
59 #include "llvm/Instructions.h"
60 #include "llvm/IntrinsicInst.h"
61 #include "llvm/DerivedTypes.h"
62 #include "llvm/Analysis/IVUsers.h"
63 #include "llvm/Analysis/Dominators.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include "llvm/ADT/SmallBitVector.h"
69 #include "llvm/ADT/SetVector.h"
70 #include "llvm/ADT/DenseSet.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ValueHandle.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetLowering.h"
80 /// RegSortData - This class holds data which is used to order reuse candidates.
83 /// UsedByIndices - This represents the set of LSRUse indices which reference
84 /// a particular register.
85 SmallBitVector UsedByIndices;
89 void print(raw_ostream &OS) const;
95 void RegSortData::print(raw_ostream &OS) const {
96 OS << "[NumUses=" << UsedByIndices.count() << ']';
99 void RegSortData::dump() const {
100 print(errs()); errs() << '\n';
105 /// RegUseTracker - Map register candidates to information about how they are
107 class RegUseTracker {
108 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
110 RegUsesTy RegUsesMap;
111 SmallVector<const SCEV *, 16> RegSequence;
114 void CountRegister(const SCEV *Reg, size_t LUIdx);
115 void DropRegister(const SCEV *Reg, size_t LUIdx);
117 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
119 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
123 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
124 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
125 iterator begin() { return RegSequence.begin(); }
126 iterator end() { return RegSequence.end(); }
127 const_iterator begin() const { return RegSequence.begin(); }
128 const_iterator end() const { return RegSequence.end(); }
134 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
135 std::pair<RegUsesTy::iterator, bool> Pair =
136 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
137 RegSortData &RSD = Pair.first->second;
139 RegSequence.push_back(Reg);
140 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
141 RSD.UsedByIndices.set(LUIdx);
145 RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
146 RegUsesTy::iterator It = RegUsesMap.find(Reg);
147 assert(It != RegUsesMap.end());
148 RegSortData &RSD = It->second;
149 assert(RSD.UsedByIndices.size() > LUIdx);
150 RSD.UsedByIndices.reset(LUIdx);
154 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
155 if (!RegUsesMap.count(Reg)) return false;
156 const SmallBitVector &UsedByIndices =
157 RegUsesMap.find(Reg)->second.UsedByIndices;
158 int i = UsedByIndices.find_first();
159 if (i == -1) return false;
160 if ((size_t)i != LUIdx) return true;
161 return UsedByIndices.find_next(i) != -1;
164 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
165 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
166 assert(I != RegUsesMap.end() && "Unknown register!");
167 return I->second.UsedByIndices;
170 void RegUseTracker::clear() {
177 /// Formula - This class holds information that describes a formula for
178 /// computing satisfying a use. It may include broken-out immediates and scaled
181 /// AM - This is used to represent complex addressing, as well as other kinds
182 /// of interesting uses.
183 TargetLowering::AddrMode AM;
185 /// BaseRegs - The list of "base" registers for this use. When this is
186 /// non-empty, AM.HasBaseReg should be set to true.
187 SmallVector<const SCEV *, 2> BaseRegs;
189 /// ScaledReg - The 'scaled' register for this use. This should be non-null
190 /// when AM.Scale is not zero.
191 const SCEV *ScaledReg;
193 Formula() : ScaledReg(0) {}
195 void InitialMatch(const SCEV *S, Loop *L,
196 ScalarEvolution &SE, DominatorTree &DT);
198 unsigned getNumRegs() const;
199 const Type *getType() const;
201 bool referencesReg(const SCEV *S) const;
202 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
203 const RegUseTracker &RegUses) const;
205 void print(raw_ostream &OS) const;
211 /// DoInitialMatch - Recursion helper for InitialMatch.
212 static void DoInitialMatch(const SCEV *S, Loop *L,
213 SmallVectorImpl<const SCEV *> &Good,
214 SmallVectorImpl<const SCEV *> &Bad,
215 ScalarEvolution &SE, DominatorTree &DT) {
216 // Collect expressions which properly dominate the loop header.
217 if (S->properlyDominates(L->getHeader(), &DT)) {
222 // Look at add operands.
223 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
224 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
226 DoInitialMatch(*I, L, Good, Bad, SE, DT);
230 // Look at addrec operands.
231 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
232 if (!AR->getStart()->isZero()) {
233 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
234 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
235 AR->getStepRecurrence(SE),
237 L, Good, Bad, SE, DT);
241 // Handle a multiplication by -1 (negation) if it didn't fold.
242 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
243 if (Mul->getOperand(0)->isAllOnesValue()) {
244 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
245 const SCEV *NewMul = SE.getMulExpr(Ops);
247 SmallVector<const SCEV *, 4> MyGood;
248 SmallVector<const SCEV *, 4> MyBad;
249 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
250 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
251 SE.getEffectiveSCEVType(NewMul->getType())));
252 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
253 E = MyGood.end(); I != E; ++I)
254 Good.push_back(SE.getMulExpr(NegOne, *I));
255 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
256 E = MyBad.end(); I != E; ++I)
257 Bad.push_back(SE.getMulExpr(NegOne, *I));
261 // Ok, we can't do anything interesting. Just stuff the whole thing into a
262 // register and hope for the best.
266 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
267 /// attempting to keep all loop-invariant and loop-computable values in a
268 /// single base register.
269 void Formula::InitialMatch(const SCEV *S, Loop *L,
270 ScalarEvolution &SE, DominatorTree &DT) {
271 SmallVector<const SCEV *, 4> Good;
272 SmallVector<const SCEV *, 4> Bad;
273 DoInitialMatch(S, L, Good, Bad, SE, DT);
275 const SCEV *Sum = SE.getAddExpr(Good);
277 BaseRegs.push_back(Sum);
278 AM.HasBaseReg = true;
281 const SCEV *Sum = SE.getAddExpr(Bad);
283 BaseRegs.push_back(Sum);
284 AM.HasBaseReg = true;
288 /// getNumRegs - Return the total number of register operands used by this
289 /// formula. This does not include register uses implied by non-constant
291 unsigned Formula::getNumRegs() const {
292 return !!ScaledReg + BaseRegs.size();
295 /// getType - Return the type of this formula, if it has one, or null
296 /// otherwise. This type is meaningless except for the bit size.
297 const Type *Formula::getType() const {
298 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
299 ScaledReg ? ScaledReg->getType() :
300 AM.BaseGV ? AM.BaseGV->getType() :
304 /// referencesReg - Test if this formula references the given register.
305 bool Formula::referencesReg(const SCEV *S) const {
306 return S == ScaledReg ||
307 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
310 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
311 /// which are used by uses other than the use with the given index.
312 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
313 const RegUseTracker &RegUses) const {
315 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
317 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
318 E = BaseRegs.end(); I != E; ++I)
319 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
324 void Formula::print(raw_ostream &OS) const {
327 if (!First) OS << " + "; else First = false;
328 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
330 if (AM.BaseOffs != 0) {
331 if (!First) OS << " + "; else First = false;
334 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
335 E = BaseRegs.end(); I != E; ++I) {
336 if (!First) OS << " + "; else First = false;
337 OS << "reg(" << **I << ')';
339 if (AM.HasBaseReg && BaseRegs.empty()) {
340 if (!First) OS << " + "; else First = false;
341 OS << "**error: HasBaseReg**";
342 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
343 if (!First) OS << " + "; else First = false;
344 OS << "**error: !HasBaseReg**";
347 if (!First) OS << " + "; else First = false;
348 OS << AM.Scale << "*reg(";
357 void Formula::dump() const {
358 print(errs()); errs() << '\n';
361 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
362 /// without changing its value.
363 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
365 IntegerType::get(SE.getContext(),
366 SE.getTypeSizeInBits(AR->getType()) + 1);
367 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
370 /// isAddSExtable - Return true if the given add can be sign-extended
371 /// without changing its value.
372 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
374 IntegerType::get(SE.getContext(),
375 SE.getTypeSizeInBits(A->getType()) + 1);
376 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
379 /// isMulSExtable - Return true if the given add can be sign-extended
380 /// without changing its value.
381 static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
383 IntegerType::get(SE.getContext(),
384 SE.getTypeSizeInBits(A->getType()) + 1);
385 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
388 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
389 /// and if the remainder is known to be zero, or null otherwise. If
390 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
391 /// to Y, ignoring that the multiplication may overflow, which is useful when
392 /// the result will be used in a context where the most significant bits are
394 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
396 bool IgnoreSignificantBits = false) {
397 // Handle the trivial case, which works for any SCEV type.
399 return SE.getConstant(LHS->getType(), 1);
401 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
403 if (RHS->isAllOnesValue())
404 return SE.getMulExpr(LHS, RHS);
406 // Check for a division of a constant by a constant.
407 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
408 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
411 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
413 return SE.getConstant(C->getValue()->getValue()
414 .sdiv(RC->getValue()->getValue()));
417 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
418 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
419 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
420 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
421 IgnoreSignificantBits);
422 if (!Start) return 0;
423 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
424 IgnoreSignificantBits);
426 return SE.getAddRecExpr(Start, Step, AR->getLoop());
430 // Distribute the sdiv over add operands, if the add doesn't overflow.
431 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
432 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
433 SmallVector<const SCEV *, 8> Ops;
434 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
436 const SCEV *Op = getExactSDiv(*I, RHS, SE,
437 IgnoreSignificantBits);
441 return SE.getAddExpr(Ops);
445 // Check for a multiply operand that we can pull RHS out of.
446 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
447 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
448 SmallVector<const SCEV *, 4> Ops;
450 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
453 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
454 IgnoreSignificantBits)) {
461 return Found ? SE.getMulExpr(Ops) : 0;
464 // Otherwise we don't know.
468 /// ExtractImmediate - If S involves the addition of a constant integer value,
469 /// return that integer value, and mutate S to point to a new SCEV with that
471 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
472 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
473 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
474 S = SE.getConstant(C->getType(), 0);
475 return C->getValue()->getSExtValue();
477 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
478 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
479 int64_t Result = ExtractImmediate(NewOps.front(), SE);
480 S = SE.getAddExpr(NewOps);
482 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
483 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
484 int64_t Result = ExtractImmediate(NewOps.front(), SE);
485 S = SE.getAddRecExpr(NewOps, AR->getLoop());
491 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
492 /// return that symbol, and mutate S to point to a new SCEV with that
494 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
495 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
496 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
497 S = SE.getConstant(GV->getType(), 0);
500 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
501 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
502 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
503 S = SE.getAddExpr(NewOps);
505 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
506 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
507 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
508 S = SE.getAddRecExpr(NewOps, AR->getLoop());
514 /// isAddressUse - Returns true if the specified instruction is using the
515 /// specified value as an address.
516 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
517 bool isAddress = isa<LoadInst>(Inst);
518 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
519 if (SI->getOperand(1) == OperandVal)
521 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
522 // Addressing modes can also be folded into prefetches and a variety
524 switch (II->getIntrinsicID()) {
526 case Intrinsic::prefetch:
527 case Intrinsic::x86_sse2_loadu_dq:
528 case Intrinsic::x86_sse2_loadu_pd:
529 case Intrinsic::x86_sse_loadu_ps:
530 case Intrinsic::x86_sse_storeu_ps:
531 case Intrinsic::x86_sse2_storeu_pd:
532 case Intrinsic::x86_sse2_storeu_dq:
533 case Intrinsic::x86_sse2_storel_dq:
534 if (II->getOperand(1) == OperandVal)
542 /// getAccessType - Return the type of the memory being accessed.
543 static const Type *getAccessType(const Instruction *Inst) {
544 const Type *AccessTy = Inst->getType();
545 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
546 AccessTy = SI->getOperand(0)->getType();
547 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
548 // Addressing modes can also be folded into prefetches and a variety
550 switch (II->getIntrinsicID()) {
552 case Intrinsic::x86_sse_storeu_ps:
553 case Intrinsic::x86_sse2_storeu_pd:
554 case Intrinsic::x86_sse2_storeu_dq:
555 case Intrinsic::x86_sse2_storel_dq:
556 AccessTy = II->getOperand(1)->getType();
561 // All pointers have the same requirements, so canonicalize them to an
562 // arbitrary pointer type to minimize variation.
563 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
564 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
565 PTy->getAddressSpace());
570 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
571 /// specified set are trivially dead, delete them and see if this makes any of
572 /// their operands subsequently dead.
574 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
575 bool Changed = false;
577 while (!DeadInsts.empty()) {
578 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
580 if (I == 0 || !isInstructionTriviallyDead(I))
583 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
584 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
587 DeadInsts.push_back(U);
590 I->eraseFromParent();
599 /// Cost - This class is used to measure and compare candidate formulae.
601 /// TODO: Some of these could be merged. Also, a lexical ordering
602 /// isn't always optimal.
606 unsigned NumBaseAdds;
612 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
615 unsigned getNumRegs() const { return NumRegs; }
617 bool operator<(const Cost &Other) const;
621 void RateFormula(const Formula &F,
622 SmallPtrSet<const SCEV *, 16> &Regs,
623 const DenseSet<const SCEV *> &VisitedRegs,
625 const SmallVectorImpl<int64_t> &Offsets,
626 ScalarEvolution &SE, DominatorTree &DT);
628 void print(raw_ostream &OS) const;
632 void RateRegister(const SCEV *Reg,
633 SmallPtrSet<const SCEV *, 16> &Regs,
635 ScalarEvolution &SE, DominatorTree &DT);
636 void RatePrimaryRegister(const SCEV *Reg,
637 SmallPtrSet<const SCEV *, 16> &Regs,
639 ScalarEvolution &SE, DominatorTree &DT);
644 /// RateRegister - Tally up interesting quantities from the given register.
645 void Cost::RateRegister(const SCEV *Reg,
646 SmallPtrSet<const SCEV *, 16> &Regs,
648 ScalarEvolution &SE, DominatorTree &DT) {
649 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
650 if (AR->getLoop() == L)
651 AddRecCost += 1; /// TODO: This should be a function of the stride.
653 // If this is an addrec for a loop that's already been visited by LSR,
654 // don't second-guess its addrec phi nodes. LSR isn't currently smart
655 // enough to reason about more than one loop at a time. Consider these
656 // registers free and leave them alone.
657 else if (L->contains(AR->getLoop()) ||
658 (!AR->getLoop()->contains(L) &&
659 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
660 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
661 PHINode *PN = dyn_cast<PHINode>(I); ++I)
662 if (SE.isSCEVable(PN->getType()) &&
663 (SE.getEffectiveSCEVType(PN->getType()) ==
664 SE.getEffectiveSCEVType(AR->getType())) &&
665 SE.getSCEV(PN) == AR)
668 // If this isn't one of the addrecs that the loop already has, it
669 // would require a costly new phi and add. TODO: This isn't
670 // precisely modeled right now.
672 if (!Regs.count(AR->getStart()))
673 RateRegister(AR->getStart(), Regs, L, SE, DT);
676 // Add the step value register, if it needs one.
677 // TODO: The non-affine case isn't precisely modeled here.
678 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
679 if (!Regs.count(AR->getStart()))
680 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
684 // Rough heuristic; favor registers which don't require extra setup
685 // instructions in the preheader.
686 if (!isa<SCEVUnknown>(Reg) &&
687 !isa<SCEVConstant>(Reg) &&
688 !(isa<SCEVAddRecExpr>(Reg) &&
689 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
690 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
694 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
696 void Cost::RatePrimaryRegister(const SCEV *Reg,
697 SmallPtrSet<const SCEV *, 16> &Regs,
699 ScalarEvolution &SE, DominatorTree &DT) {
700 if (Regs.insert(Reg))
701 RateRegister(Reg, Regs, L, SE, DT);
704 void Cost::RateFormula(const Formula &F,
705 SmallPtrSet<const SCEV *, 16> &Regs,
706 const DenseSet<const SCEV *> &VisitedRegs,
708 const SmallVectorImpl<int64_t> &Offsets,
709 ScalarEvolution &SE, DominatorTree &DT) {
710 // Tally up the registers.
711 if (const SCEV *ScaledReg = F.ScaledReg) {
712 if (VisitedRegs.count(ScaledReg)) {
716 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
718 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
719 E = F.BaseRegs.end(); I != E; ++I) {
720 const SCEV *BaseReg = *I;
721 if (VisitedRegs.count(BaseReg)) {
725 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
727 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
728 BaseReg->hasComputableLoopEvolution(L);
731 if (F.BaseRegs.size() > 1)
732 NumBaseAdds += F.BaseRegs.size() - 1;
734 // Tally up the non-zero immediates.
735 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
736 E = Offsets.end(); I != E; ++I) {
737 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
739 ImmCost += 64; // Handle symbolic values conservatively.
740 // TODO: This should probably be the pointer size.
741 else if (Offset != 0)
742 ImmCost += APInt(64, Offset, true).getMinSignedBits();
746 /// Loose - Set this cost to a loosing value.
756 /// operator< - Choose the lower cost.
757 bool Cost::operator<(const Cost &Other) const {
758 if (NumRegs != Other.NumRegs)
759 return NumRegs < Other.NumRegs;
760 if (AddRecCost != Other.AddRecCost)
761 return AddRecCost < Other.AddRecCost;
762 if (NumIVMuls != Other.NumIVMuls)
763 return NumIVMuls < Other.NumIVMuls;
764 if (NumBaseAdds != Other.NumBaseAdds)
765 return NumBaseAdds < Other.NumBaseAdds;
766 if (ImmCost != Other.ImmCost)
767 return ImmCost < Other.ImmCost;
768 if (SetupCost != Other.SetupCost)
769 return SetupCost < Other.SetupCost;
773 void Cost::print(raw_ostream &OS) const {
774 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
776 OS << ", with addrec cost " << AddRecCost;
778 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
779 if (NumBaseAdds != 0)
780 OS << ", plus " << NumBaseAdds << " base add"
781 << (NumBaseAdds == 1 ? "" : "s");
783 OS << ", plus " << ImmCost << " imm cost";
785 OS << ", plus " << SetupCost << " setup cost";
788 void Cost::dump() const {
789 print(errs()); errs() << '\n';
794 /// LSRFixup - An operand value in an instruction which is to be replaced
795 /// with some equivalent, possibly strength-reduced, replacement.
797 /// UserInst - The instruction which will be updated.
798 Instruction *UserInst;
800 /// OperandValToReplace - The operand of the instruction which will
801 /// be replaced. The operand may be used more than once; every instance
802 /// will be replaced.
803 Value *OperandValToReplace;
805 /// PostIncLoops - If this user is to use the post-incremented value of an
806 /// induction variable, this variable is non-null and holds the loop
807 /// associated with the induction variable.
808 PostIncLoopSet PostIncLoops;
810 /// LUIdx - The index of the LSRUse describing the expression which
811 /// this fixup needs, minus an offset (below).
814 /// Offset - A constant offset to be added to the LSRUse expression.
815 /// This allows multiple fixups to share the same LSRUse with different
816 /// offsets, for example in an unrolled loop.
819 bool isUseFullyOutsideLoop(const Loop *L) const;
823 void print(raw_ostream &OS) const;
830 : UserInst(0), OperandValToReplace(0),
831 LUIdx(~size_t(0)), Offset(0) {}
833 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
834 /// value outside of the given loop.
835 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
836 // PHI nodes use their value in their incoming blocks.
837 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
838 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
839 if (PN->getIncomingValue(i) == OperandValToReplace &&
840 L->contains(PN->getIncomingBlock(i)))
845 return !L->contains(UserInst);
848 void LSRFixup::print(raw_ostream &OS) const {
850 // Store is common and interesting enough to be worth special-casing.
851 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
853 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
854 } else if (UserInst->getType()->isVoidTy())
855 OS << UserInst->getOpcodeName();
857 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
859 OS << ", OperandValToReplace=";
860 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
862 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
863 E = PostIncLoops.end(); I != E; ++I) {
864 OS << ", PostIncLoop=";
865 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
868 if (LUIdx != ~size_t(0))
869 OS << ", LUIdx=" << LUIdx;
872 OS << ", Offset=" << Offset;
875 void LSRFixup::dump() const {
876 print(errs()); errs() << '\n';
881 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
882 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
883 struct UniquifierDenseMapInfo {
884 static SmallVector<const SCEV *, 2> getEmptyKey() {
885 SmallVector<const SCEV *, 2> V;
886 V.push_back(reinterpret_cast<const SCEV *>(-1));
890 static SmallVector<const SCEV *, 2> getTombstoneKey() {
891 SmallVector<const SCEV *, 2> V;
892 V.push_back(reinterpret_cast<const SCEV *>(-2));
896 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
898 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
899 E = V.end(); I != E; ++I)
900 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
904 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
905 const SmallVector<const SCEV *, 2> &RHS) {
910 /// LSRUse - This class holds the state that LSR keeps for each use in
911 /// IVUsers, as well as uses invented by LSR itself. It includes information
912 /// about what kinds of things can be folded into the user, information about
913 /// the user itself, and information about how the use may be satisfied.
914 /// TODO: Represent multiple users of the same expression in common?
916 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
919 /// KindType - An enum for a kind of use, indicating what types of
920 /// scaled and immediate operands it might support.
922 Basic, ///< A normal use, with no folding.
923 Special, ///< A special case of basic, allowing -1 scales.
924 Address, ///< An address use; folding according to TargetLowering
925 ICmpZero ///< An equality icmp with both operands folded into one.
926 // TODO: Add a generic icmp too?
930 const Type *AccessTy;
932 SmallVector<int64_t, 8> Offsets;
936 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
937 /// LSRUse are outside of the loop, in which case some special-case heuristics
939 bool AllFixupsOutsideLoop;
941 /// Formulae - A list of ways to build a value that can satisfy this user.
942 /// After the list is populated, one of these is selected heuristically and
943 /// used to formulate a replacement for OperandValToReplace in UserInst.
944 SmallVector<Formula, 12> Formulae;
946 /// Regs - The set of register candidates used by all formulae in this LSRUse.
947 SmallPtrSet<const SCEV *, 4> Regs;
949 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
950 MinOffset(INT64_MAX),
951 MaxOffset(INT64_MIN),
952 AllFixupsOutsideLoop(true) {}
954 bool InsertFormula(const Formula &F);
955 void DeleteFormula(Formula &F);
956 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
960 void print(raw_ostream &OS) const;
964 /// InsertFormula - If the given formula has not yet been inserted, add it to
965 /// the list, and return true. Return false otherwise.
966 bool LSRUse::InsertFormula(const Formula &F) {
967 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
968 if (F.ScaledReg) Key.push_back(F.ScaledReg);
969 // Unstable sort by host order ok, because this is only used for uniquifying.
970 std::sort(Key.begin(), Key.end());
972 if (!Uniquifier.insert(Key).second)
975 // Using a register to hold the value of 0 is not profitable.
976 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
977 "Zero allocated in a scaled register!");
979 for (SmallVectorImpl<const SCEV *>::const_iterator I =
980 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
981 assert(!(*I)->isZero() && "Zero allocated in a base register!");
984 // Add the formula to the list.
985 Formulae.push_back(F);
987 // Record registers now being used by this use.
988 if (F.ScaledReg) Regs.insert(F.ScaledReg);
989 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
994 /// DeleteFormula - Remove the given formula from this use's list.
995 void LSRUse::DeleteFormula(Formula &F) {
996 std::swap(F, Formulae.back());
1000 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
1001 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1002 // Now that we've filtered out some formulae, recompute the Regs set.
1003 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1005 for (size_t FIdx = 0, NumForms = Formulae.size(); FIdx != NumForms; ++FIdx) {
1006 Formula &F = Formulae[FIdx];
1007 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1008 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1011 // Update the RegTracker.
1012 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1013 E = OldRegs.end(); I != E; ++I)
1014 if (!Regs.count(*I))
1015 RegUses.DropRegister(*I, LUIdx);
1018 void LSRUse::print(raw_ostream &OS) const {
1019 OS << "LSR Use: Kind=";
1021 case Basic: OS << "Basic"; break;
1022 case Special: OS << "Special"; break;
1023 case ICmpZero: OS << "ICmpZero"; break;
1025 OS << "Address of ";
1026 if (AccessTy->isPointerTy())
1027 OS << "pointer"; // the full pointer type could be really verbose
1032 OS << ", Offsets={";
1033 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1034 E = Offsets.end(); I != E; ++I) {
1041 if (AllFixupsOutsideLoop)
1042 OS << ", all-fixups-outside-loop";
1045 void LSRUse::dump() const {
1046 print(errs()); errs() << '\n';
1049 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1050 /// be completely folded into the user instruction at isel time. This includes
1051 /// address-mode folding and special icmp tricks.
1052 static bool isLegalUse(const TargetLowering::AddrMode &AM,
1053 LSRUse::KindType Kind, const Type *AccessTy,
1054 const TargetLowering *TLI) {
1056 case LSRUse::Address:
1057 // If we have low-level target information, ask the target if it can
1058 // completely fold this address.
1059 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1061 // Otherwise, just guess that reg+reg addressing is legal.
1062 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1064 case LSRUse::ICmpZero:
1065 // There's not even a target hook for querying whether it would be legal to
1066 // fold a GV into an ICmp.
1070 // ICmp only has two operands; don't allow more than two non-trivial parts.
1071 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1074 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1075 // putting the scaled register in the other operand of the icmp.
1076 if (AM.Scale != 0 && AM.Scale != -1)
1079 // If we have low-level target information, ask the target if it can fold an
1080 // integer immediate on an icmp.
1081 if (AM.BaseOffs != 0) {
1082 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1089 // Only handle single-register values.
1090 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1092 case LSRUse::Special:
1093 // Only handle -1 scales, or no scale.
1094 return AM.Scale == 0 || AM.Scale == -1;
1100 static bool isLegalUse(TargetLowering::AddrMode AM,
1101 int64_t MinOffset, int64_t MaxOffset,
1102 LSRUse::KindType Kind, const Type *AccessTy,
1103 const TargetLowering *TLI) {
1104 // Check for overflow.
1105 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1108 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1109 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1110 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1111 // Check for overflow.
1112 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1115 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1116 return isLegalUse(AM, Kind, AccessTy, TLI);
1121 static bool isAlwaysFoldable(int64_t BaseOffs,
1122 GlobalValue *BaseGV,
1124 LSRUse::KindType Kind, const Type *AccessTy,
1125 const TargetLowering *TLI) {
1126 // Fast-path: zero is always foldable.
1127 if (BaseOffs == 0 && !BaseGV) return true;
1129 // Conservatively, create an address with an immediate and a
1130 // base and a scale.
1131 TargetLowering::AddrMode AM;
1132 AM.BaseOffs = BaseOffs;
1134 AM.HasBaseReg = HasBaseReg;
1135 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1137 return isLegalUse(AM, Kind, AccessTy, TLI);
1140 static bool isAlwaysFoldable(const SCEV *S,
1141 int64_t MinOffset, int64_t MaxOffset,
1143 LSRUse::KindType Kind, const Type *AccessTy,
1144 const TargetLowering *TLI,
1145 ScalarEvolution &SE) {
1146 // Fast-path: zero is always foldable.
1147 if (S->isZero()) return true;
1149 // Conservatively, create an address with an immediate and a
1150 // base and a scale.
1151 int64_t BaseOffs = ExtractImmediate(S, SE);
1152 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1154 // If there's anything else involved, it's not foldable.
1155 if (!S->isZero()) return false;
1157 // Fast-path: zero is always foldable.
1158 if (BaseOffs == 0 && !BaseGV) return true;
1160 // Conservatively, create an address with an immediate and a
1161 // base and a scale.
1162 TargetLowering::AddrMode AM;
1163 AM.BaseOffs = BaseOffs;
1165 AM.HasBaseReg = HasBaseReg;
1166 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1168 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1171 /// FormulaSorter - This class implements an ordering for formulae which sorts
1172 /// the by their standalone cost.
1173 class FormulaSorter {
1174 /// These two sets are kept empty, so that we compute standalone costs.
1175 DenseSet<const SCEV *> VisitedRegs;
1176 SmallPtrSet<const SCEV *, 16> Regs;
1179 ScalarEvolution &SE;
1183 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1184 : L(l), LU(&lu), SE(se), DT(dt) {}
1186 bool operator()(const Formula &A, const Formula &B) {
1188 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1191 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1193 return CostA < CostB;
1197 /// LSRInstance - This class holds state for the main loop strength reduction
1201 ScalarEvolution &SE;
1204 const TargetLowering *const TLI;
1208 /// IVIncInsertPos - This is the insert position that the current loop's
1209 /// induction variable increment should be placed. In simple loops, this is
1210 /// the latch block's terminator. But in more complicated cases, this is a
1211 /// position which will dominate all the in-loop post-increment users.
1212 Instruction *IVIncInsertPos;
1214 /// Factors - Interesting factors between use strides.
1215 SmallSetVector<int64_t, 8> Factors;
1217 /// Types - Interesting use types, to facilitate truncation reuse.
1218 SmallSetVector<const Type *, 4> Types;
1220 /// Fixups - The list of operands which are to be replaced.
1221 SmallVector<LSRFixup, 16> Fixups;
1223 /// Uses - The list of interesting uses.
1224 SmallVector<LSRUse, 16> Uses;
1226 /// RegUses - Track which uses use which register candidates.
1227 RegUseTracker RegUses;
1229 void OptimizeShadowIV();
1230 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1231 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1232 bool OptimizeLoopTermCond();
1234 void CollectInterestingTypesAndFactors();
1235 void CollectFixupsAndInitialFormulae();
1237 LSRFixup &getNewFixup() {
1238 Fixups.push_back(LSRFixup());
1239 return Fixups.back();
1242 // Support for sharing of LSRUses between LSRFixups.
1243 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1246 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1247 LSRUse::KindType Kind, const Type *AccessTy);
1249 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1250 LSRUse::KindType Kind,
1251 const Type *AccessTy);
1254 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1255 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1256 void CountRegisters(const Formula &F, size_t LUIdx);
1257 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1259 void CollectLoopInvariantFixupsAndFormulae();
1261 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1262 unsigned Depth = 0);
1263 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1264 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1265 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1266 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1267 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1268 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1269 void GenerateCrossUseConstantOffsets();
1270 void GenerateAllReuseFormulae();
1272 void FilterOutUndesirableDedicatedRegisters();
1274 size_t EstimateSearchSpaceComplexity() const;
1275 void NarrowSearchSpaceUsingHeuristics();
1277 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1279 SmallVectorImpl<const Formula *> &Workspace,
1280 const Cost &CurCost,
1281 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1282 DenseSet<const SCEV *> &VisitedRegs) const;
1283 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1285 BasicBlock::iterator
1286 HoistInsertPosition(BasicBlock::iterator IP,
1287 const SmallVectorImpl<Instruction *> &Inputs) const;
1288 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1290 const LSRUse &LU) const;
1292 Value *Expand(const LSRFixup &LF,
1294 BasicBlock::iterator IP,
1295 SCEVExpander &Rewriter,
1296 SmallVectorImpl<WeakVH> &DeadInsts) const;
1297 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1299 SCEVExpander &Rewriter,
1300 SmallVectorImpl<WeakVH> &DeadInsts,
1302 void Rewrite(const LSRFixup &LF,
1304 SCEVExpander &Rewriter,
1305 SmallVectorImpl<WeakVH> &DeadInsts,
1307 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1310 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1312 bool getChanged() const { return Changed; }
1314 void print_factors_and_types(raw_ostream &OS) const;
1315 void print_fixups(raw_ostream &OS) const;
1316 void print_uses(raw_ostream &OS) const;
1317 void print(raw_ostream &OS) const;
1323 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1324 /// inside the loop then try to eliminate the cast operation.
1325 void LSRInstance::OptimizeShadowIV() {
1326 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1327 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1330 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1331 UI != E; /* empty */) {
1332 IVUsers::const_iterator CandidateUI = UI;
1334 Instruction *ShadowUse = CandidateUI->getUser();
1335 const Type *DestTy = NULL;
1337 /* If shadow use is a int->float cast then insert a second IV
1338 to eliminate this cast.
1340 for (unsigned i = 0; i < n; ++i)
1346 for (unsigned i = 0; i < n; ++i, ++d)
1349 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1350 DestTy = UCast->getDestTy();
1351 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1352 DestTy = SCast->getDestTy();
1353 if (!DestTy) continue;
1356 // If target does not support DestTy natively then do not apply
1357 // this transformation.
1358 EVT DVT = TLI->getValueType(DestTy);
1359 if (!TLI->isTypeLegal(DVT)) continue;
1362 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1364 if (PH->getNumIncomingValues() != 2) continue;
1366 const Type *SrcTy = PH->getType();
1367 int Mantissa = DestTy->getFPMantissaWidth();
1368 if (Mantissa == -1) continue;
1369 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1372 unsigned Entry, Latch;
1373 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1381 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1382 if (!Init) continue;
1383 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1385 BinaryOperator *Incr =
1386 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1387 if (!Incr) continue;
1388 if (Incr->getOpcode() != Instruction::Add
1389 && Incr->getOpcode() != Instruction::Sub)
1392 /* Initialize new IV, double d = 0.0 in above example. */
1393 ConstantInt *C = NULL;
1394 if (Incr->getOperand(0) == PH)
1395 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1396 else if (Incr->getOperand(1) == PH)
1397 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1403 // Ignore negative constants, as the code below doesn't handle them
1404 // correctly. TODO: Remove this restriction.
1405 if (!C->getValue().isStrictlyPositive()) continue;
1407 /* Add new PHINode. */
1408 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1410 /* create new increment. '++d' in above example. */
1411 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1412 BinaryOperator *NewIncr =
1413 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1414 Instruction::FAdd : Instruction::FSub,
1415 NewPH, CFP, "IV.S.next.", Incr);
1417 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1418 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1420 /* Remove cast operation */
1421 ShadowUse->replaceAllUsesWith(NewPH);
1422 ShadowUse->eraseFromParent();
1427 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1428 /// set the IV user and stride information and return true, otherwise return
1430 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1431 IVStrideUse *&CondUse) {
1432 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1433 if (UI->getUser() == Cond) {
1434 // NOTE: we could handle setcc instructions with multiple uses here, but
1435 // InstCombine does it as well for simple uses, it's not clear that it
1436 // occurs enough in real life to handle.
1443 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1444 /// a max computation.
1446 /// This is a narrow solution to a specific, but acute, problem. For loops
1452 /// } while (++i < n);
1454 /// the trip count isn't just 'n', because 'n' might not be positive. And
1455 /// unfortunately this can come up even for loops where the user didn't use
1456 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1457 /// will commonly be lowered like this:
1463 /// } while (++i < n);
1466 /// and then it's possible for subsequent optimization to obscure the if
1467 /// test in such a way that indvars can't find it.
1469 /// When indvars can't find the if test in loops like this, it creates a
1470 /// max expression, which allows it to give the loop a canonical
1471 /// induction variable:
1474 /// max = n < 1 ? 1 : n;
1477 /// } while (++i != max);
1479 /// Canonical induction variables are necessary because the loop passes
1480 /// are designed around them. The most obvious example of this is the
1481 /// LoopInfo analysis, which doesn't remember trip count values. It
1482 /// expects to be able to rediscover the trip count each time it is
1483 /// needed, and it does this using a simple analysis that only succeeds if
1484 /// the loop has a canonical induction variable.
1486 /// However, when it comes time to generate code, the maximum operation
1487 /// can be quite costly, especially if it's inside of an outer loop.
1489 /// This function solves this problem by detecting this type of loop and
1490 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1491 /// the instructions for the maximum computation.
1493 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1494 // Check that the loop matches the pattern we're looking for.
1495 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1496 Cond->getPredicate() != CmpInst::ICMP_NE)
1499 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1500 if (!Sel || !Sel->hasOneUse()) return Cond;
1502 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1503 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1505 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1507 // Add one to the backedge-taken count to get the trip count.
1508 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
1509 if (IterationCount != SE.getSCEV(Sel)) return Cond;
1511 // Check for a max calculation that matches the pattern. There's no check
1512 // for ICMP_ULE here because the comparison would be with zero, which
1513 // isn't interesting.
1514 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1515 const SCEVNAryExpr *Max = 0;
1516 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1517 Pred = ICmpInst::ICMP_SLE;
1519 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1520 Pred = ICmpInst::ICMP_SLT;
1522 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1523 Pred = ICmpInst::ICMP_ULT;
1530 // To handle a max with more than two operands, this optimization would
1531 // require additional checking and setup.
1532 if (Max->getNumOperands() != 2)
1535 const SCEV *MaxLHS = Max->getOperand(0);
1536 const SCEV *MaxRHS = Max->getOperand(1);
1538 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1539 // for a comparison with 1. For <= and >=, a comparison with zero.
1541 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1544 // Check the relevant induction variable for conformance to
1546 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
1547 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1548 if (!AR || !AR->isAffine() ||
1549 AR->getStart() != One ||
1550 AR->getStepRecurrence(SE) != One)
1553 assert(AR->getLoop() == L &&
1554 "Loop condition operand is an addrec in a different loop!");
1556 // Check the right operand of the select, and remember it, as it will
1557 // be used in the new comparison instruction.
1559 if (ICmpInst::isTrueWhenEqual(Pred)) {
1560 // Look for n+1, and grab n.
1561 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1562 if (isa<ConstantInt>(BO->getOperand(1)) &&
1563 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1564 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1565 NewRHS = BO->getOperand(0);
1566 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1567 if (isa<ConstantInt>(BO->getOperand(1)) &&
1568 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1569 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1570 NewRHS = BO->getOperand(0);
1573 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
1574 NewRHS = Sel->getOperand(1);
1575 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
1576 NewRHS = Sel->getOperand(2);
1578 llvm_unreachable("Max doesn't match expected pattern!");
1580 // Determine the new comparison opcode. It may be signed or unsigned,
1581 // and the original comparison may be either equality or inequality.
1582 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1583 Pred = CmpInst::getInversePredicate(Pred);
1585 // Ok, everything looks ok to change the condition into an SLT or SGE and
1586 // delete the max calculation.
1588 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1590 // Delete the max calculation instructions.
1591 Cond->replaceAllUsesWith(NewCond);
1592 CondUse->setUser(NewCond);
1593 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1594 Cond->eraseFromParent();
1595 Sel->eraseFromParent();
1596 if (Cmp->use_empty())
1597 Cmp->eraseFromParent();
1601 /// OptimizeLoopTermCond - Change loop terminating condition to use the
1602 /// postinc iv when possible.
1604 LSRInstance::OptimizeLoopTermCond() {
1605 SmallPtrSet<Instruction *, 4> PostIncs;
1607 BasicBlock *LatchBlock = L->getLoopLatch();
1608 SmallVector<BasicBlock*, 8> ExitingBlocks;
1609 L->getExitingBlocks(ExitingBlocks);
1611 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1612 BasicBlock *ExitingBlock = ExitingBlocks[i];
1614 // Get the terminating condition for the loop if possible. If we
1615 // can, we want to change it to use a post-incremented version of its
1616 // induction variable, to allow coalescing the live ranges for the IV into
1617 // one register value.
1619 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1622 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1623 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1626 // Search IVUsesByStride to find Cond's IVUse if there is one.
1627 IVStrideUse *CondUse = 0;
1628 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1629 if (!FindIVUserForCond(Cond, CondUse))
1632 // If the trip count is computed in terms of a max (due to ScalarEvolution
1633 // being unable to find a sufficient guard, for example), change the loop
1634 // comparison to use SLT or ULT instead of NE.
1635 // One consequence of doing this now is that it disrupts the count-down
1636 // optimization. That's not always a bad thing though, because in such
1637 // cases it may still be worthwhile to avoid a max.
1638 Cond = OptimizeMax(Cond, CondUse);
1640 // If this exiting block dominates the latch block, it may also use
1641 // the post-inc value if it won't be shared with other uses.
1642 // Check for dominance.
1643 if (!DT.dominates(ExitingBlock, LatchBlock))
1646 // Conservatively avoid trying to use the post-inc value in non-latch
1647 // exits if there may be pre-inc users in intervening blocks.
1648 if (LatchBlock != ExitingBlock)
1649 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1650 // Test if the use is reachable from the exiting block. This dominator
1651 // query is a conservative approximation of reachability.
1652 if (&*UI != CondUse &&
1653 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1654 // Conservatively assume there may be reuse if the quotient of their
1655 // strides could be a legal scale.
1656 const SCEV *A = IU.getStride(*CondUse, L);
1657 const SCEV *B = IU.getStride(*UI, L);
1658 if (!A || !B) continue;
1659 if (SE.getTypeSizeInBits(A->getType()) !=
1660 SE.getTypeSizeInBits(B->getType())) {
1661 if (SE.getTypeSizeInBits(A->getType()) >
1662 SE.getTypeSizeInBits(B->getType()))
1663 B = SE.getSignExtendExpr(B, A->getType());
1665 A = SE.getSignExtendExpr(A, B->getType());
1667 if (const SCEVConstant *D =
1668 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
1669 // Stride of one or negative one can have reuse with non-addresses.
1670 if (D->getValue()->isOne() ||
1671 D->getValue()->isAllOnesValue())
1672 goto decline_post_inc;
1673 // Avoid weird situations.
1674 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1675 D->getValue()->getValue().isMinSignedValue())
1676 goto decline_post_inc;
1677 // Without TLI, assume that any stride might be valid, and so any
1678 // use might be shared.
1680 goto decline_post_inc;
1681 // Check for possible scaled-address reuse.
1682 const Type *AccessTy = getAccessType(UI->getUser());
1683 TargetLowering::AddrMode AM;
1684 AM.Scale = D->getValue()->getSExtValue();
1685 if (TLI->isLegalAddressingMode(AM, AccessTy))
1686 goto decline_post_inc;
1687 AM.Scale = -AM.Scale;
1688 if (TLI->isLegalAddressingMode(AM, AccessTy))
1689 goto decline_post_inc;
1693 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
1696 // It's possible for the setcc instruction to be anywhere in the loop, and
1697 // possible for it to have multiple users. If it is not immediately before
1698 // the exiting block branch, move it.
1699 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1700 if (Cond->hasOneUse()) {
1701 Cond->moveBefore(TermBr);
1703 // Clone the terminating condition and insert into the loopend.
1704 ICmpInst *OldCond = Cond;
1705 Cond = cast<ICmpInst>(Cond->clone());
1706 Cond->setName(L->getHeader()->getName() + ".termcond");
1707 ExitingBlock->getInstList().insert(TermBr, Cond);
1709 // Clone the IVUse, as the old use still exists!
1710 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
1711 TermBr->replaceUsesOfWith(OldCond, Cond);
1715 // If we get to here, we know that we can transform the setcc instruction to
1716 // use the post-incremented version of the IV, allowing us to coalesce the
1717 // live ranges for the IV correctly.
1718 CondUse->transformToPostInc(L);
1721 PostIncs.insert(Cond);
1725 // Determine an insertion point for the loop induction variable increment. It
1726 // must dominate all the post-inc comparisons we just set up, and it must
1727 // dominate the loop latch edge.
1728 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1729 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1730 E = PostIncs.end(); I != E; ++I) {
1732 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1734 if (BB == (*I)->getParent())
1735 IVIncInsertPos = *I;
1736 else if (BB != IVIncInsertPos->getParent())
1737 IVIncInsertPos = BB->getTerminator();
1744 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1745 LSRUse::KindType Kind, const Type *AccessTy) {
1746 int64_t NewMinOffset = LU.MinOffset;
1747 int64_t NewMaxOffset = LU.MaxOffset;
1748 const Type *NewAccessTy = AccessTy;
1750 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1751 // something conservative, however this can pessimize in the case that one of
1752 // the uses will have all its uses outside the loop, for example.
1753 if (LU.Kind != Kind)
1755 // Conservatively assume HasBaseReg is true for now.
1756 if (NewOffset < LU.MinOffset) {
1757 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1758 Kind, AccessTy, TLI))
1760 NewMinOffset = NewOffset;
1761 } else if (NewOffset > LU.MaxOffset) {
1762 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1763 Kind, AccessTy, TLI))
1765 NewMaxOffset = NewOffset;
1767 // Check for a mismatched access type, and fall back conservatively as needed.
1768 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1769 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
1772 LU.MinOffset = NewMinOffset;
1773 LU.MaxOffset = NewMaxOffset;
1774 LU.AccessTy = NewAccessTy;
1775 if (NewOffset != LU.Offsets.back())
1776 LU.Offsets.push_back(NewOffset);
1780 /// getUse - Return an LSRUse index and an offset value for a fixup which
1781 /// needs the given expression, with the given kind and optional access type.
1782 /// Either reuse an existing use or create a new one, as needed.
1783 std::pair<size_t, int64_t>
1784 LSRInstance::getUse(const SCEV *&Expr,
1785 LSRUse::KindType Kind, const Type *AccessTy) {
1786 const SCEV *Copy = Expr;
1787 int64_t Offset = ExtractImmediate(Expr, SE);
1789 // Basic uses can't accept any offset, for example.
1790 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
1795 std::pair<UseMapTy::iterator, bool> P =
1796 UseMap.insert(std::make_pair(Expr, 0));
1798 // A use already existed with this base.
1799 size_t LUIdx = P.first->second;
1800 LSRUse &LU = Uses[LUIdx];
1801 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1803 return std::make_pair(LUIdx, Offset);
1806 // Create a new use.
1807 size_t LUIdx = Uses.size();
1808 P.first->second = LUIdx;
1809 Uses.push_back(LSRUse(Kind, AccessTy));
1810 LSRUse &LU = Uses[LUIdx];
1812 // We don't need to track redundant offsets, but we don't need to go out
1813 // of our way here to avoid them.
1814 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1815 LU.Offsets.push_back(Offset);
1817 LU.MinOffset = Offset;
1818 LU.MaxOffset = Offset;
1819 return std::make_pair(LUIdx, Offset);
1822 void LSRInstance::CollectInterestingTypesAndFactors() {
1823 SmallSetVector<const SCEV *, 4> Strides;
1825 // Collect interesting types and strides.
1826 SmallVector<const SCEV *, 4> Worklist;
1827 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1828 const SCEV *Expr = IU.getExpr(*UI);
1830 // Collect interesting types.
1831 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
1833 // Add strides for mentioned loops.
1834 Worklist.push_back(Expr);
1836 const SCEV *S = Worklist.pop_back_val();
1837 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1838 Strides.insert(AR->getStepRecurrence(SE));
1839 Worklist.push_back(AR->getStart());
1840 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1841 Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1843 } while (!Worklist.empty());
1846 // Compute interesting factors from the set of interesting strides.
1847 for (SmallSetVector<const SCEV *, 4>::const_iterator
1848 I = Strides.begin(), E = Strides.end(); I != E; ++I)
1849 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1850 next(I); NewStrideIter != E; ++NewStrideIter) {
1851 const SCEV *OldStride = *I;
1852 const SCEV *NewStride = *NewStrideIter;
1854 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1855 SE.getTypeSizeInBits(NewStride->getType())) {
1856 if (SE.getTypeSizeInBits(OldStride->getType()) >
1857 SE.getTypeSizeInBits(NewStride->getType()))
1858 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1860 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1862 if (const SCEVConstant *Factor =
1863 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1865 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1866 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1867 } else if (const SCEVConstant *Factor =
1868 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1871 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1872 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1876 // If all uses use the same type, don't bother looking for truncation-based
1878 if (Types.size() == 1)
1881 DEBUG(print_factors_and_types(dbgs()));
1884 void LSRInstance::CollectFixupsAndInitialFormulae() {
1885 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1887 LSRFixup &LF = getNewFixup();
1888 LF.UserInst = UI->getUser();
1889 LF.OperandValToReplace = UI->getOperandValToReplace();
1890 LF.PostIncLoops = UI->getPostIncLoops();
1892 LSRUse::KindType Kind = LSRUse::Basic;
1893 const Type *AccessTy = 0;
1894 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1895 Kind = LSRUse::Address;
1896 AccessTy = getAccessType(LF.UserInst);
1899 const SCEV *S = IU.getExpr(*UI);
1901 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1902 // (N - i == 0), and this allows (N - i) to be the expression that we work
1903 // with rather than just N or i, so we can consider the register
1904 // requirements for both N and i at the same time. Limiting this code to
1905 // equality icmps is not a problem because all interesting loops use
1906 // equality icmps, thanks to IndVarSimplify.
1907 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1908 if (CI->isEquality()) {
1909 // Swap the operands if needed to put the OperandValToReplace on the
1910 // left, for consistency.
1911 Value *NV = CI->getOperand(1);
1912 if (NV == LF.OperandValToReplace) {
1913 CI->setOperand(1, CI->getOperand(0));
1914 CI->setOperand(0, NV);
1917 // x == y --> x - y == 0
1918 const SCEV *N = SE.getSCEV(NV);
1919 if (N->isLoopInvariant(L)) {
1920 Kind = LSRUse::ICmpZero;
1921 S = SE.getMinusSCEV(N, S);
1924 // -1 and the negations of all interesting strides (except the negation
1925 // of -1) are now also interesting.
1926 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1927 if (Factors[i] != -1)
1928 Factors.insert(-(uint64_t)Factors[i]);
1932 // Set up the initial formula for this use.
1933 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1935 LF.Offset = P.second;
1936 LSRUse &LU = Uses[LF.LUIdx];
1937 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
1939 // If this is the first use of this LSRUse, give it a formula.
1940 if (LU.Formulae.empty()) {
1941 InsertInitialFormula(S, LU, LF.LUIdx);
1942 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1946 DEBUG(print_fixups(dbgs()));
1950 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
1952 F.InitialMatch(S, L, SE, DT);
1953 bool Inserted = InsertFormula(LU, LUIdx, F);
1954 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1958 LSRInstance::InsertSupplementalFormula(const SCEV *S,
1959 LSRUse &LU, size_t LUIdx) {
1961 F.BaseRegs.push_back(S);
1962 F.AM.HasBaseReg = true;
1963 bool Inserted = InsertFormula(LU, LUIdx, F);
1964 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1967 /// CountRegisters - Note which registers are used by the given formula,
1968 /// updating RegUses.
1969 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1971 RegUses.CountRegister(F.ScaledReg, LUIdx);
1972 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1973 E = F.BaseRegs.end(); I != E; ++I)
1974 RegUses.CountRegister(*I, LUIdx);
1977 /// InsertFormula - If the given formula has not yet been inserted, add it to
1978 /// the list, and return true. Return false otherwise.
1979 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1980 if (!LU.InsertFormula(F))
1983 CountRegisters(F, LUIdx);
1987 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1988 /// loop-invariant values which we're tracking. These other uses will pin these
1989 /// values in registers, making them less profitable for elimination.
1990 /// TODO: This currently misses non-constant addrec step registers.
1991 /// TODO: Should this give more weight to users inside the loop?
1993 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1994 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1995 SmallPtrSet<const SCEV *, 8> Inserted;
1997 while (!Worklist.empty()) {
1998 const SCEV *S = Worklist.pop_back_val();
2000 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
2001 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
2002 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2003 Worklist.push_back(C->getOperand());
2004 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2005 Worklist.push_back(D->getLHS());
2006 Worklist.push_back(D->getRHS());
2007 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2008 if (!Inserted.insert(U)) continue;
2009 const Value *V = U->getValue();
2010 if (const Instruction *Inst = dyn_cast<Instruction>(V))
2011 if (L->contains(Inst)) continue;
2012 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
2014 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2015 // Ignore non-instructions.
2018 // Ignore instructions in other functions (as can happen with
2020 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
2022 // Ignore instructions not dominated by the loop.
2023 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2024 UserInst->getParent() :
2025 cast<PHINode>(UserInst)->getIncomingBlock(
2026 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2027 if (!DT.dominates(L->getHeader(), UseBB))
2029 // Ignore uses which are part of other SCEV expressions, to avoid
2030 // analyzing them multiple times.
2031 if (SE.isSCEVable(UserInst->getType())) {
2032 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2033 // If the user is a no-op, look through to its uses.
2034 if (!isa<SCEVUnknown>(UserS))
2038 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2042 // Ignore icmp instructions which are already being analyzed.
2043 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2044 unsigned OtherIdx = !UI.getOperandNo();
2045 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2046 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
2050 LSRFixup &LF = getNewFixup();
2051 LF.UserInst = const_cast<Instruction *>(UserInst);
2052 LF.OperandValToReplace = UI.getUse();
2053 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2055 LF.Offset = P.second;
2056 LSRUse &LU = Uses[LF.LUIdx];
2057 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2058 InsertSupplementalFormula(U, LU, LF.LUIdx);
2059 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2066 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
2067 /// separate registers. If C is non-null, multiply each subexpression by C.
2068 static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2069 SmallVectorImpl<const SCEV *> &Ops,
2070 ScalarEvolution &SE) {
2071 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2072 // Break out add operands.
2073 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2075 CollectSubexprs(*I, C, Ops, SE);
2077 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2078 // Split a non-zero base out of an addrec.
2079 if (!AR->getStart()->isZero()) {
2080 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
2081 AR->getStepRecurrence(SE),
2082 AR->getLoop()), C, Ops, SE);
2083 CollectSubexprs(AR->getStart(), C, Ops, SE);
2086 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2087 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2088 if (Mul->getNumOperands() == 2)
2089 if (const SCEVConstant *Op0 =
2090 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2091 CollectSubexprs(Mul->getOperand(1),
2092 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2098 // Otherwise use the value itself.
2099 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2102 /// GenerateReassociations - Split out subexpressions from adds and the bases of
2104 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2107 // Arbitrarily cap recursion to protect compile time.
2108 if (Depth >= 3) return;
2110 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2111 const SCEV *BaseReg = Base.BaseRegs[i];
2113 SmallVector<const SCEV *, 8> AddOps;
2114 CollectSubexprs(BaseReg, 0, AddOps, SE);
2115 if (AddOps.size() == 1) continue;
2117 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2118 JE = AddOps.end(); J != JE; ++J) {
2119 // Don't pull a constant into a register if the constant could be folded
2120 // into an immediate field.
2121 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2122 Base.getNumRegs() > 1,
2123 LU.Kind, LU.AccessTy, TLI, SE))
2126 // Collect all operands except *J.
2127 SmallVector<const SCEV *, 8> InnerAddOps;
2128 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2129 KE = AddOps.end(); K != KE; ++K)
2131 InnerAddOps.push_back(*K);
2133 // Don't leave just a constant behind in a register if the constant could
2134 // be folded into an immediate field.
2135 if (InnerAddOps.size() == 1 &&
2136 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2137 Base.getNumRegs() > 1,
2138 LU.Kind, LU.AccessTy, TLI, SE))
2141 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2142 if (InnerSum->isZero())
2145 F.BaseRegs[i] = InnerSum;
2146 F.BaseRegs.push_back(*J);
2147 if (InsertFormula(LU, LUIdx, F))
2148 // If that formula hadn't been seen before, recurse to find more like
2150 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2155 /// GenerateCombinations - Generate a formula consisting of all of the
2156 /// loop-dominating registers added into a single register.
2157 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
2159 // This method is only interesting on a plurality of registers.
2160 if (Base.BaseRegs.size() <= 1) return;
2164 SmallVector<const SCEV *, 4> Ops;
2165 for (SmallVectorImpl<const SCEV *>::const_iterator
2166 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2167 const SCEV *BaseReg = *I;
2168 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2169 !BaseReg->hasComputableLoopEvolution(L))
2170 Ops.push_back(BaseReg);
2172 F.BaseRegs.push_back(BaseReg);
2174 if (Ops.size() > 1) {
2175 const SCEV *Sum = SE.getAddExpr(Ops);
2176 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2177 // opportunity to fold something. For now, just ignore such cases
2178 // rather than proceed with zero in a register.
2179 if (!Sum->isZero()) {
2180 F.BaseRegs.push_back(Sum);
2181 (void)InsertFormula(LU, LUIdx, F);
2186 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2187 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2189 // We can't add a symbolic offset if the address already contains one.
2190 if (Base.AM.BaseGV) return;
2192 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2193 const SCEV *G = Base.BaseRegs[i];
2194 GlobalValue *GV = ExtractSymbol(G, SE);
2195 if (G->isZero() || !GV)
2199 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2200 LU.Kind, LU.AccessTy, TLI))
2203 (void)InsertFormula(LU, LUIdx, F);
2207 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2208 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2210 // TODO: For now, just add the min and max offset, because it usually isn't
2211 // worthwhile looking at everything inbetween.
2212 SmallVector<int64_t, 4> Worklist;
2213 Worklist.push_back(LU.MinOffset);
2214 if (LU.MaxOffset != LU.MinOffset)
2215 Worklist.push_back(LU.MaxOffset);
2217 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2218 const SCEV *G = Base.BaseRegs[i];
2220 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2221 E = Worklist.end(); I != E; ++I) {
2223 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2224 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2225 LU.Kind, LU.AccessTy, TLI)) {
2226 F.BaseRegs[i] = SE.getAddExpr(G, SE.getConstant(G->getType(), *I));
2228 (void)InsertFormula(LU, LUIdx, F);
2232 int64_t Imm = ExtractImmediate(G, SE);
2233 if (G->isZero() || Imm == 0)
2236 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2237 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2238 LU.Kind, LU.AccessTy, TLI))
2241 (void)InsertFormula(LU, LUIdx, F);
2245 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2246 /// the comparison. For example, x == y -> x*c == y*c.
2247 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2249 if (LU.Kind != LSRUse::ICmpZero) return;
2251 // Determine the integer type for the base formula.
2252 const Type *IntTy = Base.getType();
2254 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2256 // Don't do this if there is more than one offset.
2257 if (LU.MinOffset != LU.MaxOffset) return;
2259 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2261 // Check each interesting stride.
2262 for (SmallSetVector<int64_t, 8>::const_iterator
2263 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2264 int64_t Factor = *I;
2267 // Check that the multiplication doesn't overflow.
2268 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2270 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2271 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
2274 // Check that multiplying with the use offset doesn't overflow.
2275 int64_t Offset = LU.MinOffset;
2276 if (Offset == INT64_MIN && Factor == -1)
2278 Offset = (uint64_t)Offset * Factor;
2279 if (Offset / Factor != LU.MinOffset)
2282 // Check that this scale is legal.
2283 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2286 // Compensate for the use having MinOffset built into it.
2287 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2289 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2291 // Check that multiplying with each base register doesn't overflow.
2292 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2293 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2294 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2298 // Check that multiplying with the scaled register doesn't overflow.
2300 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2301 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2305 // If we make it here and it's legal, add it.
2306 (void)InsertFormula(LU, LUIdx, F);
2311 /// GenerateScales - Generate stride factor reuse formulae by making use of
2312 /// scaled-offset address modes, for example.
2313 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2315 // Determine the integer type for the base formula.
2316 const Type *IntTy = Base.getType();
2319 // If this Formula already has a scaled register, we can't add another one.
2320 if (Base.AM.Scale != 0) return;
2322 // Check each interesting stride.
2323 for (SmallSetVector<int64_t, 8>::const_iterator
2324 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2325 int64_t Factor = *I;
2327 Base.AM.Scale = Factor;
2328 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2329 // Check whether this scale is going to be legal.
2330 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2331 LU.Kind, LU.AccessTy, TLI)) {
2332 // As a special-case, handle special out-of-loop Basic users specially.
2333 // TODO: Reconsider this special case.
2334 if (LU.Kind == LSRUse::Basic &&
2335 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2336 LSRUse::Special, LU.AccessTy, TLI) &&
2337 LU.AllFixupsOutsideLoop)
2338 LU.Kind = LSRUse::Special;
2342 // For an ICmpZero, negating a solitary base register won't lead to
2344 if (LU.Kind == LSRUse::ICmpZero &&
2345 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2347 // For each addrec base reg, apply the scale, if possible.
2348 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2349 if (const SCEVAddRecExpr *AR =
2350 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2351 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2352 if (FactorS->isZero())
2354 // Divide out the factor, ignoring high bits, since we'll be
2355 // scaling the value back up in the end.
2356 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
2357 // TODO: This could be optimized to avoid all the copying.
2359 F.ScaledReg = Quotient;
2360 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2361 F.BaseRegs.pop_back();
2362 (void)InsertFormula(LU, LUIdx, F);
2368 /// GenerateTruncates - Generate reuse formulae from different IV types.
2369 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2371 // This requires TargetLowering to tell us which truncates are free.
2374 // Don't bother truncating symbolic values.
2375 if (Base.AM.BaseGV) return;
2377 // Determine the integer type for the base formula.
2378 const Type *DstTy = Base.getType();
2380 DstTy = SE.getEffectiveSCEVType(DstTy);
2382 for (SmallSetVector<const Type *, 4>::const_iterator
2383 I = Types.begin(), E = Types.end(); I != E; ++I) {
2384 const Type *SrcTy = *I;
2385 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2388 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2389 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2390 JE = F.BaseRegs.end(); J != JE; ++J)
2391 *J = SE.getAnyExtendExpr(*J, SrcTy);
2393 // TODO: This assumes we've done basic processing on all uses and
2394 // have an idea what the register usage is.
2395 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2398 (void)InsertFormula(LU, LUIdx, F);
2405 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
2406 /// defer modifications so that the search phase doesn't have to worry about
2407 /// the data structures moving underneath it.
2411 const SCEV *OrigReg;
2413 WorkItem(size_t LI, int64_t I, const SCEV *R)
2414 : LUIdx(LI), Imm(I), OrigReg(R) {}
2416 void print(raw_ostream &OS) const;
2422 void WorkItem::print(raw_ostream &OS) const {
2423 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2424 << " , add offset " << Imm;
2427 void WorkItem::dump() const {
2428 print(errs()); errs() << '\n';
2431 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2432 /// distance apart and try to form reuse opportunities between them.
2433 void LSRInstance::GenerateCrossUseConstantOffsets() {
2434 // Group the registers by their value without any added constant offset.
2435 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2436 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2438 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2439 SmallVector<const SCEV *, 8> Sequence;
2440 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2442 const SCEV *Reg = *I;
2443 int64_t Imm = ExtractImmediate(Reg, SE);
2444 std::pair<RegMapTy::iterator, bool> Pair =
2445 Map.insert(std::make_pair(Reg, ImmMapTy()));
2447 Sequence.push_back(Reg);
2448 Pair.first->second.insert(std::make_pair(Imm, *I));
2449 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2452 // Now examine each set of registers with the same base value. Build up
2453 // a list of work to do and do the work in a separate step so that we're
2454 // not adding formulae and register counts while we're searching.
2455 SmallVector<WorkItem, 32> WorkItems;
2456 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2457 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2458 E = Sequence.end(); I != E; ++I) {
2459 const SCEV *Reg = *I;
2460 const ImmMapTy &Imms = Map.find(Reg)->second;
2462 // It's not worthwhile looking for reuse if there's only one offset.
2463 if (Imms.size() == 1)
2466 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2467 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2469 dbgs() << ' ' << J->first;
2472 // Examine each offset.
2473 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2475 const SCEV *OrigReg = J->second;
2477 int64_t JImm = J->first;
2478 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2480 if (!isa<SCEVConstant>(OrigReg) &&
2481 UsedByIndicesMap[Reg].count() == 1) {
2482 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2486 // Conservatively examine offsets between this orig reg a few selected
2488 ImmMapTy::const_iterator OtherImms[] = {
2489 Imms.begin(), prior(Imms.end()),
2490 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2492 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2493 ImmMapTy::const_iterator M = OtherImms[i];
2494 if (M == J || M == JE) continue;
2496 // Compute the difference between the two.
2497 int64_t Imm = (uint64_t)JImm - M->first;
2498 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2499 LUIdx = UsedByIndices.find_next(LUIdx))
2500 // Make a memo of this use, offset, and register tuple.
2501 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2502 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
2509 UsedByIndicesMap.clear();
2510 UniqueItems.clear();
2512 // Now iterate through the worklist and add new formulae.
2513 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2514 E = WorkItems.end(); I != E; ++I) {
2515 const WorkItem &WI = *I;
2516 size_t LUIdx = WI.LUIdx;
2517 LSRUse &LU = Uses[LUIdx];
2518 int64_t Imm = WI.Imm;
2519 const SCEV *OrigReg = WI.OrigReg;
2521 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2522 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2523 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2525 // TODO: Use a more targeted data structure.
2526 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2527 Formula F = LU.Formulae[L];
2528 // Use the immediate in the scaled register.
2529 if (F.ScaledReg == OrigReg) {
2530 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2531 Imm * (uint64_t)F.AM.Scale;
2532 // Don't create 50 + reg(-50).
2533 if (F.referencesReg(SE.getSCEV(
2534 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2537 NewF.AM.BaseOffs = Offs;
2538 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2539 LU.Kind, LU.AccessTy, TLI))
2541 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2543 // If the new scale is a constant in a register, and adding the constant
2544 // value to the immediate would produce a value closer to zero than the
2545 // immediate itself, then the formula isn't worthwhile.
2546 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2547 if (C->getValue()->getValue().isNegative() !=
2548 (NewF.AM.BaseOffs < 0) &&
2549 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2550 .ule(abs64(NewF.AM.BaseOffs)))
2554 (void)InsertFormula(LU, LUIdx, NewF);
2556 // Use the immediate in a base register.
2557 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2558 const SCEV *BaseReg = F.BaseRegs[N];
2559 if (BaseReg != OrigReg)
2562 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2563 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2564 LU.Kind, LU.AccessTy, TLI))
2566 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2568 // If the new formula has a constant in a register, and adding the
2569 // constant value to the immediate would produce a value closer to
2570 // zero than the immediate itself, then the formula isn't worthwhile.
2571 for (SmallVectorImpl<const SCEV *>::const_iterator
2572 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2574 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2575 if (C->getValue()->getValue().isNegative() !=
2576 (NewF.AM.BaseOffs < 0) &&
2577 C->getValue()->getValue().abs()
2578 .ule(abs64(NewF.AM.BaseOffs)))
2582 (void)InsertFormula(LU, LUIdx, NewF);
2591 /// GenerateAllReuseFormulae - Generate formulae for each use.
2593 LSRInstance::GenerateAllReuseFormulae() {
2594 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
2595 // queries are more precise.
2596 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2597 LSRUse &LU = Uses[LUIdx];
2598 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2599 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2600 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2601 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2603 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2604 LSRUse &LU = Uses[LUIdx];
2605 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2606 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2607 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2608 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2609 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2610 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2611 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2612 GenerateScales(LU, LUIdx, LU.Formulae[i]);
2614 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2615 LSRUse &LU = Uses[LUIdx];
2616 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2617 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2620 GenerateCrossUseConstantOffsets();
2623 /// If their are multiple formulae with the same set of registers used
2624 /// by other uses, pick the best one and delete the others.
2625 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2627 bool Changed = false;
2630 // Collect the best formula for each unique set of shared registers. This
2631 // is reset for each use.
2632 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2634 BestFormulaeTy BestFormulae;
2636 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2637 LSRUse &LU = Uses[LUIdx];
2638 FormulaSorter Sorter(L, LU, SE, DT);
2639 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << "\n");
2642 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2643 FIdx != NumForms; ++FIdx) {
2644 Formula &F = LU.Formulae[FIdx];
2646 SmallVector<const SCEV *, 2> Key;
2647 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2648 JE = F.BaseRegs.end(); J != JE; ++J) {
2649 const SCEV *Reg = *J;
2650 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2654 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2655 Key.push_back(F.ScaledReg);
2656 // Unstable sort by host order ok, because this is only used for
2658 std::sort(Key.begin(), Key.end());
2660 std::pair<BestFormulaeTy::const_iterator, bool> P =
2661 BestFormulae.insert(std::make_pair(Key, FIdx));
2663 Formula &Best = LU.Formulae[P.first->second];
2664 if (Sorter.operator()(F, Best))
2666 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
2668 " in favor of formula "; Best.print(dbgs());
2673 LU.DeleteFormula(F);
2682 LU.RecomputeRegs(LUIdx, RegUses);
2684 // Reset this to prepare for the next use.
2685 BestFormulae.clear();
2688 DEBUG(if (Changed) {
2690 "After filtering out undesirable candidates:\n";
2695 // This is a rough guess that seems to work fairly well.
2696 static const size_t ComplexityLimit = UINT16_MAX;
2698 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2699 /// solutions the solver might have to consider. It almost never considers
2700 /// this many solutions because it prune the search space, but the pruning
2701 /// isn't always sufficient.
2702 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
2704 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2705 E = Uses.end(); I != E; ++I) {
2706 size_t FSize = I->Formulae.size();
2707 if (FSize >= ComplexityLimit) {
2708 Power = ComplexityLimit;
2712 if (Power >= ComplexityLimit)
2718 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
2719 /// formulae to choose from, use some rough heuristics to prune down the number
2720 /// of formulae. This keeps the main solver from taking an extraordinary amount
2721 /// of time in some worst-case scenarios.
2722 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2723 SmallPtrSet<const SCEV *, 4> Taken;
2724 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2725 // Ok, we have too many of formulae on our hands to conveniently handle.
2726 // Use a rough heuristic to thin out the list.
2727 DEBUG(dbgs() << "The search space is too complex.\n");
2729 // Pick the register which is used by the most LSRUses, which is likely
2730 // to be a good reuse register candidate.
2731 const SCEV *Best = 0;
2732 unsigned BestNum = 0;
2733 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2735 const SCEV *Reg = *I;
2736 if (Taken.count(Reg))
2741 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2742 if (Count > BestNum) {
2749 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2750 << " will yield profitable reuse.\n");
2753 // In any use with formulae which references this register, delete formulae
2754 // which don't reference it.
2755 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2756 LSRUse &LU = Uses[LUIdx];
2757 if (!LU.Regs.count(Best)) continue;
2760 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2761 Formula &F = LU.Formulae[i];
2762 if (!F.referencesReg(Best)) {
2763 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2764 LU.DeleteFormula(F);
2768 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
2774 LU.RecomputeRegs(LUIdx, RegUses);
2777 DEBUG(dbgs() << "After pre-selection:\n";
2778 print_uses(dbgs()));
2782 /// SolveRecurse - This is the recursive solver.
2783 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2785 SmallVectorImpl<const Formula *> &Workspace,
2786 const Cost &CurCost,
2787 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2788 DenseSet<const SCEV *> &VisitedRegs) const {
2791 // - use more aggressive filtering
2792 // - sort the formula so that the most profitable solutions are found first
2793 // - sort the uses too
2795 // - don't compute a cost, and then compare. compare while computing a cost
2797 // - track register sets with SmallBitVector
2799 const LSRUse &LU = Uses[Workspace.size()];
2801 // If this use references any register that's already a part of the
2802 // in-progress solution, consider it a requirement that a formula must
2803 // reference that register in order to be considered. This prunes out
2804 // unprofitable searching.
2805 SmallSetVector<const SCEV *, 4> ReqRegs;
2806 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2807 E = CurRegs.end(); I != E; ++I)
2808 if (LU.Regs.count(*I))
2811 bool AnySatisfiedReqRegs = false;
2812 SmallPtrSet<const SCEV *, 16> NewRegs;
2815 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2816 E = LU.Formulae.end(); I != E; ++I) {
2817 const Formula &F = *I;
2819 // Ignore formulae which do not use any of the required registers.
2820 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2821 JE = ReqRegs.end(); J != JE; ++J) {
2822 const SCEV *Reg = *J;
2823 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2824 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2828 AnySatisfiedReqRegs = true;
2830 // Evaluate the cost of the current formula. If it's already worse than
2831 // the current best, prune the search at that point.
2834 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2835 if (NewCost < SolutionCost) {
2836 Workspace.push_back(&F);
2837 if (Workspace.size() != Uses.size()) {
2838 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2839 NewRegs, VisitedRegs);
2840 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2841 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2843 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2844 dbgs() << ". Regs:";
2845 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2846 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2847 dbgs() << ' ' << **I;
2850 SolutionCost = NewCost;
2851 Solution = Workspace;
2853 Workspace.pop_back();
2858 // If none of the formulae had all of the required registers, relax the
2859 // constraint so that we don't exclude all formulae.
2860 if (!AnySatisfiedReqRegs) {
2861 assert(!ReqRegs.empty() && "Solver failed even without required registers");
2867 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2868 SmallVector<const Formula *, 8> Workspace;
2870 SolutionCost.Loose();
2872 SmallPtrSet<const SCEV *, 16> CurRegs;
2873 DenseSet<const SCEV *> VisitedRegs;
2874 Workspace.reserve(Uses.size());
2876 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2877 CurRegs, VisitedRegs);
2879 // Ok, we've now made all our decisions.
2880 DEBUG(dbgs() << "\n"
2881 "The chosen solution requires "; SolutionCost.print(dbgs());
2883 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2885 Uses[i].print(dbgs());
2888 Solution[i]->print(dbgs());
2893 /// getImmediateDominator - A handy utility for the specific DominatorTree
2894 /// query that we need here.
2896 static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2897 DomTreeNode *Node = DT.getNode(BB);
2898 if (!Node) return 0;
2899 Node = Node->getIDom();
2900 if (!Node) return 0;
2901 return Node->getBlock();
2904 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
2905 /// the dominator tree far as we can go while still being dominated by the
2906 /// input positions. This helps canonicalize the insert position, which
2907 /// encourages sharing.
2908 BasicBlock::iterator
2909 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
2910 const SmallVectorImpl<Instruction *> &Inputs)
2913 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
2914 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
2917 for (BasicBlock *Rung = IP->getParent(); ; Rung = IDom) {
2918 IDom = getImmediateDominator(Rung, DT);
2919 if (!IDom) return IP;
2921 // Don't climb into a loop though.
2922 const Loop *IDomLoop = LI.getLoopFor(IDom);
2923 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
2924 if (IDomDepth <= IPLoopDepth &&
2925 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
2929 bool AllDominate = true;
2930 Instruction *BetterPos = 0;
2931 Instruction *Tentative = IDom->getTerminator();
2932 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2933 E = Inputs.end(); I != E; ++I) {
2934 Instruction *Inst = *I;
2935 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2936 AllDominate = false;
2939 // Attempt to find an insert position in the middle of the block,
2940 // instead of at the end, so that it can be used for other expansions.
2941 if (IDom == Inst->getParent() &&
2942 (!BetterPos || DT.dominates(BetterPos, Inst)))
2943 BetterPos = llvm::next(BasicBlock::iterator(Inst));
2956 /// AdjustInsertPositionForExpand - Determine an input position which will be
2957 /// dominated by the operands and which will dominate the result.
2958 BasicBlock::iterator
2959 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2961 const LSRUse &LU) const {
2962 // Collect some instructions which must be dominated by the
2963 // expanding replacement. These must be dominated by any operands that
2964 // will be required in the expansion.
2965 SmallVector<Instruction *, 4> Inputs;
2966 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2967 Inputs.push_back(I);
2968 if (LU.Kind == LSRUse::ICmpZero)
2969 if (Instruction *I =
2970 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2971 Inputs.push_back(I);
2972 if (LF.PostIncLoops.count(L)) {
2973 if (LF.isUseFullyOutsideLoop(L))
2974 Inputs.push_back(L->getLoopLatch()->getTerminator());
2976 Inputs.push_back(IVIncInsertPos);
2978 // The expansion must also be dominated by the increment positions of any
2979 // loops it for which it is using post-inc mode.
2980 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
2981 E = LF.PostIncLoops.end(); I != E; ++I) {
2982 const Loop *PIL = *I;
2983 if (PIL == L) continue;
2985 // Be dominated by the loop exit.
2986 SmallVector<BasicBlock *, 4> ExitingBlocks;
2987 PIL->getExitingBlocks(ExitingBlocks);
2988 if (!ExitingBlocks.empty()) {
2989 BasicBlock *BB = ExitingBlocks[0];
2990 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
2991 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
2992 Inputs.push_back(BB->getTerminator());
2996 // Then, climb up the immediate dominator tree as far as we can go while
2997 // still being dominated by the input positions.
2998 IP = HoistInsertPosition(IP, Inputs);
3000 // Don't insert instructions before PHI nodes.
3001 while (isa<PHINode>(IP)) ++IP;
3003 // Ignore debug intrinsics.
3004 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
3009 Value *LSRInstance::Expand(const LSRFixup &LF,
3011 BasicBlock::iterator IP,
3012 SCEVExpander &Rewriter,
3013 SmallVectorImpl<WeakVH> &DeadInsts) const {
3014 const LSRUse &LU = Uses[LF.LUIdx];
3016 // Determine an input position which will be dominated by the operands and
3017 // which will dominate the result.
3018 IP = AdjustInsertPositionForExpand(IP, LF, LU);
3020 // Inform the Rewriter if we have a post-increment use, so that it can
3021 // perform an advantageous expansion.
3022 Rewriter.setPostInc(LF.PostIncLoops);
3024 // This is the type that the user actually needs.
3025 const Type *OpTy = LF.OperandValToReplace->getType();
3026 // This will be the type that we'll initially expand to.
3027 const Type *Ty = F.getType();
3029 // No type known; just expand directly to the ultimate type.
3031 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3032 // Expand directly to the ultimate type if it's the right size.
3034 // This is the type to do integer arithmetic in.
3035 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3037 // Build up a list of operands to add together to form the full base.
3038 SmallVector<const SCEV *, 8> Ops;
3040 // Expand the BaseRegs portion.
3041 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3042 E = F.BaseRegs.end(); I != E; ++I) {
3043 const SCEV *Reg = *I;
3044 assert(!Reg->isZero() && "Zero allocated in a base register!");
3046 // If we're expanding for a post-inc user, make the post-inc adjustment.
3047 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3048 Reg = TransformForPostIncUse(Denormalize, Reg,
3049 LF.UserInst, LF.OperandValToReplace,
3052 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3055 // Flush the operand list to suppress SCEVExpander hoisting.
3057 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3059 Ops.push_back(SE.getUnknown(FullV));
3062 // Expand the ScaledReg portion.
3063 Value *ICmpScaledV = 0;
3064 if (F.AM.Scale != 0) {
3065 const SCEV *ScaledS = F.ScaledReg;
3067 // If we're expanding for a post-inc user, make the post-inc adjustment.
3068 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3069 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3070 LF.UserInst, LF.OperandValToReplace,
3073 if (LU.Kind == LSRUse::ICmpZero) {
3074 // An interesting way of "folding" with an icmp is to use a negated
3075 // scale, which we'll implement by inserting it into the other operand
3077 assert(F.AM.Scale == -1 &&
3078 "The only scale supported by ICmpZero uses is -1!");
3079 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3081 // Otherwise just expand the scaled register and an explicit scale,
3082 // which is expected to be matched as part of the address.
3083 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3084 ScaledS = SE.getMulExpr(ScaledS,
3085 SE.getConstant(ScaledS->getType(), F.AM.Scale));
3086 Ops.push_back(ScaledS);
3088 // Flush the operand list to suppress SCEVExpander hoisting.
3089 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3091 Ops.push_back(SE.getUnknown(FullV));
3095 // Expand the GV portion.
3097 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3099 // Flush the operand list to suppress SCEVExpander hoisting.
3100 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3102 Ops.push_back(SE.getUnknown(FullV));
3105 // Expand the immediate portion.
3106 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3108 if (LU.Kind == LSRUse::ICmpZero) {
3109 // The other interesting way of "folding" with an ICmpZero is to use a
3110 // negated immediate.
3112 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3114 Ops.push_back(SE.getUnknown(ICmpScaledV));
3115 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3118 // Just add the immediate values. These again are expected to be matched
3119 // as part of the address.
3120 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
3124 // Emit instructions summing all the operands.
3125 const SCEV *FullS = Ops.empty() ?
3126 SE.getConstant(IntTy, 0) :
3128 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3130 // We're done expanding now, so reset the rewriter.
3131 Rewriter.clearPostInc();
3133 // An ICmpZero Formula represents an ICmp which we're handling as a
3134 // comparison against zero. Now that we've expanded an expression for that
3135 // form, update the ICmp's other operand.
3136 if (LU.Kind == LSRUse::ICmpZero) {
3137 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3138 DeadInsts.push_back(CI->getOperand(1));
3139 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3140 "a scale at the same time!");
3141 if (F.AM.Scale == -1) {
3142 if (ICmpScaledV->getType() != OpTy) {
3144 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3146 ICmpScaledV, OpTy, "tmp", CI);
3149 CI->setOperand(1, ICmpScaledV);
3151 assert(F.AM.Scale == 0 &&
3152 "ICmp does not support folding a global value and "
3153 "a scale at the same time!");
3154 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3156 if (C->getType() != OpTy)
3157 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3161 CI->setOperand(1, C);
3168 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3169 /// of their operands effectively happens in their predecessor blocks, so the
3170 /// expression may need to be expanded in multiple places.
3171 void LSRInstance::RewriteForPHI(PHINode *PN,
3174 SCEVExpander &Rewriter,
3175 SmallVectorImpl<WeakVH> &DeadInsts,
3177 DenseMap<BasicBlock *, Value *> Inserted;
3178 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3179 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3180 BasicBlock *BB = PN->getIncomingBlock(i);
3182 // If this is a critical edge, split the edge so that we do not insert
3183 // the code on all predecessor/successor paths. We do this unless this
3184 // is the canonical backedge for this loop, which complicates post-inc
3186 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3187 !isa<IndirectBrInst>(BB->getTerminator()) &&
3188 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3189 // Split the critical edge.
3190 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3192 // If PN is outside of the loop and BB is in the loop, we want to
3193 // move the block to be immediately before the PHI block, not
3194 // immediately after BB.
3195 if (L->contains(BB) && !L->contains(PN))
3196 NewBB->moveBefore(PN->getParent());
3198 // Splitting the edge can reduce the number of PHI entries we have.
3199 e = PN->getNumIncomingValues();
3201 i = PN->getBasicBlockIndex(BB);
3204 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3205 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3207 PN->setIncomingValue(i, Pair.first->second);
3209 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
3211 // If this is reuse-by-noop-cast, insert the noop cast.
3212 const Type *OpTy = LF.OperandValToReplace->getType();
3213 if (FullV->getType() != OpTy)
3215 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3217 FullV, LF.OperandValToReplace->getType(),
3218 "tmp", BB->getTerminator());
3220 PN->setIncomingValue(i, FullV);
3221 Pair.first->second = FullV;
3226 /// Rewrite - Emit instructions for the leading candidate expression for this
3227 /// LSRUse (this is called "expanding"), and update the UserInst to reference
3228 /// the newly expanded value.
3229 void LSRInstance::Rewrite(const LSRFixup &LF,
3231 SCEVExpander &Rewriter,
3232 SmallVectorImpl<WeakVH> &DeadInsts,
3234 // First, find an insertion point that dominates UserInst. For PHI nodes,
3235 // find the nearest block which dominates all the relevant uses.
3236 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
3237 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
3239 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
3241 // If this is reuse-by-noop-cast, insert the noop cast.
3242 const Type *OpTy = LF.OperandValToReplace->getType();
3243 if (FullV->getType() != OpTy) {
3245 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3246 FullV, OpTy, "tmp", LF.UserInst);
3250 // Update the user. ICmpZero is handled specially here (for now) because
3251 // Expand may have updated one of the operands of the icmp already, and
3252 // its new value may happen to be equal to LF.OperandValToReplace, in
3253 // which case doing replaceUsesOfWith leads to replacing both operands
3254 // with the same value. TODO: Reorganize this.
3255 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3256 LF.UserInst->setOperand(0, FullV);
3258 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3261 DeadInsts.push_back(LF.OperandValToReplace);
3265 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3267 // Keep track of instructions we may have made dead, so that
3268 // we can remove them after we are done working.
3269 SmallVector<WeakVH, 16> DeadInsts;
3271 SCEVExpander Rewriter(SE);
3272 Rewriter.disableCanonicalMode();
3273 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3275 // Expand the new value definitions and update the users.
3276 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3277 size_t LUIdx = Fixups[i].LUIdx;
3279 Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
3284 // Clean up after ourselves. This must be done before deleting any
3288 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3291 LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3292 : IU(P->getAnalysis<IVUsers>()),
3293 SE(P->getAnalysis<ScalarEvolution>()),
3294 DT(P->getAnalysis<DominatorTree>()),
3295 LI(P->getAnalysis<LoopInfo>()),
3296 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
3298 // If LoopSimplify form is not available, stay out of trouble.
3299 if (!L->isLoopSimplifyForm()) return;
3301 // If there's no interesting work to be done, bail early.
3302 if (IU.empty()) return;
3304 DEBUG(dbgs() << "\nLSR on loop ";
3305 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3308 /// OptimizeShadowIV - If IV is used in a int-to-float cast
3309 /// inside the loop then try to eliminate the cast operation.
3312 // Change loop terminating condition to use the postinc iv when possible.
3313 Changed |= OptimizeLoopTermCond();
3315 CollectInterestingTypesAndFactors();
3316 CollectFixupsAndInitialFormulae();
3317 CollectLoopInvariantFixupsAndFormulae();
3319 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3320 print_uses(dbgs()));
3322 // Now use the reuse data to generate a bunch of interesting ways
3323 // to formulate the values needed for the uses.
3324 GenerateAllReuseFormulae();
3326 DEBUG(dbgs() << "\n"
3327 "After generating reuse formulae:\n";
3328 print_uses(dbgs()));
3330 FilterOutUndesirableDedicatedRegisters();
3331 NarrowSearchSpaceUsingHeuristics();
3333 SmallVector<const Formula *, 8> Solution;
3335 assert(Solution.size() == Uses.size() && "Malformed solution!");
3337 // Release memory that is no longer needed.
3343 // Formulae should be legal.
3344 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3345 E = Uses.end(); I != E; ++I) {
3346 const LSRUse &LU = *I;
3347 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3348 JE = LU.Formulae.end(); J != JE; ++J)
3349 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3350 LU.Kind, LU.AccessTy, TLI) &&
3351 "Illegal formula generated!");
3355 // Now that we've decided what we want, make it so.
3356 ImplementSolution(Solution, P);
3359 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3360 if (Factors.empty() && Types.empty()) return;
3362 OS << "LSR has identified the following interesting factors and types: ";
3365 for (SmallSetVector<int64_t, 8>::const_iterator
3366 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3367 if (!First) OS << ", ";
3372 for (SmallSetVector<const Type *, 4>::const_iterator
3373 I = Types.begin(), E = Types.end(); I != E; ++I) {
3374 if (!First) OS << ", ";
3376 OS << '(' << **I << ')';
3381 void LSRInstance::print_fixups(raw_ostream &OS) const {
3382 OS << "LSR is examining the following fixup sites:\n";
3383 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3384 E = Fixups.end(); I != E; ++I) {
3385 const LSRFixup &LF = *I;
3392 void LSRInstance::print_uses(raw_ostream &OS) const {
3393 OS << "LSR is examining the following uses:\n";
3394 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3395 E = Uses.end(); I != E; ++I) {
3396 const LSRUse &LU = *I;
3400 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3401 JE = LU.Formulae.end(); J != JE; ++J) {
3409 void LSRInstance::print(raw_ostream &OS) const {
3410 print_factors_and_types(OS);
3415 void LSRInstance::dump() const {
3416 print(errs()); errs() << '\n';
3421 class LoopStrengthReduce : public LoopPass {
3422 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3423 /// transformation profitability.
3424 const TargetLowering *const TLI;
3427 static char ID; // Pass ID, replacement for typeid
3428 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3431 bool runOnLoop(Loop *L, LPPassManager &LPM);
3432 void getAnalysisUsage(AnalysisUsage &AU) const;
3437 char LoopStrengthReduce::ID = 0;
3438 static RegisterPass<LoopStrengthReduce>
3439 X("loop-reduce", "Loop Strength Reduction");
3441 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3442 return new LoopStrengthReduce(TLI);
3445 LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3446 : LoopPass(&ID), TLI(tli) {}
3448 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3449 // We split critical edges, so we change the CFG. However, we do update
3450 // many analyses if they are around.
3451 AU.addPreservedID(LoopSimplifyID);
3452 AU.addPreserved("domfrontier");
3454 AU.addRequired<LoopInfo>();
3455 AU.addPreserved<LoopInfo>();
3456 AU.addRequiredID(LoopSimplifyID);
3457 AU.addRequired<DominatorTree>();
3458 AU.addPreserved<DominatorTree>();
3459 AU.addRequired<ScalarEvolution>();
3460 AU.addPreserved<ScalarEvolution>();
3461 AU.addRequired<IVUsers>();
3462 AU.addPreserved<IVUsers>();
3465 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3466 bool Changed = false;
3468 // Run the main LSR transformation.
3469 Changed |= LSRInstance(TLI, L, this).getChanged();
3471 // At this point, it is worth checking to see if any recurrence PHIs are also
3472 // dead, so that we can remove them as well.
3473 Changed |= DeleteDeadPHIs(L->getHeader());