blob: 191fcc02c4b032dfb552a8034b48d6750ea2b335 [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman36f891b2005-07-30 00:12:19 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution expander,
11// which is used to generate the code corresponding to a given scalar evolution
12// expression.
13//
14//===----------------------------------------------------------------------===//
15
Nate Begeman36f891b2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000017#include "llvm/Analysis/LoopInfo.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000018#include "llvm/Target/TargetData.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000019using namespace llvm;
20
Chris Lattnerca1a4be2006-02-04 09:51:53 +000021/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000023Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
24 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +000025 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
27 return V;
28
Dan Gohmanf04fa482009-04-16 15:52:57 +000029 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohmanaf79fb52009-04-21 01:07:12 +000030 if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000031 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000032 if (CastInst *CI = dyn_cast<CastInst>(V))
33 if ((CI->getOpcode() == Instruction::PtrToInt ||
34 CI->getOpcode() == Instruction::IntToPtr) &&
35 SE.getTypeSizeInBits(CI->getType()) ==
36 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
37 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000038 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
39 if ((CE->getOpcode() == Instruction::PtrToInt ||
40 CE->getOpcode() == Instruction::IntToPtr) &&
41 SE.getTypeSizeInBits(CE->getType()) ==
42 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
43 return CE->getOperand(0);
44 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000045
Chris Lattnerca1a4be2006-02-04 09:51:53 +000046 // FIXME: keep track of the cast instruction.
47 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000048 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000049
50 if (Argument *A = dyn_cast<Argument>(V)) {
51 // Check to see if there is already a cast!
52 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
53 UI != E; ++UI) {
54 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000055 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
56 if (CI->getOpcode() == opcode) {
57 // If the cast isn't the first instruction of the function, move it.
58 if (BasicBlock::iterator(CI) !=
59 A->getParent()->getEntryBlock().begin()) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000060 // If the CastInst is the insert point, change the insert point.
61 if (CI == InsertPt) ++InsertPt;
62 // Splice the cast at the beginning of the entry block.
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000063 CI->moveBefore(A->getParent()->getEntryBlock().begin());
64 }
65 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000066 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000067 }
Dan Gohmancf5ab822009-05-01 17:13:31 +000068 Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
69 A->getParent()->getEntryBlock().begin());
70 InsertedValues.insert(I);
71 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000072 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000073
Chris Lattnerca1a4be2006-02-04 09:51:53 +000074 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000075
Chris Lattnerca1a4be2006-02-04 09:51:53 +000076 // Check to see if there is already a cast. If there is, use it.
77 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
78 UI != E; ++UI) {
79 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000080 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
81 if (CI->getOpcode() == opcode) {
82 BasicBlock::iterator It = I; ++It;
83 if (isa<InvokeInst>(I))
84 It = cast<InvokeInst>(I)->getNormalDest()->begin();
85 while (isa<PHINode>(It)) ++It;
86 if (It != BasicBlock::iterator(CI)) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000087 // If the CastInst is the insert point, change the insert point.
88 if (CI == InsertPt) ++InsertPt;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000089 // Splice the cast immediately after the operand in question.
90 CI->moveBefore(It);
91 }
92 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000093 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000094 }
95 BasicBlock::iterator IP = I; ++IP;
96 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
97 IP = II->getNormalDest()->begin();
98 while (isa<PHINode>(IP)) ++IP;
Dan Gohmancf5ab822009-05-01 17:13:31 +000099 Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
100 InsertedValues.insert(CI);
101 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000102}
103
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000104/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
105/// which must be possible with a noop cast.
106Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
107 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
108 assert((Op == Instruction::BitCast ||
Devang Patele2a17462009-04-22 18:51:05 +0000109 Op == Instruction::PtrToInt ||
110 Op == Instruction::IntToPtr) &&
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000111 "InsertNoopCastOfTo cannot perform non-noop casts!");
112 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
113 "InsertNoopCastOfTo cannot change sizes!");
114 return InsertCastOfTo(Op, V, Ty);
115}
116
Chris Lattner7fec90e2007-04-13 05:04:18 +0000117/// InsertBinop - Insert the specified binary operator, doing a small amount
118/// of work to avoid inserting an obviously redundant operation.
119Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Dan Gohman6cdc7272009-04-22 16:05:50 +0000120 Value *RHS, BasicBlock::iterator InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000121 // Fold a binop with constant operands.
122 if (Constant *CLHS = dyn_cast<Constant>(LHS))
123 if (Constant *CRHS = dyn_cast<Constant>(RHS))
124 return ConstantExpr::get(Opcode, CLHS, CRHS);
125
Chris Lattner7fec90e2007-04-13 05:04:18 +0000126 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
127 unsigned ScanLimit = 6;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000128 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
129 if (InsertPt != BlockBegin) {
130 // Scanning starts from the last instruction before InsertPt.
131 BasicBlock::iterator IP = InsertPt;
132 --IP;
133 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000134 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
135 IP->getOperand(1) == RHS)
136 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000137 if (IP == BlockBegin) break;
138 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000139 }
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000140
141 // If we haven't found this binop, insert it.
Dan Gohmancf5ab822009-05-01 17:13:31 +0000142 Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
143 InsertedValues.insert(BO);
144 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000145}
146
Dan Gohman453aa4f2009-05-24 18:06:31 +0000147/// FactorOutConstant - Test if S is evenly divisible by Factor, using signed
148/// division. If so, update S with Factor divided out and return true.
149/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
150/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
151/// check to see if the divide was folded.
152static bool FactorOutConstant(SCEVHandle &S,
153 const APInt &Factor,
154 ScalarEvolution &SE) {
155 // Everything is divisible by one.
156 if (Factor == 1)
157 return true;
158
159 // For a Constant, check for a multiple of the given factor.
160 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
161 if (!C->getValue()->getValue().srem(Factor)) {
162 ConstantInt *CI =
163 ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
164 SCEVHandle Div = SE.getConstant(CI);
165 S = Div;
166 return true;
167 }
168
169 // In a Mul, check if there is a constant operand which is a multiple
170 // of the given factor.
171 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
172 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
173 if (!C->getValue()->getValue().srem(Factor)) {
174 std::vector<SCEVHandle> NewMulOps(M->getOperands());
175 NewMulOps[0] =
176 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
177 S = SE.getMulExpr(NewMulOps);
178 return true;
179 }
180
181 // In an AddRec, check if both start and step are divisible.
182 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
183 SCEVHandle Start = A->getStart();
184 if (!FactorOutConstant(Start, Factor, SE))
185 return false;
186 SCEVHandle Step = A->getStepRecurrence(SE);
187 if (!FactorOutConstant(Step, Factor, SE))
188 return false;
189 S = SE.getAddRecExpr(Start, Step, A->getLoop());
190 return true;
191 }
192
193 return false;
194}
195
Dan Gohman5be18e82009-05-19 02:15:55 +0000196/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000197/// instead of using ptrtoint+arithmetic+inttoptr. This helps
198/// BasicAliasAnalysis analyze the result. However, it suffers from the
199/// underlying bug described in PR2831. Addition in LLVM currently always
200/// has two's complement wrapping guaranteed. However, the semantics for
201/// getelementptr overflow are ambiguous. In the common case though, this
202/// expansion gets used when a GEP in the original code has been converted
203/// into integer arithmetic, in which case the resulting code will be no
204/// more undefined than it was originally.
205///
206/// Design note: It might seem desirable for this function to be more
207/// loop-aware. If some of the indices are loop-invariant while others
208/// aren't, it might seem desirable to emit multiple GEPs, keeping the
209/// loop-invariant portions of the overall computation outside the loop.
210/// However, there are a few reasons this is not done here. Hoisting simple
211/// arithmetic is a low-level optimization that often isn't very
212/// important until late in the optimization process. In fact, passes
213/// like InstructionCombining will combine GEPs, even if it means
214/// pushing loop-invariant computation down into loops, so even if the
215/// GEPs were split here, the work would quickly be undone. The
216/// LoopStrengthReduction pass, which is usually run quite late (and
217/// after the last InstructionCombining pass), takes care of hoisting
218/// loop-invariant portions of expressions, after considering what
219/// can be folded using target addressing modes.
220///
221Value *SCEVExpander::expandAddToGEP(const SCEVHandle *op_begin,
222 const SCEVHandle *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000223 const PointerType *PTy,
224 const Type *Ty,
225 Value *V) {
226 const Type *ElTy = PTy->getElementType();
227 SmallVector<Value *, 4> GepIndices;
Dan Gohman453aa4f2009-05-24 18:06:31 +0000228 std::vector<SCEVHandle> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000229 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000230
231 // Decend down the pointer's type and attempt to convert the other
232 // operands into GEP indices, at each level. The first index in a GEP
233 // indexes into the array implied by the pointer operand; the rest of
234 // the indices index into the element or field type selected by the
235 // preceding index.
236 for (;;) {
237 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
238 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
239 std::vector<SCEVHandle> NewOps;
240 std::vector<SCEVHandle> ScaledOps;
241 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000242 // Split AddRecs up into parts as either of the parts may be usable
243 // without the other.
244 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
245 if (!A->getStart()->isZero()) {
246 SCEVHandle Start = A->getStart();
247 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
248 A->getStepRecurrence(SE),
249 A->getLoop()));
250 Ops[i] = Start;
251 ++e;
252 }
253 // If the scale size is not 0, attempt to factor out a scale.
Dan Gohman5be18e82009-05-19 02:15:55 +0000254 if (ElSize != 0) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000255 SCEVHandle Op = Ops[i];
256 if (FactorOutConstant(Op, ElSize, SE)) {
257 ScaledOps.push_back(Op); // Op now has ElSize factored out.
Dan Gohman5be18e82009-05-19 02:15:55 +0000258 continue;
259 }
260 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000261 // If the operand was not divisible, add it to the list of operands
262 // we'll scan next iteration.
Dan Gohman5be18e82009-05-19 02:15:55 +0000263 NewOps.push_back(Ops[i]);
264 }
265 Ops = NewOps;
266 AnyNonZeroIndices |= !ScaledOps.empty();
267 Value *Scaled = ScaledOps.empty() ?
268 Constant::getNullValue(Ty) :
269 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
270 GepIndices.push_back(Scaled);
271
272 // Collect struct field index operands.
273 if (!Ops.empty())
274 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
275 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
276 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
277 const StructLayout &SL = *SE.TD->getStructLayout(STy);
278 uint64_t FullOffset = C->getValue()->getZExtValue();
279 if (FullOffset < SL.getSizeInBytes()) {
280 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
281 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
282 ElTy = STy->getTypeAtIndex(ElIdx);
283 Ops[0] =
284 SE.getConstant(ConstantInt::get(Ty,
285 FullOffset -
286 SL.getElementOffset(ElIdx)));
287 AnyNonZeroIndices = true;
288 continue;
289 }
290 }
291 break;
292 }
293
294 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
295 ElTy = ATy->getElementType();
296 continue;
297 }
298 break;
299 }
300
301 // If none of the operands were convertable to proper GEP indices, cast
302 // the base to i8* and do an ugly getelementptr with that. It's still
303 // better than ptrtoint+arithmetic+inttoptr at least.
304 if (!AnyNonZeroIndices) {
305 V = InsertNoopCastOfTo(V,
306 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
307 Value *Idx = expand(SE.getAddExpr(Ops));
308 Idx = InsertNoopCastOfTo(Idx, Ty);
309
310 // Fold a GEP with constant operands.
311 if (Constant *CLHS = dyn_cast<Constant>(V))
312 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000313 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000314
315 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
316 unsigned ScanLimit = 6;
317 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
318 if (InsertPt != BlockBegin) {
319 // Scanning starts from the last instruction before InsertPt.
320 BasicBlock::iterator IP = InsertPt;
321 --IP;
322 for (; ScanLimit; --IP, --ScanLimit) {
323 if (IP->getOpcode() == Instruction::GetElementPtr &&
324 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
325 return IP;
326 if (IP == BlockBegin) break;
327 }
328 }
329
330 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
331 InsertedValues.insert(GEP);
332 return GEP;
333 }
334
335 // Insert a pretty getelementptr.
336 Value *GEP = GetElementPtrInst::Create(V,
337 GepIndices.begin(),
338 GepIndices.end(),
339 "scevgep", InsertPt);
340 Ops.push_back(SE.getUnknown(GEP));
341 InsertedValues.insert(GEP);
342 return expand(SE.getAddExpr(Ops));
343}
344
Dan Gohman890f92b2009-04-18 17:56:28 +0000345Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000346 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000347 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000348
Dan Gohman453aa4f2009-05-24 18:06:31 +0000349 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
350 // comments on expandAddToGEP for details.
Dan Gohman5be18e82009-05-19 02:15:55 +0000351 if (SE.TD)
Dan Gohman453aa4f2009-05-24 18:06:31 +0000352 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
353 const std::vector<SCEVHandle> &Ops = S->getOperands();
Dan Gohmanfb5a3412009-05-24 19:02:45 +0000354 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1],
Dan Gohman453aa4f2009-05-24 18:06:31 +0000355 PTy, Ty, V);
356 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000357
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000358 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000359
360 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000361 for (int i = S->getNumOperands()-2; i >= 0; --i) {
362 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000363 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000364 V = InsertBinop(Instruction::Add, V, W, InsertPt);
365 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000366 return V;
367}
Dan Gohman5be18e82009-05-19 02:15:55 +0000368
Dan Gohman890f92b2009-04-18 17:56:28 +0000369Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000370 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000371 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000372 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000373 if (SC->getValue()->isAllOnesValue())
374 FirstOp = 1;
375
376 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000377 Value *V = expand(S->getOperand(i+1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000378 V = InsertNoopCastOfTo(V, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000379
380 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000381 for (; i >= FirstOp; --i) {
382 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000383 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000384 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
385 }
386
Nate Begeman36f891b2005-07-30 00:12:19 +0000387 // -1 * ... ---> 0 - ...
388 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000389 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000390 return V;
391}
392
Dan Gohman890f92b2009-04-18 17:56:28 +0000393Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000394 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000395
Nick Lewycky6177fd42008-07-08 05:05:37 +0000396 Value *LHS = expand(S->getLHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000397 LHS = InsertNoopCastOfTo(LHS, Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000398 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000399 const APInt &RHS = SC->getValue()->getValue();
400 if (RHS.isPowerOf2())
401 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000402 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000403 InsertPt);
404 }
405
406 Value *RHS = expand(S->getRHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000407 RHS = InsertNoopCastOfTo(RHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000408 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
409}
410
Dan Gohman453aa4f2009-05-24 18:06:31 +0000411/// Move parts of Base into Rest to leave Base with the minimal
412/// expression that provides a pointer operand suitable for a
413/// GEP expansion.
414static void ExposePointerBase(SCEVHandle &Base, SCEVHandle &Rest,
415 ScalarEvolution &SE) {
416 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
417 Base = A->getStart();
418 Rest = SE.getAddExpr(Rest,
419 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
420 A->getStepRecurrence(SE),
421 A->getLoop()));
422 }
423 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
424 Base = A->getOperand(A->getNumOperands()-1);
425 std::vector<SCEVHandle> NewAddOps(A->op_begin(), A->op_end());
426 NewAddOps.back() = Rest;
427 Rest = SE.getAddExpr(NewAddOps);
428 ExposePointerBase(Base, Rest, SE);
429 }
430}
431
Dan Gohman890f92b2009-04-18 17:56:28 +0000432Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000433 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000434 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000435
436 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000437 if (!S->getStart()->isZero()) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000438 std::vector<SCEVHandle> NewOps(S->getOperands());
Dan Gohman246b2562007-10-22 18:31:58 +0000439 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000440 SCEVHandle Rest = SE.getAddRecExpr(NewOps, L);
441
442 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
443 // comments on expandAddToGEP for details.
444 if (SE.TD) {
445 SCEVHandle Base = S->getStart();
446 SCEVHandle RestArray[1] = Rest;
447 // Dig into the expression to find the pointer base for a GEP.
448 ExposePointerBase(Base, RestArray[0], SE);
449 // If we found a pointer, expand the AddRec with a GEP.
450 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
451 Value *StartV = expand(Base);
452 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
453 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
454 }
455 }
456
457 Value *RestV = expand(Rest);
458 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(RestV)));
Nate Begeman36f891b2005-07-30 00:12:19 +0000459 }
460
461 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000462 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000463 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000464 // Create and insert the PHI node for the induction variable in the
465 // specified loop.
466 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000467 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000468 InsertedValues.insert(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000469 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
470
471 pred_iterator HPI = pred_begin(Header);
472 assert(HPI != pred_end(Header) && "Loop with zero preds???");
473 if (!L->contains(*HPI)) ++HPI;
474 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
475 "No backedge in loop?");
476
477 // Insert a unit add instruction right before the terminator corresponding
478 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000479 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000480 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000481 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000482 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000483
484 pred_iterator PI = pred_begin(Header);
485 if (*PI == L->getLoopPreheader())
486 ++PI;
487 PN->addIncoming(Add, *PI);
488 return PN;
489 }
490
491 // Get the canonical induction variable I for this loop.
492 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
493
Chris Lattnerdf14a042005-10-30 06:24:33 +0000494 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000495 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000496 Value *F = expand(S->getOperand(1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000497 F = InsertNoopCastOfTo(F, Ty);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000498
499 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000500 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000501 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000502 return I;
503
504 // If the insert point is directly inside of the loop, emit the multiply at
505 // the insert point. Otherwise, L is a loop that is a parent of the insert
506 // point loop. If we can, move the multiply to the outer most loop that it
507 // is safe to be in.
Dan Gohman6cdc7272009-04-22 16:05:50 +0000508 BasicBlock::iterator MulInsertPt = getInsertionPoint();
Dan Gohman5be18e82009-05-19 02:15:55 +0000509 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
Chris Lattnerdf14a042005-10-30 06:24:33 +0000510 if (InsertPtLoop != L && InsertPtLoop &&
511 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000512 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000513 // If we cannot hoist the multiply out of this loop, don't.
514 if (!InsertPtLoop->isLoopInvariant(F)) break;
515
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000516 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
517
518 // If this loop hasn't got a preheader, we aren't able to hoist the
519 // multiply.
520 if (!InsertPtLoopPH)
521 break;
522
523 // Otherwise, move the insert point to the preheader.
524 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000525 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000526 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000527 }
528
Chris Lattner7fec90e2007-04-13 05:04:18 +0000529 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000530 }
531
532 // If this is a chain of recurrences, turn it into a closed form, using the
533 // folders, then expandCodeFor the closed form. This allows the folders to
534 // simplify the expression without having to build a bunch of special code
535 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000536 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000537
Dan Gohman246b2562007-10-22 18:31:58 +0000538 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000539 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000540
Dan Gohmand19534a2007-06-15 14:38:12 +0000541 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000542}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000543
Dan Gohman890f92b2009-04-18 17:56:28 +0000544Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000545 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000546 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000547 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000548 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
549 InsertedValues.insert(I);
550 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000551}
552
Dan Gohman890f92b2009-04-18 17:56:28 +0000553Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000554 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000555 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000556 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000557 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
558 InsertedValues.insert(I);
559 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000560}
561
Dan Gohman890f92b2009-04-18 17:56:28 +0000562Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000563 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000564 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000565 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000566 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
567 InsertedValues.insert(I);
568 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000569}
570
Dan Gohman890f92b2009-04-18 17:56:28 +0000571Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000572 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000573 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000574 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000575 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
576 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000577 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000578 Instruction *ICmp =
579 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
580 InsertedValues.insert(ICmp);
581 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
582 InsertedValues.insert(Sel);
583 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000584 }
585 return LHS;
586}
587
Dan Gohman890f92b2009-04-18 17:56:28 +0000588Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000589 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000590 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000591 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000592 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
593 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000594 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000595 Instruction *ICmp =
596 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
597 InsertedValues.insert(ICmp);
598 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
599 InsertedValues.insert(Sel);
600 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000601 }
602 return LHS;
603}
604
Dan Gohman752ec7d2009-04-23 15:16:49 +0000605Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000606 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000607 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000608 if (Ty) {
609 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
610 "non-trivial casts should be done with the SCEVs directly!");
611 V = InsertNoopCastOfTo(V, Ty);
612 }
613 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000614}
615
Dan Gohman890f92b2009-04-18 17:56:28 +0000616Value *SCEVExpander::expand(const SCEV *S) {
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000617 // Check to see if we already expanded this.
Torok Edwin3790fb02009-05-24 19:36:09 +0000618 std::map<SCEVHandle, AssertingVH<Value> >::iterator I =
619 InsertedExpressions.find(S);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000620 if (I != InsertedExpressions.end())
621 return I->second;
622
623 Value *V = visit(S);
624 InsertedExpressions[S] = V;
625 return V;
626}