llvm.org GIT mirror llvm / 572645c
Reapply the new LoopStrengthReduction code, with compile time and bug fixes, and with improved heuristics for analyzing foreign-loop addrecs. This change also flattens IVUsers, eliminating the stride-oriented groupings, which makes it easier to work with. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@95975 91177308-0d34-0410-b5e6-96231b3b80d8 Dan Gohman 9 years ago
35 changed file(s) with 3606 addition(s) and 2772 deletion(s). Raw diff Collapse all Expand all
1515 #define LLVM_ANALYSIS_IVUSERS_H
1616
1717 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include
18 #include "llvm/Support/ValueHandle.h"
2119
2220 namespace llvm {
2321
2422 class DominatorTree;
2523 class Instruction;
2624 class Value;
27 struct IVUsersOfOneStride;
28
29 /// IVStrideUse - Keep track of one use of a strided induction variable, where
30 /// the stride is stored externally. The Offset member keeps track of the
31 /// offset from the IV, User is the actual user of the operand, and
32 /// 'OperandValToReplace' is the operand of the User that is the use.
25 class IVUsers;
26 class ScalarEvolution;
27 class SCEV;
28
29 /// IVStrideUse - Keep track of one use of a strided induction variable.
30 /// The Expr member keeps track of the expression, User is the actual user
31 /// instruction of the operand, and 'OperandValToReplace' is the operand of
32 /// the User that is the use.
3333 class IVStrideUse : public CallbackVH, public ilist_node {
3434 public:
35 IVStrideUse(IVUsersOfOneStride *parent,
36 const SCEV *offset,
35 IVStrideUse(IVUsers *P, const SCEV *S, const SCEV *Off,
3736 Instruction* U, Value *O)
38 : CallbackVH(U), Parent(parent), Offset(offset),
39 OperandValToReplace(O),
40 IsUseOfPostIncrementedValue(false) {
37 : CallbackVH(U), Parent(P), Stride(S), Offset(Off),
38 OperandValToReplace(O), IsUseOfPostIncrementedValue(false) {
4139 }
4240
4341 /// getUser - Return the user instruction for this use.
5048 setValPtr(NewUser);
5149 }
5250
53 /// getParent - Return a pointer to the IVUsersOfOneStride that owns
51 /// getParent - Return a pointer to the IVUsers that owns
5452 /// this IVStrideUse.
55 IVUsersOfOneStride *getParent() const { return Parent; }
53 IVUsers *getParent() const { return Parent; }
54
55 /// getStride - Return the expression for the stride for the use.
56 const SCEV *getStride() const { return Stride; }
57
58 /// setStride - Assign a new stride to this use.
59 void setStride(const SCEV *Val) {
60 Stride = Val;
61 }
5662
5763 /// getOffset - Return the offset to add to a theoeretical induction
5864 /// variable that starts at zero and counts up by the stride to compute
9197 }
9298
9399 private:
94 /// Parent - a pointer to the IVUsersOfOneStride that owns this IVStrideUse.
95 IVUsersOfOneStride *Parent;
100 /// Parent - a pointer to the IVUsers that owns this IVStrideUse.
101 IVUsers *Parent;
102
103 /// Stride - The stride for this use.
104 const SCEV *Stride;
96105
97106 /// Offset - The offset to add to the base induction expression.
98107 const SCEV *Offset;
137146 mutable ilist_node Sentinel;
138147 };
139148
140 /// IVUsersOfOneStride - This structure keeps track of all instructions that
141 /// have an operand that is based on the trip count multiplied by some stride.
142 struct IVUsersOfOneStride : public ilist_node {
143 private:
144 IVUsersOfOneStride(const IVUsersOfOneStride &I); // do not implement
145 void operator=(const IVUsersOfOneStride &I); // do not implement
146
147 public:
148 IVUsersOfOneStride() : Stride(0) {}
149
150 explicit IVUsersOfOneStride(const SCEV *stride) : Stride(stride) {}
151
152 /// Stride - The stride for all the contained IVStrideUses. This is
153 /// a constant for affine strides.
154 const SCEV *Stride;
155
156 /// Users - Keep track of all of the users of this stride as well as the
157 /// initial value and the operand that uses the IV.
158 ilist Users;
159
160 void addUser(const SCEV *Offset, Instruction *User, Value *Operand) {
161 Users.push_back(new IVStrideUse(this, Offset, User, Operand));
162 }
163
164 void removeUser(IVStrideUse *User) {
165 Users.erase(User);
166 }
167
168 void print(raw_ostream &OS) const;
169
170 /// dump - This method is used for debugging.
171 void dump() const;
172 };
173
174149 class IVUsers : public LoopPass {
175 friend class IVStrideUserVH;
150 friend class IVStrideUse;
176151 Loop *L;
177152 LoopInfo *LI;
178153 DominatorTree *DT;
181156
182157 /// IVUses - A list of all tracked IV uses of induction variable expressions
183158 /// we are interested in.
184 ilist IVUses;
185
186 public:
187 /// IVUsesByStride - A mapping from the strides in StrideOrder to the
188 /// uses in IVUses.
189 std::map IVUsesByStride;
190
191 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
192 /// We use this to iterate over the IVUsesByStride collection without being
193 /// dependent on random ordering of pointers in the process.
194 SmallVector StrideOrder;
195
196 private:
159 ilist IVUses;
160
197161 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
198162
199163 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
209173 /// return true. Otherwise, return false.
210174 bool AddUsersIfInteresting(Instruction *I);
211175
212 void AddUser(const SCEV *Stride, const SCEV *Offset,
213 Instruction *User, Value *Operand);
176 IVStrideUse &AddUser(const SCEV *Stride, const SCEV *Offset,
177 Instruction *User, Value *Operand);
214178
215179 /// getReplacementExpr - Return a SCEV expression which computes the
216180 /// value of the OperandValToReplace of the given IVStrideUse.
221185 /// isUseOfPostIncrementedValue flag.
222186 const SCEV *getCanonicalExpr(const IVStrideUse &U) const;
223187
188 typedef ilist::iterator iterator;
189 typedef ilist::const_iterator const_iterator;
190 iterator begin() { return IVUses.begin(); }
191 iterator end() { return IVUses.end(); }
192 const_iterator begin() const { return IVUses.begin(); }
193 const_iterator end() const { return IVUses.end(); }
194 bool empty() const { return IVUses.empty(); }
195
224196 void print(raw_ostream &OS, const Module* = 0) const;
225197
226198 /// dump - This method is used for debugging.
2626 /// and destroy it when finished to allow the release of the associated
2727 /// memory.
2828 class SCEVExpander : public SCEVVisitor {
29 public:
3029 ScalarEvolution &SE;
31
32 private:
3330 std::map, AssertingVH >
3431 InsertedExpressions;
3532 std::set InsertedValues;
3535 return new IVUsers();
3636 }
3737
38 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
39 /// subexpression that is an AddRec from a loop other than L. An outer loop
40 /// of L is OK, but not an inner loop nor a disjoint loop.
41 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
42 // This is very common, put it first.
43 if (isa(S))
44 return false;
45 if (const SCEVCommutativeExpr *AE = dyn_cast(S)) {
46 for (unsigned int i=0; i< AE->getNumOperands(); i++)
47 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
48 return true;
49 return false;
50 }
51 if (const SCEVAddRecExpr *AE = dyn_cast(S)) {
52 if (const Loop *newLoop = AE->getLoop()) {
53 if (newLoop == L)
54 return false;
55 // if newLoop is an outer loop of L, this is OK.
56 if (newLoop->contains(L))
57 return false;
38 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
39 /// separate registers.
40 static void CollectSubexprs(const SCEV *S,
41 SmallVectorImpl &Ops,
42 ScalarEvolution &SE) {
43 if (const SCEVAddExpr *Add = dyn_cast(S)) {
44 // Break out add operands.
45 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
46 I != E; ++I)
47 CollectSubexprs(*I, Ops, SE);
48 return;
49 } else if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
50 // Split a non-zero base out of an addrec.
51 if (!AR->getStart()->isZero()) {
52 CollectSubexprs(AR->getStart(), Ops, SE);
53 CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
54 AR->getStepRecurrence(SE),
55 AR->getLoop()), Ops, SE);
56 return;
5857 }
59 return true;
60 }
61 if (const SCEVUDivExpr *DE = dyn_cast(S))
62 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
63 containsAddRecFromDifferentLoop(DE->getRHS(), L);
64 #if 0
65 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
66 // need this when it is.
67 if (const SCEVSDivExpr *DE = dyn_cast(S))
68 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
69 containsAddRecFromDifferentLoop(DE->getRHS(), L);
70 #endif
71 if (const SCEVCastExpr *CE = dyn_cast(S))
72 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
73 return false;
58 }
59
60 // Otherwise use the value itself.
61 Ops.push_back(S);
7462 }
7563
7664 /// getSCEVStartAndStride - Compute the start and stride of this expression,
8977 if (const SCEVAddExpr *AE = dyn_cast(SH)) {
9078 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
9179 if (const SCEVAddRecExpr *AddRec =
92 dyn_cast(AE->getOperand(i))) {
93 if (AddRec->getLoop() == L)
94 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
95 else
96 return false; // Nested IV of some sort?
97 } else {
80 dyn_cast(AE->getOperand(i)))
81 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
82 else
9883 Start = SE->getAddExpr(Start, AE->getOperand(i));
99 }
10084 } else if (isa(SH)) {
10185 TheAddRec = SH;
10286 } else {
10387 return false; // not analyzable.
10488 }
10589
106 const SCEVAddRecExpr *AddRec = dyn_cast(TheAddRec);
107 if (!AddRec || AddRec->getLoop() != L) return false;
90 // Break down TheAddRec into its component parts.
91 SmallVector Subexprs;
92 CollectSubexprs(TheAddRec, Subexprs, *SE);
93
94 // Look for an addrec on the current loop among the parts.
95 const SCEV *AddRecStride = 0;
96 for (SmallVectorImpl::iterator I = Subexprs.begin(),
97 E = Subexprs.end(); I != E; ++I) {
98 const SCEV *S = *I;
99 if (const SCEVAddRecExpr *AR = dyn_cast(S))
100 if (AR->getLoop() == L) {
101 *I = AR->getStart();
102 AddRecStride = AR->getStepRecurrence(*SE);
103 break;
104 }
105 }
106 if (!AddRecStride)
107 return false;
108
109 // Add up everything else into a start value (which may not be
110 // loop-invariant).
111 const SCEV *AddRecStart = SE->getAddExpr(Subexprs);
108112
109113 // Use getSCEVAtScope to attempt to simplify other loops out of
110114 // the picture.
111 const SCEV *AddRecStart = AddRec->getStart();
112115 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
113 const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE);
114
115 // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other
116 // than an outer loop of the current loop, reject it. LSR has no concept of
117 // operating on more than one loop at a time so don't confuse it with such
118 // expressions.
119 if (containsAddRecFromDifferentLoop(AddRecStart, L))
120 return false;
121116
122117 Start = SE->getAddExpr(Start, AddRecStart);
123118
130125
131126 DEBUG(dbgs() << "[";
132127 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
133 dbgs() << "] Variable stride: " << *AddRec << "\n");
128 dbgs() << "] Variable stride: " << *AddRecStride << "\n");
134129 }
135130
136131 Stride = AddRecStride;
246241 }
247242
248243 if (AddUserToIVUsers) {
249 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
250 if (!StrideUses) { // First occurrence of this stride?
251 StrideOrder.push_back(Stride);
252 StrideUses = new IVUsersOfOneStride(Stride);
253 IVUses.push_back(StrideUses);
254 IVUsesByStride[Stride] = StrideUses;
255 }
256
257244 // Okay, we found a user that we cannot reduce. Analyze the instruction
258245 // and decide what to do with it. If we are a use inside of the loop, use
259246 // the value before incrementation, otherwise use it after incrementation.
261248 // The value used will be incremented by the stride more than we are
262249 // expecting, so subtract this off.
263250 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
264 StrideUses->addUser(NewStart, User, I);
265 StrideUses->Users.back().setIsUseOfPostIncrementedValue(true);
251 IVUses.push_back(new IVStrideUse(this, Stride, NewStart, User, I));
252 IVUses.back().setIsUseOfPostIncrementedValue(true);
266253 DEBUG(dbgs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
267254 } else {
268 StrideUses->addUser(Start, User, I);
255 IVUses.push_back(new IVStrideUse(this, Stride, Start, User, I));
269256 }
270257 }
271258 }
272259 return true;
273260 }
274261
275 void IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
276 Instruction *User, Value *Operand) {
277 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
278 if (!StrideUses) { // First occurrence of this stride?
279 StrideOrder.push_back(Stride);
280 StrideUses = new IVUsersOfOneStride(Stride);
281 IVUses.push_back(StrideUses);
282 IVUsesByStride[Stride] = StrideUses;
283 }
284 IVUsesByStride[Stride]->addUser(Offset, User, Operand);
262 IVStrideUse &IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
263 Instruction *User, Value *Operand) {
264 IVUses.push_back(new IVStrideUse(this, Stride, Offset, User, Operand));
265 return IVUses.back();
285266 }
286267
287268 IVUsers::IVUsers()
315296 /// value of the OperandValToReplace of the given IVStrideUse.
316297 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
317298 // Start with zero.
318 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
299 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
319300 // Create the basic add recurrence.
320 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
301 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
321302 // Add the offset in a separate step, because it may be loop-variant.
322303 RetVal = SE->getAddExpr(RetVal, U.getOffset());
323304 // For uses of post-incremented values, add an extra stride to compute
324305 // the actual replacement value.
325306 if (U.isUseOfPostIncrementedValue())
326 RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride);
307 RetVal = SE->getAddExpr(RetVal, U.getStride());
327308 return RetVal;
328309 }
329310
332313 /// isUseOfPostIncrementedValue flag.
333314 const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
334315 // Start with zero.
335 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
316 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
336317 // Create the basic add recurrence.
337 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
318 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
338319 // Add the offset in a separate step, because it may be loop-variant.
339320 RetVal = SE->getAddExpr(RetVal, U.getOffset());
340321 return RetVal;
357338 OS << ":\n";
358339
359340 IVUsersAsmAnnotator Annotator;
360 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
361 std::map::const_iterator SI =
362 IVUsesByStride.find(StrideOrder[Stride]);
363 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
364 OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n";
365
366 for (ilist::const_iterator UI = SI->second->Users.begin(),
367 E = SI->second->Users.end(); UI != E; ++UI) {
368 OS << " ";
369 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
370 OS << " = ";
371 OS << *getReplacementExpr(*UI);
372 if (UI->isUseOfPostIncrementedValue())
373 OS << " (post-inc)";
374 OS << " in ";
375 UI->getUser()->print(OS, &Annotator);
376 OS << '\n';
377 }
341 for (ilist::const_iterator UI = IVUses.begin(),
342 E = IVUses.end(); UI != E; ++UI) {
343 OS << " ";
344 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
345 OS << " = "
346 << *getReplacementExpr(*UI);
347 if (UI->isUseOfPostIncrementedValue())
348 OS << " (post-inc)";
349 OS << " in ";
350 UI->getUser()->print(OS, &Annotator);
351 OS << '\n';
378352 }
379353 }
380354
383357 }
384358
385359 void IVUsers::releaseMemory() {
386 IVUsesByStride.clear();
387 StrideOrder.clear();
388360 Processed.clear();
389361 IVUses.clear();
390362 }
391363
392364 void IVStrideUse::deleted() {
393365 // Remove this user from the list.
394 Parent->Users.erase(this);
366 Parent->IVUses.erase(this);
395367 // this now dangles!
396368 }
397
398 void IVUsersOfOneStride::print(raw_ostream &OS) const {
399 OS << "IV Users of one stride:\n";
400
401 if (Stride)
402 OS << " Stride: " << *Stride << '\n';
403
404 OS << " Users:\n";
405
406 unsigned Count = 1;
407
408 for (ilist::const_iterator
409 I = Users.begin(), E = Users.end(); I != E; ++I) {
410 const IVStrideUse &SU = *I;
411 OS << " " << Count++ << '\n';
412 OS << " Offset: " << *SU.getOffset() << '\n';
413 OS << " Instr: " << *SU << '\n';
414 }
415 }
416
417 void IVUsersOfOneStride::dump() const {
418 print(dbgs());
419 }
640640 // Reuse a previously-inserted PHI, if present.
641641 for (BasicBlock::iterator I = L->getHeader()->begin();
642642 PHINode *PN = dyn_cast(I); ++I)
643 if (isInsertedInstruction(PN) && SE.getSCEV(PN) == Normalized)
644 return PN;
643 if (SE.isSCEVable(PN->getType()) &&
644 (SE.getEffectiveSCEVType(PN->getType()) ==
645 SE.getEffectiveSCEVType(Normalized->getType())) &&
646 SE.getSCEV(PN) == Normalized)
647 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
648 // Remember this PHI, even in post-inc mode.
649 InsertedValues.insert(PN);
650 // Remember the increment.
651 Instruction *IncV =
652 cast(PN->getIncomingValueForBlock(LatchBlock)
653 ->stripPointerCasts());
654 rememberInstruction(IncV);
655 // Make sure the increment is where we want it. But don't move it
656 // down past a potential existing post-inc user.
657 if (L == IVIncInsertLoop && !SE.DT->dominates(IncV, IVIncInsertPos))
658 IncV->moveBefore(IVIncInsertPos);
659 return PN;
660 }
645661
646662 // Save the original insertion point so we can restore it when we're done.
647663 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1313 #include "llvm/Target/TargetMachine.h"
1414 #include "llvm/PassManager.h"
1515 #include "llvm/Pass.h"
16 #include "llvm/Analysis/Verifier.h"
1617 #include "llvm/Assembly/PrintModulePass.h"
1718 #include "llvm/CodeGen/AsmPrinter.h"
1819 #include "llvm/CodeGen/Passes.h"
233234 PM.add(createLoopStrengthReducePass(getTargetLowering()));
234235 if (PrintLSR)
235236 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
237 #ifndef NDEBUG
238 PM.add(createVerifierPass());
239 #endif
236240 }
237241
238242 // Turn exception handling constructs into something the code generators can
363363 if (ExitingBlock)
364364 NeedCannIV = true;
365365 }
366 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
367 const SCEV *Stride = IU->StrideOrder[i];
368 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
366 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
367 const Type *Ty =
368 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
369369 if (!LargestType ||
370370 SE->getTypeSizeInBits(Ty) >
371371 SE->getTypeSizeInBits(LargestType))
372372 LargestType = Ty;
373
374 std::map::iterator SI =
375 IU->IVUsesByStride.find(IU->StrideOrder[i]);
376 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
377
378 if (!SI->second->Users.empty())
379 NeedCannIV = true;
373 NeedCannIV = true;
380374 }
381375
382376 // Now that we know the largest of the induction variable expressions
454448 // add the offsets to the primary induction variable and cast, avoiding
455449 // the need for the code evaluation methods to insert induction variables
456450 // of different sizes.
457 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
458 const SCEV *Stride = IU->StrideOrder[i];
459
460 std::map::iterator SI =
461 IU->IVUsesByStride.find(IU->StrideOrder[i]);
462 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
463 ilist &List = SI->second->Users;
464 for (ilist::iterator UI = List.begin(),
465 E = List.end(); UI != E; ++UI) {
466 Value *Op = UI->getOperandValToReplace();
467 const Type *UseTy = Op->getType();
468 Instruction *User = UI->getUser();
469
470 // Compute the final addrec to expand into code.
471 const SCEV *AR = IU->getReplacementExpr(*UI);
472
473 // Evaluate the expression out of the loop, if possible.
474 if (!L->contains(UI->getUser())) {
475 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
476 if (ExitVal->isLoopInvariant(L))
477 AR = ExitVal;
478 }
479
480 // FIXME: It is an extremely bad idea to indvar substitute anything more
481 // complex than affine induction variables. Doing so will put expensive
482 // polynomial evaluations inside of the loop, and the str reduction pass
483 // currently can only reduce affine polynomials. For now just disable
484 // indvar subst on anything more complex than an affine addrec, unless
485 // it can be expanded to a trivial value.
486 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
487 continue;
488
489 // Determine the insertion point for this user. By default, insert
490 // immediately before the user. The SCEVExpander class will automatically
491 // hoist loop invariants out of the loop. For PHI nodes, there may be
492 // multiple uses, so compute the nearest common dominator for the
493 // incoming blocks.
494 Instruction *InsertPt = User;
495 if (PHINode *PHI = dyn_cast(InsertPt))
496 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
497 if (PHI->getIncomingValue(i) == Op) {
498 if (InsertPt == User)
499 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
500 else
501 InsertPt =
502 DT->findNearestCommonDominator(InsertPt->getParent(),
503 PHI->getIncomingBlock(i))
504 ->getTerminator();
505 }
506
507 // Now expand it into actual Instructions and patch it into place.
508 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
509
510 // Patch the new value into place.
511 if (Op->hasName())
512 NewVal->takeName(Op);
513 User->replaceUsesOfWith(Op, NewVal);
514 UI->setOperandValToReplace(NewVal);
515 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
516 << " into = " << *NewVal << "\n");
517 ++NumRemoved;
518 Changed = true;
519
520 // The old value may be dead now.
521 DeadInsts.push_back(Op);
451 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
452 const SCEV *Stride = UI->getStride();
453 Value *Op = UI->getOperandValToReplace();
454 const Type *UseTy = Op->getType();
455 Instruction *User = UI->getUser();
456
457 // Compute the final addrec to expand into code.
458 const SCEV *AR = IU->getReplacementExpr(*UI);
459
460 // Evaluate the expression out of the loop, if possible.
461 if (!L->contains(UI->getUser())) {
462 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
463 if (ExitVal->isLoopInvariant(L))
464 AR = ExitVal;
522465 }
466
467 // FIXME: It is an extremely bad idea to indvar substitute anything more
468 // complex than affine induction variables. Doing so will put expensive
469 // polynomial evaluations inside of the loop, and the str reduction pass
470 // currently can only reduce affine polynomials. For now just disable
471 // indvar subst on anything more complex than an affine addrec, unless
472 // it can be expanded to a trivial value.
473 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
474 continue;
475
476 // Determine the insertion point for this user. By default, insert
477 // immediately before the user. The SCEVExpander class will automatically
478 // hoist loop invariants out of the loop. For PHI nodes, there may be
479 // multiple uses, so compute the nearest common dominator for the
480 // incoming blocks.
481 Instruction *InsertPt = User;
482 if (PHINode *PHI = dyn_cast(InsertPt))
483 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
484 if (PHI->getIncomingValue(i) == Op) {
485 if (InsertPt == User)
486 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
487 else
488 InsertPt =
489 DT->findNearestCommonDominator(InsertPt->getParent(),
490 PHI->getIncomingBlock(i))
491 ->getTerminator();
492 }
493
494 // Now expand it into actual Instructions and patch it into place.
495 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
496
497 // Patch the new value into place.
498 if (Op->hasName())
499 NewVal->takeName(Op);
500 User->replaceUsesOfWith(Op, NewVal);
501 UI->setOperandValToReplace(NewVal);
502 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
503 << " into = " << *NewVal << "\n");
504 ++NumRemoved;
505 Changed = true;
506
507 // The old value may be dead now.
508 DeadInsts.push_back(Op);
523509 }
524510
525511 // Clear the rewriter cache, because values that are in the rewriter's cache
1616 // available on the target, and it performs a variety of other optimizations
1717 // related to loop induction variables.
1818 //
19 // Terminology note: this code has a lot of handling for "post-increment" or
20 // "post-inc" users. This is not talking about post-increment addressing modes;
21 // it is instead talking about code like this:
22 //
23 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
24 // ...
25 // %i.next = add %i, 1
26 // %c = icmp eq %i.next, %n
27 //
28 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
29 // it's useful to think about these as the same register, with some uses using
30 // the value of the register before the add and some using // it after. In this
31 // example, the icmp is a post-increment user, since it uses %i.next, which is
32 // the value of the induction variable after the increment. The other common
33 // case of post-increment users is users outside the loop.
34 //
35 // TODO: More sophistication in the way Formulae are generated and filtered.
36 //
37 // TODO: Handle multiple loops at a time.
38 //
39 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
40 // instead of a GlobalValue?
41 //
42 // TODO: When truncation is free, truncate ICmp users' operands to make it a
43 // smaller encoding (on x86 at least).
44 //
45 // TODO: When a negated register is used by an add (such as in a list of
46 // multiple base registers, or as the increment expression in an addrec),
47 // we may not actually need both reg and (-1 * reg) in registers; the
48 // negation can be implemented by using a sub instead of an add. The
49 // lack of support for taking this into consideration when making
50 // register pressure decisions is partly worked around by the "Special"
51 // use kind.
52 //
1953 //===----------------------------------------------------------------------===//
2054
2155 #define DEBUG_TYPE "loop-reduce"
2559 #include "llvm/IntrinsicInst.h"
2660 #include "llvm/DerivedTypes.h"
2761 #include "llvm/Analysis/IVUsers.h"
62 #include "llvm/Analysis/Dominators.h"
2863 #include "llvm/Analysis/LoopPass.h"
2964 #include "llvm/Analysis/ScalarEvolutionExpander.h"
30 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
3165 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3266 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/ADT/Statistic.h"
67 #include "llvm/ADT/SmallBitVector.h"
68 #include "llvm/ADT/SetVector.h"
69 #include "llvm/ADT/DenseSet.h"
3470 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/CommandLine.h"
3671 #include "llvm/Support/ValueHandle.h"
3772 #include "llvm/Support/raw_ostream.h"
3873 #include "llvm/Target/TargetLowering.h"
3974 #include
4075 using namespace llvm;
4176
42 STATISTIC(NumReduced , "Number of IV uses strength reduced");
43 STATISTIC(NumInserted, "Number of PHIs inserted");
44 STATISTIC(NumVariable, "Number of PHIs with variable strides");
45 STATISTIC(NumEliminated, "Number of strides eliminated");
46 STATISTIC(NumShadow, "Number of Shadow IVs optimized");
47 STATISTIC(NumImmSunk, "Number of common expr immediates sunk into uses");
48 STATISTIC(NumLoopCond, "Number of loop terminating conds optimized");
49 STATISTIC(NumCountZero, "Number of count iv optimized to count toward zero");
50
51 static cl::opt EnableFullLSRMode("enable-full-lsr",
52 cl::init(false),
53 cl::Hidden);
54
5577 namespace {
5678
57 struct BasedUser;
58
59 /// IVInfo - This structure keeps track of one IV expression inserted during
60 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
61 /// well as the PHI node and increment value created for rewrite.
62 struct IVExpr {
63 const SCEV *Stride;
64 const SCEV *Base;
65 PHINode *PHI;
66
67 IVExpr(const SCEV *const stride, const SCEV *const base, PHINode *phi)
68 : Stride(stride), Base(base), PHI(phi) {}
69 };
70
71 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
72 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
73 struct IVsOfOneStride {
74 std::vector IVs;
75
76 void addIV(const SCEV *const Stride, const SCEV *const Base, PHINode *PHI) {
77 IVs.push_back(IVExpr(Stride, Base, PHI));
78 }
79 };
80
81 class LoopStrengthReduce : public LoopPass {
82 IVUsers *IU;
83 ScalarEvolution *SE;
84 bool Changed;
85
86 /// IVsByStride - Keep track of all IVs that have been inserted for a
87 /// particular stride.
88 std::map IVsByStride;
89
90 /// DeadInsts - Keep track of instructions we may have made dead, so that
91 /// we can remove them after we are done working.
92 SmallVector DeadInsts;
93
94 /// TLI - Keep a pointer of a TargetLowering to consult for determining
95 /// transformation profitability.
96 const TargetLowering *TLI;
97
98 public:
99 static char ID; // Pass ID, replacement for typeid
100 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
101 LoopPass(&ID), TLI(tli) {}
102
103 bool runOnLoop(Loop *L, LPPassManager &LPM);
104
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 // We split critical edges, so we change the CFG. However, we do update
107 // many analyses if they are around.
108 AU.addPreservedID(LoopSimplifyID);
109 AU.addPreserved("loops");
110 AU.addPreserved("domfrontier");
111 AU.addPreserved("domtree");
112
113 AU.addRequiredID(LoopSimplifyID);
114 AU.addRequired();
115 AU.addPreserved();
116 AU.addRequired();
117 AU.addPreserved();
118 }
119
120 private:
121 void OptimizeIndvars(Loop *L);
122
123 /// OptimizeLoopTermCond - Change loop terminating condition to use the
124 /// postinc iv when possible.
125 void OptimizeLoopTermCond(Loop *L);
126
127 /// OptimizeShadowIV - If IV is used in a int-to-float cast
128 /// inside the loop then try to eliminate the cast opeation.
129 void OptimizeShadowIV(Loop *L);
130
131 /// OptimizeMax - Rewrite the loop's terminating condition
132 /// if it uses a max computation.
133 ICmpInst *OptimizeMax(Loop *L, ICmpInst *Cond,
134 IVStrideUse* &CondUse);
135
136 /// OptimizeLoopCountIV - If, after all sharing of IVs, the IV used for
137 /// deciding when to exit the loop is used only for that purpose, try to
138 /// rearrange things so it counts down to a test against zero.
139 bool OptimizeLoopCountIV(Loop *L);
140 bool OptimizeLoopCountIVOfStride(const SCEV* &Stride,
141 IVStrideUse* &CondUse, Loop *L);
142
143 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a
144 /// single stride of IV. All of the users may have different starting
145 /// values, and this may not be the only stride.
146 void StrengthReduceIVUsersOfStride(const SCEV *Stride,
147 IVUsersOfOneStride &Uses,
148 Loop *L);
149 void StrengthReduceIVUsers(Loop *L);
150
151 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
152 IVStrideUse* &CondUse,
153 const SCEV* &CondStride,
154 bool PostPass = false);
155
156 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
157 const SCEV* &CondStride);
158 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
159 const SCEV *CheckForIVReuse(bool, bool, bool, const SCEV *,
160 IVExpr&, const Type*,
161 const std::vector& UsersToProcess);
162 bool ValidScale(bool, int64_t,
163 const std::vector& UsersToProcess);
164 bool ValidOffset(bool, int64_t, int64_t,
165 const std::vector& UsersToProcess);
166 const SCEV *CollectIVUsers(const SCEV *Stride,
167 IVUsersOfOneStride &Uses,
168 Loop *L,
169 bool &AllUsesAreAddresses,
170 bool &AllUsesAreOutsideLoop,
171 std::vector &UsersToProcess);
172 bool StrideMightBeShared(const SCEV *Stride, Loop *L, bool CheckPreInc);
173 bool ShouldUseFullStrengthReductionMode(
174 const std::vector &UsersToProcess,
175 const Loop *L,
176 bool AllUsesAreAddresses,
177 const SCEV *Stride);
178 void PrepareToStrengthReduceFully(
179 std::vector &UsersToProcess,
180 const SCEV *Stride,
181 const SCEV *CommonExprs,
182 const Loop *L,
183 SCEVExpander &PreheaderRewriter);
184 void PrepareToStrengthReduceFromSmallerStride(
185 std::vector &UsersToProcess,
186 Value *CommonBaseV,
187 const IVExpr &ReuseIV,
188 Instruction *PreInsertPt);
189 void PrepareToStrengthReduceWithNewPhi(
190 std::vector &UsersToProcess,
191 const SCEV *Stride,
192 const SCEV *CommonExprs,
193 Value *CommonBaseV,
194 Instruction *IVIncInsertPt,
195 const Loop *L,
196 SCEVExpander &PreheaderRewriter);
197
198 void DeleteTriviallyDeadInstructions();
199 };
200 }
201
202 char LoopStrengthReduce::ID = 0;
203 static RegisterPass
204 X("loop-reduce", "Loop Strength Reduction");
205
206 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
207 return new LoopStrengthReduce(TLI);
208 }
209
210 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
211 /// specified set are trivially dead, delete them and see if this makes any of
212 /// their operands subsequently dead.
213 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
214 while (!DeadInsts.empty()) {
215 Instruction *I = dyn_cast_or_null(DeadInsts.pop_back_val());
216
217 if (I == 0 || !isInstructionTriviallyDead(I))
218 continue;
219
220 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
221 if (Instruction *U = dyn_cast(*OI)) {
222 *OI = 0;
223 if (U->use_empty())
224 DeadInsts.push_back(U);
79 /// RegSortData - This class holds data which is used to order reuse candidates.
80 class RegSortData {
81 public:
82 /// UsedByIndices - This represents the set of LSRUse indices which reference
83 /// a particular register.
84 SmallBitVector UsedByIndices;
85
86 RegSortData() {}
87
88 void print(raw_ostream &OS) const;
89 void dump() const;
90 };
91
92 }
93
94 void RegSortData::print(raw_ostream &OS) const {
95 OS << "[NumUses=" << UsedByIndices.count() << ']';
96 }
97
98 void RegSortData::dump() const {
99 print(errs()); errs() << '\n';
100 }
101
102 namespace {
103
104 /// RegUseTracker - Map register candidates to information about how they are
105 /// used.
106 class RegUseTracker {
107 typedef DenseMap RegUsesTy;
108
109 RegUsesTy RegUses;
110 SmallVector RegSequence;
111
112 public:
113 void CountRegister(const SCEV *Reg, size_t LUIdx);
114
115 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
116
117 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
118
119 void clear();
120
121 typedef SmallVectorImpl::iterator iterator;
122 typedef SmallVectorImpl::const_iterator const_iterator;
123 iterator begin() { return RegSequence.begin(); }
124 iterator end() { return RegSequence.end(); }
125 const_iterator begin() const { return RegSequence.begin(); }
126 const_iterator end() const { return RegSequence.end(); }
127 };
128
129 }
130
131 void
132 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
133 std::pair Pair =
134 RegUses.insert(std::make_pair(Reg, RegSortData()));
135 RegSortData &RSD = Pair.first->second;
136 if (Pair.second)
137 RegSequence.push_back(Reg);
138 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
139 RSD.UsedByIndices.set(LUIdx);
140 }
141
142 bool
143 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
144 if (!RegUses.count(Reg)) return false;
145 const SmallBitVector &UsedByIndices =
146 RegUses.find(Reg)->second.UsedByIndices;
147 int i = UsedByIndices.find_first();
148 if (i == -1) return false;
149 if ((size_t)i != LUIdx) return true;
150 return UsedByIndices.find_next(i) != -1;
151 }
152
153 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
154 RegUsesTy::const_iterator I = RegUses.find(Reg);
155 assert(I != RegUses.end() && "Unknown register!");
156 return I->second.UsedByIndices;
157 }
158
159 void RegUseTracker::clear() {
160 RegUses.clear();
161 RegSequence.clear();
162 }
163
164 namespace {
165
166 /// Formula - This class holds information that describes a formula for
167 /// computing satisfying a use. It may include broken-out immediates and scaled
168 /// registers.
169 struct Formula {
170 /// AM - This is used to represent complex addressing, as well as other kinds
171 /// of interesting uses.
172 TargetLowering::AddrMode AM;
173
174 /// BaseRegs - The list of "base" registers for this use. When this is
175 /// non-empty, AM.HasBaseReg should be set to true.
176 SmallVector BaseRegs;
177
178 /// ScaledReg - The 'scaled' register for this use. This should be non-null
179 /// when AM.Scale is not zero.
180 const SCEV *ScaledReg;
181
182 Formula() : ScaledReg(0) {}
183
184 void InitialMatch(const SCEV *S, Loop *L,
185 ScalarEvolution &SE, DominatorTree &DT);
186
187 unsigned getNumRegs() const;
188 const Type *getType() const;
189
190 bool referencesReg(const SCEV *S) const;
191 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
192 const RegUseTracker &RegUses) const;
193
194 void print(raw_ostream &OS) const;
195 void dump() const;
196 };
197
198 }
199
200 /// DoInitialMatch - Recurrsion helper for InitialMatch.
201 static void DoInitialMatch(const SCEV *S, Loop *L,
202 SmallVectorImpl &Good,
203 SmallVectorImpl &Bad,
204 ScalarEvolution &SE, DominatorTree &DT) {
205 // Collect expressions which properly dominate the loop header.
206 if (S->properlyDominates(L->getHeader(), &DT)) {
207 Good.push_back(S);
208 return;
209 }
210
211 // Look at add operands.
212 if (const SCEVAddExpr *Add = dyn_cast(S)) {
213 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
214 I != E; ++I)
215 DoInitialMatch(*I, L, Good, Bad, SE, DT);
216 return;
217 }
218
219 // Look at addrec operands.
220 if (const SCEVAddRecExpr *AR = dyn_cast(S))
221 if (!AR->getStart()->isZero()) {
222 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
223 DoInitialMatch(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
224 AR->getStepRecurrence(SE),
225 AR->getLoop()),
226 L, Good, Bad, SE, DT);
227 return;
228 }
229
230 // Handle a multiplication by -1 (negation) if it didn't fold.
231 if (const SCEVMulExpr *Mul = dyn_cast(S))
232 if (Mul->getOperand(0)->isAllOnesValue()) {
233 SmallVector Ops(Mul->op_begin()+1, Mul->op_end());
234 const SCEV *NewMul = SE.getMulExpr(Ops);
235
236 SmallVector MyGood;
237 SmallVector MyBad;
238 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
239 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
240 SE.getEffectiveSCEVType(NewMul->getType())));
241 for (SmallVectorImpl::const_iterator I = MyGood.begin(),
242 E = MyGood.end(); I != E; ++I)
243 Good.push_back(SE.getMulExpr(NegOne, *I));
244 for (SmallVectorImpl::const_iterator I = MyBad.begin(),
245 E = MyBad.end(); I != E; ++I)
246 Bad.push_back(SE.getMulExpr(NegOne, *I));
247 return;
248 }
249
250 // Ok, we can't do anything interesting. Just stuff the whole thing into a
251 // register and hope for the best.
252 Bad.push_back(S);
253 }
254
255 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
256 /// attempting to keep all loop-invariant and loop-computable values in a
257 /// single base register.
258 void Formula::InitialMatch(const SCEV *S, Loop *L,
259 ScalarEvolution &SE, DominatorTree &DT) {
260 SmallVector Good;
261 SmallVector Bad;
262 DoInitialMatch(S, L, Good, Bad, SE, DT);
263 if (!Good.empty()) {
264 BaseRegs.push_back(SE.getAddExpr(Good));
265 AM.HasBaseReg = true;
266 }
267 if (!Bad.empty()) {
268 BaseRegs.push_back(SE.getAddExpr(Bad));
269 AM.HasBaseReg = true;
270 }
271 }
272
273 /// getNumRegs - Return the total number of register operands used by this
274 /// formula. This does not include register uses implied by non-constant
275 /// addrec strides.
276 unsigned Formula::getNumRegs() const {
277 return !!ScaledReg + BaseRegs.size();
278 }
279
280 /// getType - Return the type of this formula, if it has one, or null
281 /// otherwise. This type is meaningless except for the bit size.
282 const Type *Formula::getType() const {
283 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
284 ScaledReg ? ScaledReg->getType() :
285 AM.BaseGV ? AM.BaseGV->getType() :
286 0;
287 }
288
289 /// referencesReg - Test if this formula references the given register.
290 bool Formula::referencesReg(const SCEV *S) const {
291 return S == ScaledReg ||
292 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
293 }
294
295 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
296 /// which are used by uses other than the use with the given index.
297 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
298 const RegUseTracker &RegUses) const {
299 if (ScaledReg)
300 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
301 return true;
302 for (SmallVectorImpl::const_iterator I = BaseRegs.begin(),
303 E = BaseRegs.end(); I != E; ++I)
304 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
305 return true;
306 return false;
307 }
308
309 void Formula::print(raw_ostream &OS) const {
310 bool First = true;
311 if (AM.BaseGV) {
312 if (!First) OS << " + "; else First = false;
313 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
314 }
315 if (AM.BaseOffs != 0) {
316 if (!First) OS << " + "; else First = false;
317 OS << AM.BaseOffs;
318 }
319 for (SmallVectorImpl::const_iterator I = BaseRegs.begin(),
320 E = BaseRegs.end(); I != E; ++I) {
321 if (!First) OS << " + "; else First = false;
322 OS << "reg(" << **I << ')';
323 }
324 if (AM.Scale != 0) {
325 if (!First) OS << " + "; else First = false;
326 OS << AM.Scale << "*reg(";
327 if (ScaledReg)
328 OS << *ScaledReg;
329 else
330 OS << "";
331 OS << ')';
332 }
333 }
334
335 void Formula::dump() const {
336 print(errs()); errs() << '\n';
337 }
338
339 /// getSDiv - Return an expression for LHS /s RHS, if it can be determined,
340 /// or null otherwise. If IgnoreSignificantBits is true, expressions like
341 /// (X * Y) /s Y are simplified to Y, ignoring that the multiplication may
342 /// overflow, which is useful when the result will be used in a context where
343 /// the most significant bits are ignored.
344 static const SCEV *getSDiv(const SCEV *LHS, const SCEV *RHS,
345 ScalarEvolution &SE,
346 bool IgnoreSignificantBits = false) {
347 // Handle the trivial case, which works for any SCEV type.
348 if (LHS == RHS)
349 return SE.getIntegerSCEV(1, LHS->getType());
350
351 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
352 // folding.
353 if (RHS->isAllOnesValue())
354 return SE.getMulExpr(LHS, RHS);
355
356 // Check for a division of a constant by a constant.
357 if (const SCEVConstant *C = dyn_cast(LHS)) {
358 const SCEVConstant *RC = dyn_cast(RHS);
359 if (!RC)
360 return 0;
361 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
362 return 0;
363 return SE.getConstant(C->getValue()->getValue()
364 .sdiv(RC->getValue()->getValue()));
365 }
366
367 // Distribute the sdiv over addrec operands.
368 if (const SCEVAddRecExpr *AR = dyn_cast(LHS)) {
369 const SCEV *Start = getSDiv(AR->getStart(), RHS, SE,
370 IgnoreSignificantBits);
371 if (!Start) return 0;
372 const SCEV *Step = getSDiv(AR->getStepRecurrence(SE), RHS, SE,
373 IgnoreSignificantBits);
374 if (!Step) return 0;
375 return SE.getAddRecExpr(Start, Step, AR->getLoop());
376 }
377
378 // Distribute the sdiv over add operands.
379 if (const SCEVAddExpr *Add = dyn_cast(LHS)) {
380 SmallVector Ops;
381 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
382 I != E; ++I) {
383 const SCEV *Op = getSDiv(*I, RHS, SE,
384 IgnoreSignificantBits);
385 if (!Op) return 0;
386 Ops.push_back(Op);
387 }
388 return SE.getAddExpr(Ops);
389 }
390
391 // Check for a multiply operand that we can pull RHS out of.
392 if (const SCEVMulExpr *Mul = dyn_cast(LHS))
393 if (IgnoreSignificantBits || Mul->hasNoSignedWrap()) {
394 SmallVector Ops;
395 bool Found = false;
396 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
397 I != E; ++I) {
398 if (!Found)
399 if (const SCEV *Q = getSDiv(*I, RHS, SE, IgnoreSignificantBits)) {
400 Ops.push_back(Q);
401 Found = true;
402 continue;
403 }
404 Ops.push_back(*I);
225405 }
226
227 I->eraseFromParent();
228 Changed = true;
229 }
406 return Found ? SE.getMulExpr(Ops) : 0;
407 }
408
409 // Otherwise we don't know.
410 return 0;
411 }
412
413 /// ExtractImmediate - If S involves the addition of a constant integer value,
414 /// return that integer value, and mutate S to point to a new SCEV with that
415 /// value excluded.
416 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
417 if (const SCEVConstant *C = dyn_cast(S)) {
418 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
419 S = SE.getIntegerSCEV(0, C->getType());
420 return C->getValue()->getSExtValue();
421 }
422 } else if (const SCEVAddExpr *Add = dyn_cast(S)) {
423 SmallVector NewOps(Add->op_begin(), Add->op_end());
424 int64_t Result = ExtractImmediate(NewOps.front(), SE);
425 S = SE.getAddExpr(NewOps);
426 return Result;
427 } else if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
428 SmallVector NewOps(AR->op_begin(), AR->op_end());
429 int64_t Result = ExtractImmediate(NewOps.front(), SE);
430 S = SE.getAddRecExpr(NewOps, AR->getLoop());
431 return Result;
432 }
433 return 0;
434 }
435
436 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
437 /// return that symbol, and mutate S to point to a new SCEV with that
438 /// value excluded.
439 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
440 if (const SCEVUnknown *U = dyn_cast(S)) {
441 if (GlobalValue *GV = dyn_cast(U->getValue())) {
442 S = SE.getIntegerSCEV(0, GV->getType());
443 return GV;
444 }
445 } else if (const SCEVAddExpr *Add = dyn_cast(S)) {
446 SmallVector NewOps(Add->op_begin(), Add->op_end());
447 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
448 S = SE.getAddExpr(NewOps);
449 return Result;
450 } else if (const SCEVAddRecExpr *AR = dyn_cast(S)) {
451 SmallVector NewOps(AR->op_begin(), AR->op_end());
452 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
453 S = SE.getAddRecExpr(NewOps, AR->getLoop());
454 return Result;
455 }
456 return 0;
230457 }
231458
232459 /// isAddressUse - Returns true if the specified instruction is using the
275502 break;
276503 }
277504 }
505
506 // All pointers have the same requirements, so canonicalize them to an
507 // arbitrary pointer type to minimize variation.
508 if (const PointerType *PTy = dyn_cast(AccessTy))
509 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
510 PTy->getAddressSpace());
511
278512 return AccessTy;
279513 }
280514
515 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
516 /// specified set are trivially dead, delete them and see if this makes any of
517 /// their operands subsequently dead.
518 static bool
519 DeleteTriviallyDeadInstructions(SmallVectorImpl &DeadInsts) {
520 bool Changed = false;
521
522 while (!DeadInsts.empty()) {
523 Instruction *I = dyn_cast_or_null(DeadInsts.pop_back_val());
524
525 if (I == 0 || !isInstructionTriviallyDead(I))
526 continue;
527
528 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
529 if (Instruction *U = dyn_cast(*OI)) {
530 *OI = 0;
531 if (U->use_empty())
532 DeadInsts.push_back(U);
533 }
534
535 I->eraseFromParent();
536 Changed = true;
537 }
538
539 return Changed;
540 }
541
281542 namespace {
282 /// BasedUser - For a particular base value, keep information about how we've
283 /// partitioned the expression so far.
284 struct BasedUser {
285 /// Base - The Base value for the PHI node that needs to be inserted for
286 /// this use. As the use is processed, information gets moved from this
287 /// field to the Imm field (below). BasedUser values are sorted by this
288 /// field.
289 const SCEV *Base;
290
291 /// Inst - The instruction using the induction variable.
292 Instruction *Inst;
293
294 /// OperandValToReplace - The operand value of Inst to replace with the
295 /// EmittedBase.
296 Value *OperandValToReplace;
297
298 /// Imm - The immediate value that should be added to the base immediately
299 /// before Inst, because it will be folded into the imm field of the
300 /// instruction. This is also sometimes used for loop-variant values that
301 /// must be added inside the loop.
302 const SCEV *Imm;
303
304 /// Phi - The induction variable that performs the striding that
305 /// should be used for this user.
306 PHINode *Phi;
307
308 // isUseOfPostIncrementedValue - True if this should use the
309 // post-incremented version of this IV, not the preincremented version.
310 // This can only be set in special cases, such as the terminating setcc
311 // instruction for a loop and uses outside the loop that are dominated by
312 // the loop.
313 bool isUseOfPostIncrementedValue;
314
315 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
316 : Base(IVSU.getOffset()), Inst(IVSU.getUser()),
317 OperandValToReplace(IVSU.getOperandValToReplace()),
318 Imm(se->getIntegerSCEV(0, Base->getType())),
319 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue()) {}
320
321 // Once we rewrite the code to insert the new IVs we want, update the
322 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
323 // to it.
324 void RewriteInstructionToUseNewBase(const SCEV *NewBase,
325 Instruction *InsertPt,
326 SCEVExpander &Rewriter, Loop *L, Pass *P,
327 SmallVectorImpl &DeadInsts,
328 ScalarEvolution *SE);
329
330 Value *InsertCodeForBaseAtPosition(const SCEV *NewBase,
331 const Type *Ty,
332 SCEVExpander &Rewriter,
333 Instruction *IP,
334 ScalarEvolution *SE);
335 void dump() const;
543
544 /// Cost - This class is used to measure and compare candidate formulae.
545 class Cost {
546 /// TODO: Some of these could be merged. Also, a lexical ordering
547 /// isn't always optimal.
548 unsigned NumRegs;
549 unsigned AddRecCost;
550 unsigned NumIVMuls;
551 unsigned NumBaseAdds;
552 unsigned ImmCost;
553 unsigned SetupCost;
554
555 public:
556 Cost()
557 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
558 SetupCost(0) {}
559
560 unsigned getNumRegs() const { return NumRegs; }
561
562 bool operator<(const Cost &Other) const;
563
564 void Loose();
565
566 void RateFormula(const Formula &F,
567 SmallPtrSet &Regs,
568 const DenseSet &VisitedRegs,
569 const Loop *L,
570 const SmallVectorImpl &Offsets,
571 ScalarEvolution &SE, DominatorTree &DT);
572
573 void print(raw_ostream &OS) const;
574 void dump() const;
575
576 private:
577 void RateRegister(const SCEV *Reg,
578 SmallPtrSet &Regs,
579 const Loop *L,
580 ScalarEvolution &SE, DominatorTree &DT);
581 };
582
583 }
584
585 /// RateRegister - Tally up interesting quantities from the given register.
586 void Cost::RateRegister(const SCEV *Reg,
587 SmallPtrSet &Regs,
588 const Loop *L,
589 ScalarEvolution &SE, DominatorTree &DT) {
590 if (Regs.insert(Reg)) {
591 if (const SCEVAddRecExpr *AR = dyn_cast(Reg)) {
592 if (AR->getLoop() == L)
593 AddRecCost += 1; /// TODO: This should be a function of the stride.
594
595 // If this is an addrec for a loop that's already been visited by LSR,
596 // don't second-guess its addrec phi nodes. LSR isn't currently smart
597 // enough to reason about more than one loop at a time. Consider these
598 // registers free and leave them alone.
599 else if (L->contains(AR->getLoop()) ||
600 (!AR->getLoop()->contains(L) &&
601 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
602 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
603 PHINode *PN = dyn_cast(I); ++I)
604 if (SE.isSCEVable(PN->getType()) &&
605 (SE.getEffectiveSCEVType(PN->getType()) ==
606 SE.getEffectiveSCEVType(AR->getType())) &&
607 SE.getSCEV(PN) == AR)
608 goto no_cost;
609
610 // If this isn't one of the addrecs that the loop already has, it
611 // would require a costly new phi and add.
612 ++NumBaseAdds;
613 RateRegister(AR->getStart(), Regs, L, SE, DT);
614 }
615
616 // Add the step value register, if it needs one.
617 // TODO: The non-affine case isn't precisely modeled here.
618 if (!AR->isAffine() || !isa(AR->getOperand(1)))
619 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
620 }
621 ++NumRegs;
622
623 // Rough heuristic; favor registers which don't require extra setup
624 // instructions in the preheader.
625 if (!isa(Reg) &&
626 !isa(Reg) &&
627 !(isa(Reg) &&
628 (isa(cast(Reg)->getStart()) ||
629 isa(cast(Reg)->getStart()))))
630 ++SetupCost;
631 no_cost:;
632 }
633 }
634
635 void Cost::RateFormula(const Formula &F,
636 SmallPtrSet &Regs,
637 const DenseSet &VisitedRegs,
638 const Loop *L,
639 const SmallVectorImpl &Offsets,
640 ScalarEvolution &SE, DominatorTree &DT) {
641 // Tally up the registers.
642 if (const SCEV *ScaledReg = F.ScaledReg) {
643 if (VisitedRegs.count(ScaledReg)) {
644 Loose();
645 return;
646 }
647 RateRegister(ScaledReg, Regs, L, SE, DT);
648 }
649 for (SmallVectorImpl::const_iterator I = F.BaseRegs.begin(),
650 E = F.BaseRegs.end(); I != E; ++I) {
651 const SCEV *BaseReg = *I;
652 if (VisitedRegs.count(BaseReg)) {
653 Loose();
654 return;
655 }
656 RateRegister(BaseReg, Regs, L, SE, DT);
657
658 NumIVMuls += isa(BaseReg) &&
659 BaseReg->hasComputableLoopEvolution(L);
660 }
661
662 if (F.BaseRegs.size() > 1)
663 NumBaseAdds += F.BaseRegs.size() - 1;
664
665 // Tally up the non-zero immediates.
666 for (SmallVectorImpl::const_iterator I = Offsets.begin(),
667 E = Offsets.end(); I != E; ++I) {
668 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
669 if (F.AM.BaseGV)
670 ImmCost += 64; // Handle symbolic values conservatively.
671 // TODO: This should probably be the pointer size.
672 else if (Offset != 0)
673 ImmCost += APInt(64, Offset, true).getMinSignedBits();
674 }
675 }
676
677 /// Loose - Set this cost to a loosing value.
678 void Cost::Loose() {
679 NumRegs = ~0u;
680 AddRecCost = ~0u;
681 NumIVMuls = ~0u;
682 NumBaseAdds = ~0u;
683 ImmCost = ~0u;
684 SetupCost = ~0u;
685 }
686
687 /// operator< - Choose the lower cost.
688 bool Cost::operator<(const Cost &Other) const {
689 if (NumRegs != Other.NumRegs)
690 return NumRegs < Other.NumRegs;
691 if (AddRecCost != Other.AddRecCost)
692 return AddRecCost < Other.AddRecCost;
693 if (NumIVMuls != Other.NumIVMuls)
694 return NumIVMuls < Other.NumIVMuls;
695 if (NumBaseAdds != Other.NumBaseAdds)
696 return NumBaseAdds < Other.NumBaseAdds;
697 if (ImmCost != Other.ImmCost)
698 return ImmCost < Other.ImmCost;
699 if (SetupCost != Other.SetupCost)
700 return SetupCost < Other.SetupCost;
701 return false;
702 }
703
704 void Cost::print(raw_ostream &OS) const {
705 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
706 if (AddRecCost != 0)
707 OS << ", with addrec cost " << AddRecCost;
708 if (NumIVMuls != 0)
709 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
710 if (NumBaseAdds != 0)
711 OS << ", plus " << NumBaseAdds << " base add"
712 << (NumBaseAdds == 1 ? "" : "s");
713 if (ImmCost != 0)
714 OS << ", plus " << ImmCost << " imm cost";
715 if (SetupCost != 0)
716 OS << ", plus " << SetupCost << " setup cost";
717 }
718
719 void Cost::dump() const {
720 print(errs()); errs() << '\n';
721 }
722
723 namespace {
724
725 /// LSRFixup - An operand value in an instruction which is to be replaced
726 /// with some equivalent, possibly strength-reduced, replacement.
727 struct LSRFixup {
728 /// UserInst - The instruction which will be updated.
729 Instruction *UserInst;
730
731 /// OperandValToReplace - The operand of the instruction which will
732 /// be replaced. The operand may be used more than once; every instance
733 /// will be replaced.
734 Value *OperandValToReplace;
735
736 /// PostIncLoop - If this user is to use the post-incremented value of an
737 /// induction variable, this variable is non-null and holds the loop
738 /// associated with the induction variable.
739 const Loop *PostIncLoop;
740
741 /// LUIdx - The index of the LSRUse describing the expression which
742 /// this fixup needs, minus an offset (below).
743 size_t LUIdx;
744
745 /// Offset - A constant offset to be added to the LSRUse expression.
746 /// This allows multiple fixups to share the same LSRUse with different
747 /// offsets, for example in an unrolled loop.
748 int64_t Offset;
749
750 LSRFixup();
751
752 void print(raw_ostream &OS) const;
753 void dump() const;
754 };
755
756 }
757
758 LSRFixup::LSRFixup()
759 : UserInst(0), OperandValToReplace(0), PostIncLoop(0),
760 LUIdx(~size_t(0)), Offset(0) {}
761
762 void LSRFixup::print(raw_ostream &OS) const {
763 OS << "UserInst=";
764 // Store is common and interesting enough to be worth special-casing.
765 if (StoreInst *Store = dyn_cast(UserInst)) {
766 OS << "store ";
767 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
768 } else if (UserInst->getType()->isVoidTy())
769 OS << UserInst->getOpcodeName();
770 else
771 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
772
773 OS << ", OperandValToReplace=";
774 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
775
776 if (PostIncLoop) {
777 OS << ", PostIncLoop=";
778 WriteAsOperand(OS, PostIncLoop->getHeader(), /*PrintType=*/false);
779 }
780
781 if (LUIdx != ~size_t(0))
782 OS << ", LUIdx=" << LUIdx;
783
784 if (Offset != 0)
785 OS << ", Offset=" << Offset;
786 }
787
788 void LSRFixup::dump() const {
789 print(errs()); errs() << '\n';
790 }
791
792 namespace {
793
794 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
795 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
796 struct UniquifierDenseMapInfo {
797 static SmallVector getEmptyKey() {
798 SmallVector V;
799 V.push_back(reinterpret_cast(-1));
800 return V;
801 }
802
803 static SmallVector getTombstoneKey() {
804 SmallVector V;
805 V.push_back(reinterpret_cast(-2));
806 return V;
807 }
808
809 static unsigned getHashValue(const SmallVector &V) {
810 unsigned Result = 0;
811 for (SmallVectorImpl::const_iterator I = V.begin(),
812 E = V.end(); I != E; ++I)
813 Result ^= DenseMapInfo::getHashValue(*I);
814 return Result;
815 }
816
817 static bool isEqual(const SmallVector &LHS,
818 const SmallVector &RHS) {
819 return LHS == RHS;
820 }
821 };
822
823 /// LSRUse - This class holds the state that LSR keeps for each use in
824 /// IVUsers, as well as uses invented by LSR itself. It includes information
825 /// about what kinds of things can be folded into the user, information about
826 /// the user itself, and information about how the use may be satisfied.
827 /// TODO: Represent multiple users of the same expression in common?
828 class LSRUse {
829 DenseSet, UniquifierDenseMapInfo> Uniquifier;
830
831 public:
832 /// KindType - An enum for a kind of use, indicating what types of
833 /// scaled and immediate operands it might support.
834 enum KindType {
835 Basic, ///< A normal use, with no folding.
836 Special, ///< A special case of basic, allowing -1 scales.
837 Address, ///< An address use; folding according to TargetLowering
838 ICmpZero ///< An equality icmp with both operands folded into one.
839 // TODO: Add a generic icmp too?
336840 };
337 }
338
339 void BasedUser::dump() const {
340 dbgs() << " Base=" << *Base;
341 dbgs() << " Imm=" << *Imm;
342 dbgs() << " Inst: " << *Inst;
343 }
344
345 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEV *NewBase,
346 const Type *Ty,
347 SCEVExpander &Rewriter,
348 Instruction *IP,
349 ScalarEvolution *SE) {
350 Value *Base = Rewriter.expandCodeFor(NewBase, 0, IP);
351
352 // Wrap the base in a SCEVUnknown so that ScalarEvolution doesn't try to
353 // re-analyze it.
354 const SCEV *NewValSCEV = SE->getUnknown(Base);
355
356 // Always emit the immediate into the same block as the user.
357 NewValSCEV = SE->getAddExpr(NewValSCEV, Imm);
358
359 return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
360 }
361
362
363 // Once we rewrite the code to insert the new IVs we want, update the
364 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
365 // to it. NewBasePt is the last instruction which contributes to the
366 // value of NewBase in the case that it's a diffferent instruction from
367 // the PHI that NewBase is computed from, or null otherwise.
368 //
369 void BasedUser::RewriteInstructionToUseNewBase(const SCEV *NewBase,
370 Instruction *NewBasePt,
371 SCEVExpander &Rewriter, Loop *L, Pass *P,
372 SmallVectorImpl &DeadInsts,
373 ScalarEvolution *SE) {
374 if (!isa(Inst)) {
375 // By default, insert code at the user instruction.
376 BasicBlock::iterator InsertPt = Inst;
377
378 // However, if the Operand is itself an instruction, the (potentially
379 // complex) inserted code may be shared by many users. Because of this, we
380 // want to emit code for the computation of the operand right before its old
381 // computation. This is usually safe, because we obviously used to use the
382 // computation when it was computed in its current block. However, in some
383 // cases (e.g. use of a post-incremented induction variable) the NewBase
384 // value will be pinned to live somewhere after the original computation.
385 // In this case, we have to back off.
386 //
387 // If this is a use outside the loop (which means after, since it is based
388 // on a loop indvar) we use the post-incremented value, so that we don't
389 // artificially make the preinc value live out the bottom of the loop.
390 if (!isUseOfPostIncrementedValue && L->contains(Inst)) {
391 if (NewBasePt && isa(OperandValToReplace)) {
392 InsertPt = NewBasePt;
393 ++InsertPt;
394 } else if (Instruction *OpInst
395 = dyn_cast(OperandValToReplace)) {
396 InsertPt = OpInst;
397 while (isa(InsertPt)) ++InsertPt;
398 }
399 }
400 Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
401 OperandValToReplace->getType(),
402 Rewriter, InsertPt, SE);
403 // Replace the use of the operand Value with the new Phi we just created.
404 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
405
406 DEBUG(dbgs() << " Replacing with ");
407 DEBUG(WriteAsOperand(dbgs(), NewVal, /*PrintType=*/false));
408 DEBUG(dbgs() << ", which has value " << *NewBase << " plus IMM "
409 << *Imm << "\n");
841
842 KindType Kind;
843 const Type *AccessTy;
844
845 SmallVector Offsets;
846 int64_t MinOffset;
847 int64_t MaxOffset;
848
849 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
850 /// LSRUse are outside of the loop, in which case some special-case heuristics
851 /// may be used.
852 bool AllFixupsOutsideLoop;
853
854 /// Formulae - A list of ways to build a value that can satisfy this user.
855 /// After the list is populated, one of these is selected heuristically and
856 /// used to formulate a replacement for OperandValToReplace in UserInst.
857 SmallVector Formulae;
858
859 /// Regs - The set of register candidates used by all formulae in this LSRUse.
860 SmallPtrSet Regs;
861
862 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
863 MinOffset(INT64_MAX),
864 MaxOffset(INT64_MIN),
865 AllFixupsOutsideLoop(true) {}
866
867 bool InsertFormula(size_t LUIdx, const Formula &F);
868
869 void check() const;
870
871 void print(raw_ostream &OS) const;
872 void dump() const;
873 };
874
875 /// InsertFormula - If the given formula has not yet been inserted, add it to
876 /// the list, and return true. Return false otherwise.
877 bool LSRUse::InsertFormula(size_t LUIdx, const Formula &F) {
878 SmallVector Key = F.BaseRegs;
879 if (F.ScaledReg) Key.push_back(F.ScaledReg);
880 // Unstable sort by host order ok, because this is only used for uniquifying.
881 std::sort(Key.begin(), Key.end());
882
883 if (!Uniquifier.insert(Key).second)
884 return false;
885
886 // Using a register to hold the value of 0 is not profitable.
887 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
888 "Zero allocated in a scaled register!");
889 #ifndef NDEBUG
890 for (SmallVectorImpl::const_iterator I =
891 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
892 assert(!(*I)->isZero() && "Zero allocated in a base register!");
893 #endif
894
895 // Add the formula to the list.
896 Formulae.push_back(F);
897
898 // Record registers now being used by this use.
899 if (F.ScaledReg) Regs.insert(F.ScaledReg);
900 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
901
902 return true;
903 }
904
905 void LSRUse::print(raw_ostream &OS) const {
906 OS << "LSR Use: Kind=";
907 switch (Kind) {
908 case Basic: OS << "Basic"; break;
909 case Special: OS << "Special"; break;
910 case ICmpZero: OS << "ICmpZero"; break;
911 case Address:
912 OS << "Address of ";
913 if (isa(AccessTy))
914 OS << "pointer"; // the full pointer type could be really verbose
915 else
916 OS << *AccessTy;
917 }
918
919 OS << ", Offsets={";
920 for (SmallVectorImpl::const_iterator I = Offsets.begin(),
921 E = Offsets.end(); I != E; ++I) {
922 OS << *I;
923 if (next(I) != E)
924 OS << ',';
925 }
926 OS << '}';
927
928 if (AllFixupsOutsideLoop)
929 OS << ", all-fixups-outside-loop";
930 }
931
932 void LSRUse::dump() const {
933 print(errs()); errs() << '\n';
934 }
935
936 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
937 /// be completely folded into the user instruction at isel time. This includes
938 /// address-mode folding and special icmp tricks.
939 static bool isLegalUse(const TargetLowering::AddrMode &AM,
940 LSRUse::KindType Kind, const Type *AccessTy,
941 const TargetLowering *TLI) {
942 switch (Kind) {
943 case LSRUse::Address:
944 // If we have low-level target information, ask the target if it can
945 // completely fold this address.
946 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
947
948 // Otherwise, just guess that reg+reg addressing is legal.
949 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
950
951 case LSRUse::ICmpZero:
952 // There's not even a target hook for querying whether it would be legal to
953 // fold a GV into an ICmp.
954 if (AM.BaseGV)
955 return false;
956
957 // ICmp only has two operands; don't allow more than two non-trivial parts.
958 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
959 return false;
960
961 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
962 // putting the scaled register in the other operand of the icmp.
963 if (AM.Scale != 0 && AM.Scale != -1)
964 return false;
965
966 // If we have low-level target information, ask the target if it can fold an
967 // integer immediate on an icmp.
968 if (AM.BaseOffs != 0) {
969 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
970 return false;
971 }
972
973 return true;
974
975 case LSRUse::Basic:
976 // Only handle single-register values.
977 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
978
979 case LSRUse::Special:
980 // Only handle -1 scales, or no scale.
981 return AM.Scale == 0 || AM.Scale == -1;
982 }
983
984 return false;
985 }
986
987 static bool isLegalUse(TargetLowering::AddrMode AM,
988 int64_t MinOffset, int64_t MaxOffset,
989 LSRUse::KindType Kind, const Type *AccessTy,
990 const TargetLowering *TLI) {
991 // Check for overflow.
992 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
993 (MinOffset > 0))
994 return false;
995 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
996 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
997 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
998 // Check for overflow.
999 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1000 (MaxOffset > 0))
1001 return false;
1002 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1003 return isLegalUse(AM, Kind, AccessTy, TLI);
1004 }
1005 return false;
1006 }
1007
1008 static bool isAlwaysFoldable(int64_t BaseOffs,
1009 GlobalValue *BaseGV,
1010 bool HasBaseReg,
1011 LSRUse::KindType Kind, const Type *AccessTy,
1012 const TargetLowering *TLI,
1013 ScalarEvolution &SE) {
1014 // Fast-path: zero is always foldable.
1015 if (BaseOffs == 0 && !BaseGV) return true;
1016
1017 // Conservatively, create an address with an immediate and a
1018 // base and a scale.
1019 TargetLowering::AddrMode AM;
1020 AM.BaseOffs = BaseOffs;
1021 AM.BaseGV = BaseGV;
1022 AM.HasBaseReg = HasBaseReg;
1023 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1024
1025 return isLegalUse(AM, Kind, AccessTy, TLI);
1026 }
1027
1028 static bool isAlwaysFoldable(const SCEV *S,
1029 int64_t MinOffset, int64_t MaxOffset,
1030 bool HasBaseReg,
1031 LSRUse::KindType Kind, const Type *AccessTy,
1032 const TargetLowering *TLI,
1033 ScalarEvolution &SE) {
1034 // Fast-path: zero is always foldable.
1035 if (S->isZero()) return true;
1036
1037 // Conservatively, create an address with an immediate and a
1038 // base and a scale.
1039 int64_t BaseOffs = ExtractImmediate(S, SE);
1040 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1041
1042 // If there's anything else involved, it's not foldable.
1043 if (!S->isZero()) return false;
1044
1045 // Fast-path: zero is always foldable.
1046 if (BaseOffs == 0 && !BaseGV) return true;
1047
1048 // Conservatively, create an address with an immediate and a
1049 // base and a scale.
1050 TargetLowering::AddrMode AM;
1051 AM.BaseOffs = BaseOffs;
1052 AM.BaseGV = BaseGV;
1053 AM.HasBaseReg = HasBaseReg;
1054 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1055
1056 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1057 }
1058
1059 /// FormulaSorter - This class implements an ordering for formulae which sorts
1060 /// the by their standalone cost.
1061 class FormulaSorter {
1062 /// These two sets are kept empty, so that we compute standalone costs.
1063 DenseSet VisitedRegs;
1064 SmallPtrSet Regs;
1065 Loop *L;
1066 LSRUse *LU;
1067 ScalarEvolution &SE;
1068 DominatorTree &DT;
1069
1070 public:
1071 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1072 : L(l), LU(&lu), SE(se), DT(dt) {}
1073
1074 bool operator()(const Formula &A, const Formula &B) {
1075 Cost CostA;
1076 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1077 Regs.clear();
1078 Cost CostB;
1079 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1080 Regs.clear();
1081 return CostA < CostB;
1082 }
1083 };
1084
1085 /// LSRInstance - This class holds state for the main loop strength reduction
1086 /// logic.
1087 class LSRInstance {
1088 IVUsers &IU;
1089 ScalarEvolution &SE;
1090 DominatorTree &DT;
1091 const TargetLowering *const TLI;
1092 Loop *const L;
1093 bool Changed;
1094
1095 /// IVIncInsertPos - This is the insert position that the current loop's
1096 /// induction variable increment should be placed. In simple loops, this is
1097 /// the latch block's terminator. But in more complicated cases, this is a
1098 /// position which will dominate all the in-loop post-increment users.
1099 Instruction *IVIncInsertPos;
1100
1101 /// Factors - Interesting factors between use strides.
1102 SmallSetVector Factors;
1103
1104 /// Types - Interesting use types, to facilitate truncation reuse.
1105 SmallSetVector Types;
1106
1107 /// Fixups - The list of operands which are to be replaced.
1108 SmallVector Fixups;
1109
1110 /// Uses - The list of interesting uses.
1111 SmallVector Uses;
1112
1113 /// RegUses - Track which uses use which register candidates.
1114 RegUseTracker RegUses;
1115
1116 void OptimizeShadowIV();
1117 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1118 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1119 bool OptimizeLoopTermCond();
1120
1121 void CollectInterestingTypesAndFactors();
1122 void CollectFixupsAndInitialFormulae();
1123
1124 LSRFixup &getNewFixup() {
1125 Fixups.push_back(LSRFixup());
1126 return Fixups.back();
1127 }
1128
1129 // Support for sharing of LSRUses between LSRFixups.
1130 typedef DenseMap UseMapTy;
1131 UseMapTy UseMap;
1132
1133 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1134 LSRUse::KindType Kind, const Type *AccessTy);
1135
1136 std::pair getUse(const SCEV *&Expr,
1137 LSRUse::KindType Kind,
1138 const Type *AccessTy);
1139
1140 public:
1141 void InsertInitialFormula(const SCEV *S, Loop *L, LSRUse &LU, size_t LUIdx);
1142 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1143 void CountRegisters(const Formula &F, size_t LUIdx);
1144 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1145
1146 void CollectLoopInvariantFixupsAndFormulae();
1147
1148 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1149 unsigned Depth = 0);
1150 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1151 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1152 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1153 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1154 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1155 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1156 void GenerateCrossUseConstantOffsets();
1157 void GenerateAllReuseFormulae();
1158
1159 void FilterOutUndesirableDedicatedRegisters();
1160 void NarrowSearchSpaceUsingHeuristics();
1161
1162 void SolveRecurse(SmallVectorImpl &Solution,
1163 Cost &SolutionCost,
1164 SmallVectorImpl &Workspace,
1165 const Cost &CurCost,
1166 const SmallPtrSet &CurRegs,
1167 DenseSet &VisitedRegs) const;
1168 void Solve(SmallVectorImpl &Solution) const;
1169
1170 Value *Expand(const LSRFixup &LF,
1171 const Formula &F,
1172 BasicBlock::iterator IP, Loop *L, Instruction *IVIncInsertPos,
1173 SCEVExpander &Rewriter,
1174 SmallVectorImpl &DeadInsts,
1175 ScalarEvolution &SE, DominatorTree &DT) const;
1176 void Rewrite(const LSRFixup &LF,
1177 const Formula &F,
1178 Loop *L, Instruction *IVIncInsertPos,
1179 SCEVExpander &Rewriter,
1180 SmallVectorImpl &DeadInsts,
1181 ScalarEvolution &SE, DominatorTree &DT,
1182 Pass *P) const;
1183 void ImplementSolution(const SmallVectorImpl &Solution,
1184 Pass *P);
1185
1186 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1187
1188 bool getChanged() const { return Changed; }
1189
1190 void print_factors_and_types(raw_ostream &OS) const;
1191 void print_fixups(raw_ostream &OS) const;
1192 void print_uses(raw_ostream &OS) const;
1193 void print(raw_ostream &OS) const;
1194 void dump() const;
1195 };
1196
1197 }
1198
1199 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1200 /// inside the loop then try to eliminate the cast opeation.
1201 void LSRInstance::OptimizeShadowIV() {
1202 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1203 if (isa(BackedgeTakenCount))
4101204 return;
411 }
412
413 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
414 // expression into each operand block that uses it. Note that PHI nodes can
415 // have multiple entries for the same predecessor. We use a map to make sure
416 // that a PHI node only has a single Value* for each predecessor (which also
417 // prevents us from inserting duplicate code in some blocks).
418 DenseMap InsertedCode;
419 PHINode *PN = cast(Inst);
420 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
421 if (PN->getIncomingValue(i) == OperandValToReplace) {
422 // If the original expression is outside the loop, put the replacement
423 // code in the same place as the original expression,
424 // which need not be an immediate predecessor of this PHI. This way we
425 // need only one copy of it even if it is referenced multiple times in
426 // the PHI. We don't do this when the original expression is inside the
427 // loop because multiple copies sometimes do useful sinking of code in
428 // that case(?).
429 Instruction *OldLoc = dyn_cast(OperandValToReplace);
430 BasicBlock *PHIPred = PN->getIncomingBlock(i);
431 if (L->contains(OldLoc)) {
432 // If this is a critical edge, split the edge so that we do not insert
433 // the code on all predecessor/successor paths. We do this unless this
434 // is the canonical backedge for this loop, as this can make some
435 // inserted code be in an illegal position.
436 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
437 !isa(PHIPred->getTerminator()) &&
438 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
439
440 // First step, split the critical edge.
441 BasicBlock *NewBB = SplitCriticalEdge(PHIPred, PN->getParent(),
442 P, false);
443
444 // Next step: move the basic block. In particular, if the PHI node
445 // is outside of the loop, and PredTI is in the loop, we want to
446 // move the block to be immediately before the PHI block, not
447 // immediately after PredTI.
448 if (L->contains(PHIPred) && !L->contains(PN))
449 NewBB->moveBefore(PN->getParent());
450
451 // Splitting the edge can reduce the number of PHI entries we have.
452 e = PN->getNumIncomingValues();
453 PHIPred = NewBB;
454 i = PN->getBasicBlockIndex(PHIPred);
455 }
456 }
457 Value *&Code = InsertedCode[PHIPred];
458 if (!Code) {
459 // Insert the code into the end of the predecessor block.
460 Instruction *InsertPt = (L->contains(OldLoc)) ?
461 PHIPred->getTerminator() :
462 OldLoc->getParent()->getTerminator();
463 Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
464 Rewriter, InsertPt, SE);
465
466 DEBUG(dbgs() << " Changing PHI use to ");
467 DEBUG(WriteAsOperand(dbgs(), Code, /*PrintType=*/false));
468 DEBUG(dbgs() << ", which has value " << *NewBase << " plus IMM "
469 << *Imm << "\n");
470 }
471
472 // Replace the use of the operand Value with the new Phi we just created.
473 PN->setIncomingValue(i, Code);
474 Rewriter.clear();
475 }
476 }
477
478 // PHI node might have become a constant value after SplitCriticalEdge.
479 DeadInsts.push_back(Inst);
480 }
481
482
483 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
484 /// mode, and does not need to be put in a register first.
485 static bool fitsInAddressMode(const SCEV *V, const Type *AccessTy,
486 const TargetLowering *TLI, bool HasBaseReg) {
487 if (const SCEVConstant *SC = dyn_cast(V)) {
488 int64_t VC = SC->getValue()->getSExtValue();
1205
1206 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1207 UI != E; /* empty */) {
1208 IVUsers::const_iterator CandidateUI = UI;
1209 ++UI;
1210 Instruction *ShadowUse = CandidateUI->getUser();
1211 const Type *DestTy = NULL;
1212
1213 /* If shadow use is a int->float cast then insert a second IV
1214 to eliminate this cast.
1215
1216 for (unsigned i = 0; i < n; ++i)
1217 foo((double)i);
1218
1219 is transformed into
1220
1221 double d = 0.0;
1222 for (unsigned i = 0; i < n; ++i, ++d)
1223 foo(d);
1224 */
1225 if (UIToFPInst *UCast = dyn_cast(CandidateUI->getUser()))
1226 DestTy = UCast->getDestTy();
1227 else if (SIToFPInst *SCast = dyn_cast(CandidateUI->getUser()))
1228 DestTy = SCast->getDestTy();
1229 if (!DestTy) continue;
1230
4891231 if (TLI) {
490 TargetLowering::AddrMode AM;
491 AM.BaseOffs = VC;
492 AM.HasBaseReg = HasBaseReg;
493 return TLI->isLegalAddressingMode(AM, AccessTy);
1232 // If target does not support DestTy natively then do not apply
1233 // this transformation.
1234 EVT DVT = TLI->getValueType(DestTy);
1235 if (!TLI->isTypeLegal(DVT)) continue;
1236 }
1237
1238 PHINode *PH = dyn_cast(ShadowUse->getOperand(0));
1239 if (!PH) continue;
1240 if (PH->getNumIncomingValues() != 2) continue;
1241
1242 const Type *SrcTy = PH->getType();
1243 int Mantissa = DestTy->getFPMantissaWidth();
1244 if (Mantissa == -1) continue;
1245 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1246 continue;
1247
1248 unsigned Entry, Latch;
1249 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1250 Entry = 0;
1251 Latch = 1;
4941252 } else {
495 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
496 return (VC > -(1 << 16) && VC < (1 << 16)-1);
497 }
498 }
499
500 if (const SCEVUnknown *SU = dyn_cast(V))
501 if (GlobalValue *GV = dyn_cast(SU->getValue())) {
502 if (TLI) {
503 TargetLowering::AddrMode AM;
504 AM.BaseGV = GV;
505 AM.HasBaseReg = HasBaseReg;
506 return TLI->isLegalAddressingMode(AM, AccessTy);
507 } else {
508 // Default: assume global addresses are not legal.
509 }
510 }
511
512 return false;
513 }
514
515 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
516 /// loop varying to the Imm operand.
517 static void MoveLoopVariantsToImmediateField(const SCEV *&Val, const SCEV *&Imm,
518 Loop *L, ScalarEvolution *SE) {
519 if (Val->isLoopInvariant(L)) return; // Nothing to do.
520
521 if (const SCEVAddExpr *SAE = dyn_cast(Val)) {
522 SmallVector NewOps;
523 NewOps.reserve(SAE->getNumOperands());
524
525 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
526 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
527 // If this is a loop-variant expression, it must stay in the immediate
528 // field of the expression.
529 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
530 } else {
531 NewOps.push_back(SAE->getOperand(i));
532 }
533
534 if (NewOps.empty())
535 Val = SE->getIntegerSCEV(0, Val->getType());
1253 Entry = 1;
1254 Latch = 0;
1255 }
1256
1257 ConstantInt *Init = dyn_cast(PH->getIncomingValue(Entry));
1258 if (!Init) continue;
1259 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1260
1261 BinaryOperator *Incr =
1262 dyn_cast(PH->getIncomingValue(Latch));
1263 if (!Incr) continue;
1264 if (Incr->getOpcode() != Instruction::Add
1265 && Incr->getOpcode() != Instruction::Sub)
1266 continue;
1267
1268 /* Initialize new IV, double d = 0.0 in above example. */
1269 ConstantInt *C = NULL;
1270 if (Incr->getOperand(0) == PH)
1271 C = dyn_cast(Incr->getOperand(1));
1272 else if (Incr->getOperand(1) == PH)
1273 C = dyn_cast(Incr->getOperand(0));
5361274 else
537 Val = SE->getAddExpr(NewOps);
538 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Val)) {
539 // Try to pull immediates out of the start value of nested addrec's.
540 const SCEV *Start = SARE->getStart();
541 MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
542
543 SmallVector Ops(SARE->op_begin(), SARE->op_end());
544 Ops[0] = Start;
545 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
546 } else {
547 // Otherwise, all of Val is variant, move the whole thing over.
548 Imm = SE->getAddExpr(Imm, Val);
549 Val = SE->getIntegerSCEV(0, Val->getType());
550 }
551 }
552
553
554 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
555 /// that can fit into the immediate field of instructions in the target.
556 /// Accumulate these immediate values into the Imm value.
557 static void MoveImmediateValues(const TargetLowering *TLI,
558 const Type *AccessTy,
559 const SCEV *&Val, const SCEV *&Imm,
560 bool isAddress, Loop *L,
561 ScalarEvolution *SE) {
562 if (const SCEVAddExpr *SAE = dyn_cast(Val)) {
563 SmallVector NewOps;
564 NewOps.reserve(SAE->getNumOperands());
565
566 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
567 const SCEV *NewOp = SAE->getOperand(i);
568 MoveImmediateValues(TLI, AccessTy, NewOp, Imm, isAddress, L, SE);
569
570 if (!NewOp->isLoopInvariant(L)) {
571 // If this is a loop-variant expression, it must stay in the immediate
572 // field of the expression.
573 Imm = SE->getAddExpr(Imm, NewOp);
574 } else {
575 NewOps.push_back(NewOp);
576 }
577 }
578
579 if (NewOps.empty())
580 Val = SE->getIntegerSCEV(0, Val->getType());
581 else
582 Val = SE->getAddExpr(NewOps);
583 return;
584 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Val)) {
585 // Try to pull immediates out of the start value of nested addrec's.
586 const SCEV *Start = SARE->getStart();
587 MoveImmediateValues(TLI, AccessTy, Start, Imm, isAddress, L, SE);
588
589 if (Start != SARE->getStart()) {
590 SmallVector Ops(SARE->op_begin(), SARE->op_end());
591 Ops[0] = Start;
592 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
593 }
594 return;
595 } else if (const SCEVMulExpr *SME = dyn_cast(Val)) {
596 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
597 if (isAddress &&
598 fitsInAddressMode(SME->getOperand(0), AccessTy, TLI, false) &&
599 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
600
601 const SCEV *SubImm = SE->getIntegerSCEV(0, Val->getType());
602 const SCEV *NewOp = SME->getOperand(1);
603 MoveImmediateValues(TLI, AccessTy, NewOp, SubImm, isAddress, L, SE);
604
605 // If we extracted something out of the subexpressions, see if we can
606 // simplify this!
607 if (NewOp != SME->getOperand(1)) {
608 // Scale SubImm up by "8". If the result is a target constant, we are
609 // good.
610 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
611 if (fitsInAddressMode(SubImm, AccessTy, TLI, false)) {
612 // Accumulate the immediate.
613 Imm = SE->getAddExpr(Imm, SubImm);
614
615 // Update what is left of 'Val'.
616 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
617 return;
618 }
619 }
620 }
621 }
622
623 // Loop-variant expressions must stay in the immediate field of the
624 // expression.
625 if ((isAddress && fitsInAddressMode(Val, AccessTy, TLI, false)) ||
626 !Val->isLoopInvariant(L)) {
627 Imm = SE->getAddExpr(Imm, Val);
628 Val = SE->getIntegerSCEV(0, Val->getType());
629 return;
630 }
631
632 // Otherwise, no immediates to move.
633 }
634
635 static void MoveImmediateValues(const TargetLowering *TLI,
636 Instruction *User,
637 const SCEV *&Val, const SCEV *&Imm,
638 bool isAddress, Loop *L,
639 ScalarEvolution *SE) {
640 const Type *AccessTy = getAccessType(User);
641 MoveImmediateValues(TLI, AccessTy, Val, Imm, isAddress, L, SE);
642 }
643
644 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
645 /// added together. This is used to reassociate common addition subexprs
646 /// together for maximal sharing when rewriting bases.
647 static void SeparateSubExprs(SmallVector &SubExprs,
648 const SCEV *Expr,
649 ScalarEvolution *SE) {
650 if (const SCEVAddExpr *AE = dyn_cast(Expr)) {
651 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
652 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
653 } else if (const SCEVAddRecExpr *SARE = dyn_cast(Expr)) {
654 const SCEV *Zero = SE->getIntegerSCEV(0, Expr->getType());
655 if (SARE->getOperand(0) == Zero) {
656 SubExprs.push_back(Expr);
657 } else {
658 // Compute the addrec with zero as its base.
659 SmallVector Ops(SARE->op_begin(), SARE->op_end());
660 Ops[0] = Zero; // Start with zero base.
661 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
662
663
664 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
665 }
666 } else if (!Expr->isZero()) {
667 // Do not add zero.
668 SubExprs.push_back(Expr);
669 }
670 }
671
672 // This is logically local to the following function, but C++ says we have
673 // to make it file scope.
674 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
675
676 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
677 /// the Uses, removing any common subexpressions, except that if all such
678 /// subexpressions can be folded into an addressing mode for all uses inside
679 /// the loop (this case is referred to as "free" in comments herein) we do
680 /// not remove anything. This looks for things like (a+b+c) and
681 /// (a+c+d) and computes the common (a+c) subexpression. The common expression
682 /// is *removed* from the Bases and returned.
683 static const SCEV *
684 RemoveCommonExpressionsFromUseBases(std::vector &Uses,
685 ScalarEvolution *SE, Loop *L,
686 const TargetLowering *TLI) {
687 unsigned NumUses = Uses.size();
688
689 // Only one use? This is a very common case, so we handle it specially and
690 // cheaply.
691 const SCEV *Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
692 const SCEV *Result = Zero;
693 const SCEV *FreeResult = Zero;
694 if (NumUses == 1) {
695 // If the use is inside the loop, use its base, regardless of what it is:
696 // it is clearly shared across all the IV's. If the use is outside the loop
697 // (which means after it) we don't want to factor anything *into* the loop,
698 // so just use 0 as the base.
699 if (L->contains(Uses[0].Inst))
700 std::swap(Result, Uses[0].Base);
701 return Result;
702 }
703
704 // To find common subexpressions, count how many of Uses use each expression.
705 // If any subexpressions are used Uses.size() times, they are common.
706 // Also track whether all uses of each expression can be moved into an
707 // an addressing mode "for free"; such expressions are left within the loop.
708 // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
709 std::map SubExpressionUseData;
710
711 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
712 // order we see them.
713 SmallVector UniqueSubExprs;
714
715 SmallVector SubExprs;
716 unsigned NumUsesInsideLoop = 0;
717 for (unsigned i = 0; i != NumUses; ++i) {
718 // If the user is outside the loop, just ignore it for base computation.
719 // Since the user is outside the loop, it must be *after* the loop (if it
720 // were before, it could not be based on the loop IV). We don't want users
721 // after the loop to affect base computation of values *inside* the loop,
722 // because we can always add their offsets to the result IV after the loop
723 // is done, ensuring we get good code inside the loop.
724 if (!L->contains(Uses[i].Inst))
7251275 continue;
726 NumUsesInsideLoop++;
727
728 // If the base is zero (which is common), return zero now, there are no
729 // CSEs we can find.
730 if (Uses[i].Base == Zero) return Zero;
731
732 // If this use is as an address we may be able to put CSEs in the addressing
733 // mode rather than hoisting them.
734 bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
735 // We may need the AccessTy below, but only when isAddrUse, so compute it
736 // only in that case.
737 const Type *AccessTy = 0;
738 if (isAddrUse)
739 AccessTy = getAccessType(Uses[i].Inst);
740
741 // Split the expression into subexprs.
742 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
743 // Add one to SubExpressionUseData.Count for each subexpr present, and
744 // if the subexpr is not a valid immediate within an addressing mode use,
745 // set SubExpressionUseData.notAllUsesAreFree. We definitely want to
746 // hoist these out of the loop (if they are common to all uses).
747 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
748 if (++SubExpressionUseData[SubExprs[j]].Count == 1)
749 UniqueSubExprs.push_back(SubExprs[j]);
750 if (!isAddrUse || !fitsInAddressMode(SubExprs[j], AccessTy, TLI, false))
751 SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
752 }
753 SubExprs.clear();
754 }
755
756 // Now that we know how many times each is used, build Result. Iterate over
757 // UniqueSubexprs so that we have a stable ordering.
758 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
759 std::map::iterator I =
760 SubExpressionUseData.find(UniqueSubExprs[i]);
761 assert(I != SubExpressionUseData.end() && "Entry not found?");
762 if (I->second.Count == NumUsesInsideLoop) { // Found CSE!
763 if (I->second.notAllUsesAreFree)
764 Result = SE->getAddExpr(Result, I->first);
765 else
766 FreeResult = SE->getAddExpr(FreeResult, I->first);
767 } else
768 // Remove non-cse's from SubExpressionUseData.
769 SubExpressionUseData.erase(I);
770 }
771
772 if (FreeResult != Zero) {
773 // We have some subexpressions that can be subsumed into addressing
774 // modes in every use inside the loop. However, it's possible that
775 // there are so many of them that the combined FreeResult cannot
776 // be subsumed, or that the target cannot handle both a FreeResult
777 // and a Result in the same instruction (for example because it would
778 // require too many registers). Check this.
779 for (unsigned i=0; i
780 if (!L->contains(Uses[i].Inst))
781 continue;
782 // We know this is an addressing mode use; if there are any uses that
783 // are not, FreeResult would be Zero.
784 const Type *AccessTy = getAccessType(Uses[i].Inst);
785 if (!fitsInAddressMode(FreeResult, AccessTy, TLI, Result!=Zero)) {
786 // FIXME: could split up FreeResult into pieces here, some hoisted
787 // and some not. There is no obvious advantage to this.
788 Result = SE->getAddExpr(Result, FreeResult);
789 FreeResult = Zero;
790 break;
791 }
792 }
793 }
794
795 // If we found no CSE's, return now.
796 if (Result == Zero) return Result;
797
798 // If we still have a FreeResult, remove its subexpressions from
799 // SubExpressionUseData. This means they will remain in the use Bases.
800 if (FreeResult != Zero) {
801 SeparateSubExprs(SubExprs, FreeResult, SE);
802 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
803 std::map::iterator I =
804 SubExpressionUseData.find(SubExprs[j]);
805 SubExpressionUseData.erase(I);
806 }
807 SubExprs.clear();
808 }
809
810 // Otherwise, remove all of the CSE's we found from each of the base values.
811 for (unsigned i = 0; i != NumUses; ++i) {
812 // Uses outside the loop don't necessarily include the common base, but
813 // the final IV value coming into those uses does. Instead of trying to
814 // remove the pieces of the common base, which might not be there,
815 // subtract off the base to compensate for this.
816 if (!L->contains(Uses[i].Inst)) {
817 Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
818 continue;
819 }
820
821 // Split the expression into subexprs.
822 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
823
824 // Remove any common subexpressions.
825 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
826 if (SubExpressionUseData.count(SubExprs[j])) {
827 SubExprs.erase(SubExprs.begin()+j);
828 --j; --e;
829 }
830
831 // Finally, add the non-shared expressions together.
832 if (SubExprs.empty())
833 Uses[i].Base = Zero;
834 else
835 Uses[i].Base = SE->getAddExpr(SubExprs);
836 SubExprs.clear();
837 }
838
839 return Result;
840 }
841
842 /// ValidScale - Check whether the given Scale is valid for all loads and
843 /// stores in UsersToProcess.
844 ///
845 bool LoopStrengthReduce::ValidScale(bool HasBaseReg, int64_t Scale,
846 const std::vector& UsersToProcess) {
847 if (!TLI)
848 return true;
849
850 for (unsigned i = 0, e = UsersToProcess.size(); i!=e; ++i) {
851 // If this is a load or other access, pass the type of the access in.
852 const Type *AccessTy =
853 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
854 if (isAddressUse(UsersToProcess[i].Inst,
855 UsersToProcess[i].OperandValToReplace))
856 AccessTy = getAccessType(UsersToProcess[i].Inst);
857 else if (isa(UsersToProcess[i].Inst))
858 continue;
859
860 TargetLowering::AddrMode AM;
861 if (const SCEVConstant *SC = dyn_cast(UsersToProcess[i].Imm))
862 AM.BaseOffs = SC->getValue()->getSExtValue();
863 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
864 AM.Scale = Scale;
865
866 // If load[imm+r*scale] is illegal, bail out.
867 if (!TLI->isLegalAddressingMode(AM, AccessTy))
868 return false;
869 }
870 return true;
871 }
872
873 /// ValidOffset - Check whether the given Offset is valid for all loads and
874 /// stores in UsersToProcess.
875 ///
876 bool LoopStrengthReduce::ValidOffset(bool HasBaseReg,
877 int64_t Offset,
878 int64_t Scale,
879 const std::vector& UsersToProcess) {
880 if (!TLI)
881 return true;
882
883 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
884 // If this is a load or other access, pass the type of the access in.
885 const Type *AccessTy =
886 Type::getVoidTy(UsersToProcess[i].Inst->getContext());
887 if (isAddressUse(UsersToProcess[i].Inst,
888 UsersToProcess[i].OperandValToReplace))
889 AccessTy = getAccessType(UsersToProcess[i].Inst);
890 else if (isa(UsersToProcess[i].Inst))
891 continue;
892
893 TargetLowering::AddrMode AM;
894 if (const SCEVConstant *SC = dyn_cast(UsersToProcess[i].Imm))
895 AM.BaseOffs = SC->getValue()->getSExtValue();
896 AM.BaseOffs = (uint64_t)AM.BaseOffs + (uint64_t)Offset;
897 AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
898 AM.Scale = Scale;
899
900 // If load[imm+r*scale] is illegal, bail out.
901 if (!TLI->isLegalAddressingMode(AM, AccessTy))
902 return false;
903 }
904 return true;
905 }
906
907 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
908 /// a nop.
909 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
910 const Type *Ty2) {
911 if (Ty1 == Ty2)
912 return false;
913 Ty1 = SE->getEffectiveSCEVType(Ty1);
914 Ty2 = SE->getEffectiveSCEVType(Ty2);
915 if (Ty1 == Ty2)
916 return false;
917 if (Ty1->canLosslesslyBitCastTo(Ty2))
918 return false;
919 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
920 return false;
921 return true;
922 }
923
924 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
925 /// of a previous stride and it is a legal value for the target addressing
926 /// mode scale component and optional base reg. This allows the users of
927 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
928 /// reuse is possible. Factors can be negative on same targets, e.g. ARM.
929 ///
930 /// If all uses are outside the loop, we don't require that all multiplies
931 /// be folded into the addressing mode, nor even that the factor be constant;
932 /// a multiply (executed once) outside the loop is better than another IV
933 /// within. Well, usually.
934 const SCEV *LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
935 bool AllUsesAreAddresses,
936 bool AllUsesAreOutsideLoop,
937 const SCEV *Stride,
938 IVExpr &IV, const Type *Ty,
939 const std::vector& UsersToProcess) {
940 if (const SCEVConstant *SC = dyn_cast(Stride)) {
941 int64_t SInt = SC->getValue()->getSExtValue();
942 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
943 NewStride != e; ++NewStride) {
944 std::map::iterator SI =
945 IVsByStride.find(IU->StrideOrder[NewStride]);
946 if (SI == IVsByStride.end() || !isa(SI->first))
947 continue;
948 // The other stride has no uses, don't reuse it.
949 std::map::iterator UI =
950 IU->IVUsesByStride.find(IU->StrideOrder[NewStride]);
951 if (UI->second->Users.empty())
952 continue;
953 int64_t SSInt = cast(SI->first)->getValue()->getSExtValue();
954 if (SI->first != Stride &&
955 (unsigned(abs64(SInt)) < SSInt || (SInt % SSInt) != 0))
956 continue;
957 int64_t Scale = SInt / SSInt;
958 // Check that this stride is valid for all the types used for loads and
959 // stores; if it can be used for some and not others, we might as well use
960 // the original stride everywhere, since we have to create the IV for it
961 // anyway. If the scale is 1, then we don't need to worry about folding
962 // multiplications.
963 if (Scale == 1 ||
964 (AllUsesAreAddresses &&
965 ValidScale(HasBaseReg, Scale, UsersToProcess))) {
966 // Prefer to reuse an IV with a base of zero.
967 for (std::vector::iterator II = SI->second.IVs.begin(),
968 IE = SI->second.IVs.end(); II != IE; ++II)
969 // Only reuse previous IV if it would not require a type conversion
970 // and if the base difference can be folded.
971 if (II->Base->isZero() &&
972 !RequiresTypeConversion(II->Base->getType(), Ty)) {
973 IV = *II;
974 return SE->getIntegerSCEV(Scale, Stride->getType());
975 }
976 // Otherwise, settle for an IV with a foldable base.
977 if (AllUsesAreAddresses)
978 for (std::vector::iterator II = SI->second.IVs.begin(),
979 IE = SI->second.IVs.end(); II != IE; ++II)
980 // Only reuse previous IV if it would not require a type conversion
981 // and if the base difference can be folded.
982 if (SE->getEffectiveSCEVType(II->Base->getType()) ==
983 SE->getEffectiveSCEVType(Ty) &&
984 isa(II->Base)) {
985 int64_t Base =
986 cast(II->Base)->getValue()->getSExtValue();
987 if (Base > INT32_MIN && Base <= INT32_MAX &&
988 ValidOffset(HasBaseReg, -Base * Scale,
989 Scale, UsersToProcess)) {
990 IV = *II;
991 return SE->getIntegerSCEV(Scale, Stride->getType());
992 }
993 }
994 }
995 }
996 } else if (AllUsesAreOutsideLoop) {
997 // Accept nonconstant strides here; it is really really right to substitute
998 // an existing IV if we can.
999 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1000 NewStride != e; ++NewStride) {
1001 std::map::iterator SI =
1002 IVsByStride.find(IU->StrideOrder[NewStride]);
1003 if (SI == IVsByStride.end() || !isa(SI->first))
1004 continue;
1005 int64_t SSInt = cast(SI->first)->getValue()->getSExtValue();
1006 if (SI->first != Stride && SSInt != 1)
1007 continue;
1008 for (std::vector::iterator II = SI->second.IVs.begin(),
1009 IE = SI->second.IVs.end(); II != IE; ++II)
1010 // Accept nonzero base here.
1011 // Only reuse previous IV if it would not require a type conversion.
1012 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1013 IV = *II;
1014 return Stride;
1015 }
1016 }
1017 // Special case, old IV is -1*x and this one is x. Can treat this one as
1018 // -1*old.
1019 for (unsigned NewStride = 0, e = IU->StrideOrder.size();
1020 NewStride != e; ++NewStride) {
1021 std::map::iterator SI =
1022 IVsByStride.find(IU->StrideOrder[NewStride]);
1023 if (SI == IVsByStride.end())
1024 continue;
1025 if (const SCEVMulExpr *ME = dyn_cast(SI->first))
1026 if (const SCEVConstant *SC = dyn_cast(ME->getOperand(0)))
1027 if (Stride == ME->getOperand(1) &&
1028 SC->getValue()->getSExtValue() == -1LL)
1029 for (std::vector::iterator II = SI->second.IVs.begin(),
1030 IE = SI->second.IVs.end(); II != IE; ++II)
1031 // Accept nonzero base here.
1032 // Only reuse previous IV if it would not require type conversion.
1033 if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1034 IV = *II;
1035 return SE->getIntegerSCEV(-1LL, Stride->getType());
1036 }
1037 }
1038 }
1039 return SE->getIntegerSCEV(0, Stride->getType());
1040 }
1041
1042 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1043 /// returns true if Val's isUseOfPostIncrementedValue is true.
1044 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1045 return Val.isUseOfPostIncrementedValue;
1046 }
1047
1048 /// isNonConstantNegative - Return true if the specified scev is negated, but
1049 /// not a constant.
1050 static bool isNonConstantNegative(const SCEV *Expr) {
1051 const SCEVMulExpr *Mul = dyn_cast(Expr);
1052 if (!Mul) return false;
1053
1054 // If there is a constant factor, it will be first.
1055 const SCEVConstant *SC = dyn_cast(Mul->getOperand(0));
1056 if (!SC) return false;
1057
1058 // Return true if the value is negative, this matches things like (-42 * V).
1059 return SC->getValue()->getValue().isNegative();
1060 }
1061
1062 /// CollectIVUsers - Transform our list of users and offsets to a bit more
1063 /// complex table. In this new vector, each 'BasedUser' contains 'Base', the
1064 /// base of the strided accesses, as well as the old information from Uses. We
1065 /// progressively move information from the Base field to the Imm field, until
1066 /// we eventually have the full access expression to rewrite the use.
1067 const SCEV *LoopStrengthReduce::CollectIVUsers(const SCEV *Stride,
1068 IVUsersOfOneStride &Uses,
1069 Loop *L,
1070 bool &AllUsesAreAddresses,
1071 bool &AllUsesAreOutsideLoop,
1072 std::vector &UsersToProcess) {
1073 // FIXME: Generalize to non-affine IV's.
1074 if (!Stride->isLoopInvariant(L))
1075 return SE->getIntegerSCEV(0, Stride->getType());
1076
1077 UsersToProcess.reserve(Uses.Users.size());
1078 for (ilist::iterator I = Uses.Users.begin(),
1079 E = Uses.Users.end(); I != E; ++I) {
1080 UsersToProcess.push_back(BasedUser(*I, SE));
1081
1082 // Move any loop variant operands from the offset field to the immediate
1083 // field of the use, so that we don't try to use something before it is
1084 // computed.
1085 MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1086 UsersToProcess.back().Imm, L, SE);
1087 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1088 "Base value is not loop invariant!");
1089 }
1090
1091 // We now have a whole bunch of uses of like-strided induction variables, but
1092 // they might all have different bases. We want to emit one PHI node for this
1093 // stride which we fold as many common expressions (between the IVs) into as
1094 // possible. Start by identifying the common expressions in the base values
1095 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1096 // "A+B"), emit it to the preheader, then remove the expression from the
1097 // UsersToProcess base values.
1098 const SCEV *CommonExprs =
1099 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1100
1101 // Next, figure out what we can represent in the immediate fields of
1102 // instructions. If we can represent anything there, move it to the imm
1103 // fields of the BasedUsers. We do this so that it increases the commonality
1104 // of the remaining uses.
1105 unsigned NumPHI = 0;
1106 bool HasAddress = false;
1107 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1108 // If the user is not in the current loop, this means it is using the exit
1109 // value of the IV. Do not put anything in the base, make sure it's all in
1110 // the immediate field to allow as much factoring as possible.
1111 if (!L->contains(UsersToProcess[i].Inst)) {
1112 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1113 UsersToProcess[i].Base);
1114 UsersToProcess[i].Base =
1115 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1116 } else {
1117 // Not all uses are outside the loop.
1118 AllUsesAreOutsideLoop = false;
1119
1120 // Addressing modes can be folded into loads and stores. Be careful that
1121 // the store is through the expression, not of the expression though.
1122 bool isPHI = false;
1123 bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1124 UsersToProcess[i].OperandValToReplace);
1125 if (isa(UsersToProcess[i].Inst)) {
1126 isPHI = true;
1127 ++NumPHI;
1128 }
1129
1130 if (isAddress)
1131 HasAddress = true;
1132
1133 // If this use isn't an address, then not all uses are addresses.
1134 if (!isAddress && !isPHI)
1135 AllUsesAreAddresses = false;
1136
1137 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1138 UsersToProcess[i].Imm, isAddress, L, SE);
1139 }
1140 }
1141
1142 // If one of the use is a PHI node and all other uses are addresses, still
1143 // allow iv reuse. Essentially we are trading one constant multiplication
1144 // for one fewer iv.
1145 if (NumPHI > 1)
1146 AllUsesAreAddresses = false;
1147
1148 // There are no in-loop address uses.
1149 if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1150 AllUsesAreAddresses = false;
1151
1152 return CommonExprs;
1153 }
1154
1155 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1156 /// is valid and profitable for the given set of users of a stride. In
1157 /// full strength-reduction mode, all addresses at the current stride are
1158 /// strength-reduced all the way down to pointer arithmetic.
1159 ///
1160 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1161 const std::vector &UsersToProcess,
1162 const Loop *L,
1163 bool AllUsesAreAddresses,
1164 const SCEV *Stride) {
1165 if (!EnableFullLSRMode)
1166 return false;
1167
1168 // The heuristics below aim to avoid increasing register pressure, but
1169 // fully strength-reducing all the addresses increases the number of
1170 // add instructions, so don't do this when optimizing for size.
1171 // TODO: If the loop is large, the savings due to simpler addresses
1172 // may oughtweight the costs of the extra increment instructions.
1173 if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1174 return false;
1175
1176 // TODO: For now, don't do full strength reduction if there could
1177 // potentially be greater-stride multiples of the current stride
1178 // which could reuse the current stride IV.
1179 if (IU->StrideOrder.back() != Stride)
1180 return false;
1181
1182 // Iterate through the uses to find conditions that automatically rule out
1183 // full-lsr mode.
1184 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1185 const SCEV *Base = UsersToProcess[i].Base;
1186 const SCEV *Imm = UsersToProcess[i].Imm;
1187 // If any users have a loop-variant component, they can't be fully
1188 // strength-reduced.
1189 if (Imm && !Imm->isLoopInvariant(L))
1190 return false;
1191 // If there are to users with the same base and the difference between
1192 // the two Imm values can't be folded into the address, full
1193 // strength reduction would increase register pressure.
1194 do {
1195 const SCEV *CurImm = UsersToProcess[i].Imm;
1196 if ((CurImm || Imm) && CurImm != Imm) {
1197 if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1198 if (!Imm) Imm = SE->getIntegerSCEV(0, Stride->getType());
1199 const Instruction *Inst = UsersToProcess[i].Inst;
1200 const Type *AccessTy = getAccessType(Inst);
1201 const SCEV *Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1202 if (!Diff->isZero() &&
1203 (!AllUsesAreAddresses ||
1204 !fitsInAddressMode(Diff, AccessTy, TLI, /*HasBaseReg=*/true)))
1205 return false;
1206 }
1207 } while (++i != e && Base == UsersToProcess[i].Base);
1208 }
1209
1210 // If there's exactly one user in this stride, fully strength-reducing it
1211 // won't increase register pressure. If it's starting from a non-zero base,
1212 // it'll be simpler this way.
1213 if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1214 return true;
1215
1216 // Otherwise, if there are any users in this stride that don't require
1217 // a register for their base, full strength-reduction will increase
1218 // register pressure.
1219 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1220 if (UsersToProcess[i].Base->isZero())
1221 return false;
1222
1223 // Otherwise, go for it.
1224 return true;
1225 }
1226
1227 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1228 /// with the specified start and step values in the specified loop.
1229 ///
1230 /// If NegateStride is true, the stride should be negated by using a
1231 /// subtract instead of an add.
1232 ///
1233 /// Return the created phi node.
1234 ///
1235 static PHINode *InsertAffinePhi(const SCEV *Start, const SCEV *Step,
1236 Instruction *IVIncInsertPt,
1237 const Loop *L,
1238 SCEVExpander &Rewriter) {
1239 assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1240 assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1241
1242 BasicBlock *Header = L->getHeader();
1243 BasicBlock *Preheader = L->getLoopPreheader();
1244 BasicBlock *LatchBlock = L->getLoopLatch();
1245 const Type *Ty = Start->getType();
1246 Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1247
1248 PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1249 PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1250 Preheader);
1251
1252 // If the stride is negative, insert a sub instead of an add for the
1253 // increment.
1254 bool isNegative = isNonConstantNegative(Step);
1255 const SCEV *IncAmount = Step;
1256 if (isNegative)
1257 IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1258
1259 // Insert an add instruction right before the terminator corresponding
1260 // to the back-edge or just before the only use. The location is determined
1261 // by the caller and passed in as IVIncInsertPt.
1262 Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1263 Preheader->getTerminator());
1264 Instruction *IncV;
1265 if (isNegative) {
1266 IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1267 IVIncInsertPt);
1268 } else {
1269 IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1270 IVIncInsertPt);
1271 }
1272 if (!isa(StepV)) ++NumVariable;
1273
1274 PN->addIncoming(IncV, LatchBlock);
1275
1276 ++NumInserted;
1277 return PN;
1278 }
1279
1280 static void SortUsersToProcess(std::vector &UsersToProcess) {
1281 // We want to emit code for users inside the loop first. To do this, we
1282 // rearrange BasedUser so that the entries at the end have
1283 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1284 // vector (so we handle them first).
1285 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1286 PartitionByIsUseOfPostIncrementedValue);
1287
1288 // Sort this by base, so that things with the same base are handled
1289 // together. By partitioning first and stable-sorting later, we are
1290 // guaranteed that within each base we will pop off users from within the
1291 // loop before users outside of the loop with a particular base.
1292 //
1293 // We would like to use stable_sort here, but we can't. The problem is that
1294 // const SCEV *'s don't have a deterministic ordering w.r.t to each other, so
1295 // we don't have anything to do a '<' comparison on. Because we think the
1296 // number of uses is small, do a horrible bubble sort which just relies on
1297 // ==.
1298 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1299 // Get a base value.
1300 const SCEV *Base = UsersToProcess[i].Base;
1301
1302 // Compact everything with this base to be consecutive with this one.
1303 for (unsigned j = i+1; j != e; ++j) {
1304 if (UsersToProcess[j].Base == Base) {
1305 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1306 ++i;
1307 }
1308 }
1309 }
1310 }
1311
1312 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1313 /// UsersToProcess, meaning lowering addresses all the way down to direct
1314 /// pointer arithmetic.
1315 ///
1316 void
1317 LoopStrengthReduce::PrepareToStrengthReduceFully(
1318 std::vector &UsersToProcess,
1319 const SCEV *Stride,
1320 const SCEV *CommonExprs,
1321 const Loop *L,
1322 SCEVExpander &PreheaderRewriter) {
1323 DEBUG(dbgs() << " Fully reducing all users\n");
1324
1325 // Rewrite the UsersToProcess records, creating a separate PHI for each
1326 // unique Base value.
1327 Instruction *IVIncInsertPt = L->getLoopLatch()->getTerminator();
1328 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1329 // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1330 // pick the first Imm value here to start with, and adjust it for the
1331 // other uses.
1332 const SCEV *Imm = UsersToProcess[i].Imm;
1333 const SCEV *Base = UsersToProcess[i].Base;
1334 const SCEV *Start = SE->getAddExpr(CommonExprs, Base, Imm);
1335 PHINode *Phi = InsertAffinePhi(Start, Stride, IVIncInsertPt, L,
1336 PreheaderRewriter);
1337 // Loop over all the users with the same base.
1338 do {
1339 UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1340 UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1341 UsersToProcess[i].Phi = Phi;
1342 assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1343 "ShouldUseFullStrengthReductionMode should reject this!");
1344 } while (++i != e && Base == UsersToProcess[i].Base);
1345 }
1346 }
1347
1348 /// FindIVIncInsertPt - Return the location to insert the increment instruction.
1349 /// If the only use if a use of postinc value, (must be the loop termination
1350 /// condition), then insert it just before the use.
1351 static Instruction *FindIVIncInsertPt(std::vector &UsersToProcess,
1352 const Loop *L) {
1353 if (UsersToProcess.size() == 1 &&
1354 UsersToProcess[0].isUseOfPostIncrementedValue &&
1355 L->contains(UsersToProcess[0].Inst))
1356 return UsersToProcess[0].Inst;
1357 return L->getLoopLatch()->getTerminator();
1358 }
1359
1360 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1361 /// given users to share.
1362 ///
1363 void
1364 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1365 std::vector &UsersToProcess,
1366 const SCEV *Stride,
1367 const SCEV *CommonExprs,
1368 Value *CommonBaseV,
1369 Instruction *IVIncInsertPt,
1370 const Loop *L,
1371 SCEVExpander &PreheaderRewriter) {
1372 DEBUG(dbgs() << " Inserting new PHI:\n");
1373
1374 PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1375 Stride, IVIncInsertPt, L,
1376 PreheaderRewriter);
1377
1378 // Remember this in case a later stride is multiple of this.
1379 IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1380
1381 // All the users will share this new IV.
1382 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1383 UsersToProcess[i].Phi = Phi;
1384
1385 DEBUG(dbgs() << " IV=");
1386 DEBUG(WriteAsOperand(dbgs(), Phi, /*PrintType=*/false));
1387 DEBUG(dbgs() << "\n");
1388 }
1389
1390 /// PrepareToStrengthReduceFromSmallerStride - Prepare for the given users to
1391 /// reuse an induction variable with a stride that is a factor of the current
1392 /// induction variable.
1393 ///
1394 void
1395 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1396 std::vector &UsersToProcess,
1397 Value *CommonBaseV,
1398 const IVExpr &ReuseIV,
1399 Instruction *PreInsertPt) {
1400 DEBUG(dbgs() << " Rewriting in terms of existing IV of STRIDE "
1401 << *ReuseIV.Stride << " and BASE " << *ReuseIV.Base << "\n");
1402
1403 // All the users will share the reused IV.
1404 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1405 UsersToProcess[i].Phi = ReuseIV.PHI;
1406
1407 Constant *C = dyn_cast(CommonBaseV);
1408 if (C &&
1409 (!C->isNullValue() &&
1410 !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1411 TLI, false)))
1412 // We want the common base emitted into the preheader! This is just
1413 // using cast as a copy so BitCast (no-op cast) is appropriate
1414 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1415 "commonbase", PreInsertPt);
1416 }
1417
1418 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1419 const Type *AccessTy,
1420 std::vector &UsersToProcess,
1421 const TargetLowering *TLI) {
1422 SmallVector AddrModeInsts;
1423 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1424 if (UsersToProcess[i].isUseOfPostIncrementedValue)
1425 continue;
1426 ExtAddrMode AddrMode =
1427 AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1428 AccessTy, UsersToProcess[i].Inst,
1429 AddrModeInsts, *TLI);
1430 if (GV && GV != AddrMode.BaseGV)
1431 return false;
1432 if (Offset && !AddrMode.BaseOffs)
1433 // FIXME: How to accurate check it's immediate offset is folded.
1434 return false;
1435 AddrModeInsts.clear();
1436 }
1437 return true;
1438 }
1439
1440 /// StrengthReduceIVUsersOfStride - Strength reduce all of the users of a single
1441 /// stride of IV. All of the users may have different starting values, and this
1442 /// may not be the only stride.
1443 void
1444 LoopStrengthReduce::StrengthReduceIVUsersOfStride(const SCEV *Stride,
1445 IVUsersOfOneStride &Uses,
1446 Loop *L) {
1447 // If all the users are moved to another stride, then there is nothing to do.
1448 if (Uses.Users.empty())
1449 return;
1450
1451 // Keep track if every use in UsersToProcess is an address. If they all are,
1452 // we may be able to rewrite the entire collection of them in terms of a
1453 // smaller-stride IV.
1454 bool AllUsesAreAddresses = true;
1455
1456 // Keep track if every use of a single stride is outside the loop. If so,
1457 // we want to be more aggressive about reusing a smaller-stride IV; a
1458 // multiply outside the loop is better than another IV inside. Well, usually.
1459 bool AllUsesAreOutsideLoop = true;
1460
1461 // Transform our list of users and offsets to a bit more complex table. In
1462 // this new vector, each 'BasedUser' contains 'Base' the base of the strided
1463 // access as well as the old information from Uses. We progressively move
1464 // information from the Base field to the Imm field until we eventually have
1465 // the full access expression to rewrite the use.
1466 std::vector UsersToProcess;
1467 const SCEV *CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1468 AllUsesAreOutsideLoop,
1469 UsersToProcess);
1470
1471 // Sort the UsersToProcess array so that users with common bases are
1472 // next to each other.
1473 SortUsersToProcess(UsersToProcess);
1474
1475 // If we managed to find some expressions in common, we'll need to carry
1476 // their value in a register and add it in for each use. This will take up
1477 // a register operand, which potentially restricts what stride values are
1478 // valid.
1479 bool HaveCommonExprs = !CommonExprs->isZero();
1480 const Type *ReplacedTy = CommonExprs->getType();
1481
1482 // If all uses are addresses, consider sinking the immediate part of the
1483 // common expression back into uses if they can fit in the immediate fields.
1484 if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1485 const SCEV *NewCommon = CommonExprs;
1486 const SCEV *Imm = SE->getIntegerSCEV(0, ReplacedTy);
1487 MoveImmediateValues(TLI, Type::getVoidTy(
1488 L->getLoopPreheader()->getContext()),
1489 NewCommon, Imm, true, L, SE);
1490 if (!Imm->isZero()) {
1491 bool DoSink = true;
1492
1493 // If the immediate part of the common expression is a GV, check if it's
1494 // possible to fold it into the target addressing mode.
1495 GlobalValue *GV = 0;
1496 if (const SCEVUnknown *SU = dyn_cast(Imm))
1497 GV = dyn_cast(SU->getValue());
1498 int64_t Offset = 0;
1499 if (const SCEVConstant *SC = dyn_cast(Imm))
1500 Offset = SC->getValue()->getSExtValue();
1501 if (GV || Offset)
1502 // Pass VoidTy as the AccessTy to be conservative, because
1503 // there could be multiple access types among all the uses.
1504 DoSink = IsImmFoldedIntoAddrMode(GV, Offset,
1505 Type::getVoidTy(L->getLoopPreheader()->getContext()),
1506 UsersToProcess, TLI);
1507
1508 if (DoSink) {
1509 DEBUG(dbgs() << " Sinking " << *Imm << " back down into uses\n");
1510 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1511 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1512 CommonExprs = NewCommon;
1513 HaveCommonExprs = !CommonExprs->isZero();
1514 ++NumImmSunk;
1515 }
1516 }
1517 }
1518
1519 // Now that we know what we need to do, insert the PHI node itself.
1520 //
1521 DEBUG(dbgs() << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1522 << *Stride << ":\n"
1523 << " Common base: " << *CommonExprs << '\n');
1524
1525 SCEVExpander Rewriter(*SE);
1526 SCEVExpander PreheaderRewriter(*SE);
1527
1528 BasicBlock *Preheader = L->getLoopPreheader();
1529 Instruction *PreInsertPt = Preheader->getTerminator();
1530 BasicBlock *LatchBlock = L->getLoopLatch();
1531 Instruction *IVIncInsertPt = LatchBlock->getTerminator();
1532
1533 Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1534
1535 const SCEV *RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1536 IVExpr ReuseIV(SE->getIntegerSCEV(0,
1537 Type::getInt32Ty(Preheader->getContext())),
1538 SE->getIntegerSCEV(0,
1539 Type::getInt32Ty(Preheader->getContext())),
1540 0);
1541
1542 // Choose a strength-reduction strategy and prepare for it by creating
1543 // the necessary PHIs and adjusting the bookkeeping.
1544 if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1545 AllUsesAreAddresses, Stride)) {
1546 PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1547 PreheaderRewriter);
1548 } else {
1549 // Emit the initial base value into the loop preheader.
1550 CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1551 PreInsertPt);
1552
1553 // If all uses are addresses, check if it is possible to reuse an IV. The
1554 // new IV must have a stride that is a multiple of the old stride; the
1555 // multiple must be a number that can be encoded in the scale field of the
1556 // target addressing mode; and we must have a valid instruction after this
1557 // substitution, including the immediate field, if any.
1558 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1559 AllUsesAreOutsideLoop,
1560 Stride, ReuseIV, ReplacedTy,
1561 UsersToProcess);
1562 if (!RewriteFactor->isZero())
1563 PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1564 ReuseIV, PreInsertPt);
1565 else {
1566 IVIncInsertPt = FindIVIncInsertPt(UsersToProcess, L);
1567 PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1568 CommonBaseV, IVIncInsertPt,
1569 L, PreheaderRewriter);
1570 }
1571 }
1572
1573 // Process all the users now, replacing their strided uses with
1574 // strength-reduced forms. This outer loop handles all bases, the inner
1575 // loop handles all users of a particular base.
1576 while (!UsersToProcess.empty()) {
1577 const SCEV *Base = UsersToProcess.back().Base;
1578 Instruction *Inst = UsersToProcess.back().Inst;
1579
1580 // Emit the code for Base into the preheader.
1581 Value *BaseV = 0;
1582 if (!Base->isZero()) {
1583 BaseV = PreheaderRewriter.expandCodeFor(Base, 0, PreInsertPt);
1584
1585 DEBUG(dbgs() << " INSERTING code for BASE = " << *Base << ":");
1586 if (BaseV->hasName())
1587 DEBUG(dbgs() << " Result value name = %" << BaseV->getName());
1588 DEBUG(dbgs() << "\n");
1589
1590 // If BaseV is a non-zero constant, make sure that it gets inserted into
1591 // the preheader, instead of being forward substituted into the uses. We
1592 // do this by forcing a BitCast (noop cast) to be inserted into the
1593 // preheader in this case.
1594 if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false) &&
1595 isa(BaseV)) {
1596 // We want this constant emitted into the preheader! This is just
1597 // using cast as a copy so BitCast (no-op cast) is appropriate
1598 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1599 PreInsertPt);
1600 }
1601 }
1602
1603 // Emit the code to add the immediate offset to the Phi value, just before
1604 // the instructions that we identified as using this stride and base.
1605 do {
1606 // FIXME: Use emitted users to emit other users.
1607 BasedUser &User = UsersToProcess.back();
1608
1609 DEBUG(dbgs() << " Examining ");
1610 if (User.isUseOfPostIncrementedValue)
1611 DEBUG(dbgs() << "postinc");
1612 else
1613 DEBUG(dbgs() << "preinc");
1614 DEBUG(dbgs() << " use ");
1615 DEBUG(WriteAsOperand(dbgs(), UsersToProcess.back().OperandValToReplace,
1616 /*PrintType=*/false));
1617 DEBUG(dbgs() << " in Inst: " << *User.Inst << '\n');
1618
1619 // If this instruction wants to use the post-incremented value, move it
1620 // after the post-inc and use its value instead of the PHI.
1621 Value *RewriteOp = User.Phi;
1622 if (User.isUseOfPostIncrementedValue) {
1623 RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1624 // If this user is in the loop, make sure it is the last thing in the
1625 // loop to ensure it is dominated by the increment. In case it's the
1626 // only use of the iv, the increment instruction is already before the
1627 // use.
1628 if (L->contains(User.Inst) && User.Inst != IVIncInsertPt)
1629 User.Inst->moveBefore(IVIncInsertPt);
1630 }
1631
1632 const SCEV *RewriteExpr = SE->getUnknown(RewriteOp);
1633
1634 if (SE->getEffectiveSCEVType(RewriteOp->getType()) !=
1635 SE->getEffectiveSCEVType(ReplacedTy)) {
1636 assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1637 SE->getTypeSizeInBits(ReplacedTy) &&
1638 "Unexpected widening cast!");
1639 RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1640 }
1641
1642 // If we had to insert new instructions for RewriteOp, we have to
1643 // consider that they may not have been able to end up immediately
1644 // next to RewriteOp, because non-PHI instructions may never precede
1645 // PHI instructions in a block. In this case, remember where the last
1646 // instruction was inserted so that if we're replacing a different
1647 // PHI node, we can use the later point to expand the final
1648 // RewriteExpr.
1649 Instruction *NewBasePt = dyn_cast(RewriteOp);
1650 if (RewriteOp == User.Phi) NewBasePt = 0;
1651
1652 // Clear the SCEVExpander's expression map so that we are guaranteed
1653 // to have the code emitted where we expect it.
1654 Rewriter.clear();
1655
1656 // If we are reusing the iv, then it must be multiplied by a constant
1657 // factor to take advantage of the addressing mode scale component.
1658 if (!RewriteFactor->isZero()) {
1659 // If we're reusing an IV with a nonzero base (currently this happens
1660 // only when all reuses are outside the loop) subtract that base here.
1661 // The base has been used to initialize the PHI node but we don't want
1662 // it here.
1663 if (!ReuseIV.Base->isZero()) {
1664 const SCEV *typedBase = ReuseIV.Base;
1665 if (SE->getEffectiveSCEVType(RewriteExpr->getType()) !=
1666 SE->getEffectiveSCEVType(ReuseIV.Base->getType())) {
1667 // It's possible the original IV is a larger type than the new IV,
1668 // in which case we have to truncate the Base. We checked in
1669 // RequiresTypeConversion that this is valid.
1670 assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1671 SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1672 "Unexpected lengthening conversion!");
1673 typedBase = SE->getTruncateExpr(ReuseIV.Base,
1674 RewriteExpr->getType());
1675 }
1676 RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1677 }
1678
1679 // Multiply old variable, with base removed, by new scale factor.
1680 RewriteExpr = SE->getMulExpr(RewriteFactor,
1681 RewriteExpr);
1682
1683 // The common base is emitted in the loop preheader. But since we
1684 // are reusing an IV, it has not been used to initialize the PHI node.
1685 // Add it to the expression used to rewrite the uses.
1686 // When this use is outside the loop, we earlier subtracted the
1687 // common base, and are adding it back here. Use the same expression
1688 // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1689 if (!CommonExprs->isZero()) {
1690 if (L->contains(User.Inst))
1691 RewriteExpr = SE->getAddExpr(RewriteExpr,
1692 SE->getUnknown(CommonBaseV));
1693 else
1694 RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1695 }
1696 }
1697
1698 // Now that we know what we need to do, insert code before User for the
1699 // immediate and any loop-variant expressions.
1700 if (BaseV)
1701 // Add BaseV to the PHI value if needed.
1702 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1703
1704 User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1705 Rewriter, L, this,
1706 DeadInsts, SE);
1707
1708 // Mark old value we replaced as possibly dead, so that it is eliminated
1709 // if we just replaced the last use of that value.
1710 DeadInsts.push_back(User.OperandValToReplace);
1711
1712 UsersToProcess.pop_back();
1713 ++NumReduced;
1714
1715 // If there are any more users to process with the same base, process them
1716 // now. We sorted by base above, so we just have to check the last elt.
1717 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1718 // TODO: Next, find out which base index is the most common, pull it out.
1719 }
1720
1721 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1722 // different starting values, into different PHIs.
1723 }
1724
1725 void LoopStrengthReduce::StrengthReduceIVUsers(Loop *L) {
1726 // Note: this processes each stride/type pair individually. All users
1727 // passed into StrengthReduceIVUsersOfStride have the same type AND stride.
1728 // Also, note that we iterate over IVUsesByStride indirectly by using
1729 // StrideOrder. This extra layer of indirection makes the ordering of
1730 // strides deterministic - not dependent on map order.
1731 for (unsigned Stride = 0, e = IU->StrideOrder.size(); Stride != e; ++Stride) {
1732 std::map::iterator SI =
1733 IU->IVUsesByStride.find(IU->StrideOrder[Stride]);
1734 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
1735 // FIXME: Generalize to non-affine IV's.
1736 if (!SI->first->isLoopInvariant(L))
1737 continue;
1738 StrengthReduceIVUsersOfStride(SI->first, *SI->second, L);
1276
1277 if (!C) continue;
1278
1279 // Ignore negative constants, as the code below doesn't handle them
1280 // correct