blob: ef77e46fc99ab6e2fad869ae4177ab4ff70a596f [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 Gohman4a4f7672009-05-27 02:00:53 +0000147/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000148/// division. If so, update S with Factor divided out and return true.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000149/// S need not be evenly divisble if a reasonable remainder can be
150/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000151/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
152/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
153/// check to see if the divide was folded.
154static bool FactorOutConstant(SCEVHandle &S,
Dan Gohman4a4f7672009-05-27 02:00:53 +0000155 SCEVHandle &Remainder,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000156 const APInt &Factor,
157 ScalarEvolution &SE) {
158 // Everything is divisible by one.
159 if (Factor == 1)
160 return true;
161
162 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000163 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
164 ConstantInt *CI =
165 ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
166 // If the quotient is zero and the remainder is non-zero, reject
167 // the value at this scale. It will be considered for subsequent
168 // smaller scales.
169 if (C->isZero() || !CI->isZero()) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000170 SCEVHandle Div = SE.getConstant(CI);
171 S = Div;
Dan Gohman4a4f7672009-05-27 02:00:53 +0000172 Remainder =
173 SE.getAddExpr(Remainder,
174 SE.getConstant(C->getValue()->getValue().srem(Factor)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000175 return true;
176 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000177 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000178
179 // In a Mul, check if there is a constant operand which is a multiple
180 // of the given factor.
181 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
182 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
183 if (!C->getValue()->getValue().srem(Factor)) {
184 std::vector<SCEVHandle> NewMulOps(M->getOperands());
185 NewMulOps[0] =
186 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
187 S = SE.getMulExpr(NewMulOps);
188 return true;
189 }
190
191 // In an AddRec, check if both start and step are divisible.
192 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000193 SCEVHandle Step = A->getStepRecurrence(SE);
Dan Gohman4a4f7672009-05-27 02:00:53 +0000194 SCEVHandle StepRem = SE.getIntegerSCEV(0, Step->getType());
195 if (!FactorOutConstant(Step, StepRem, Factor, SE))
196 return false;
197 if (!StepRem->isZero())
198 return false;
199 SCEVHandle Start = A->getStart();
200 if (!FactorOutConstant(Start, Remainder, Factor, SE))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000201 return false;
202 S = SE.getAddRecExpr(Start, Step, A->getLoop());
203 return true;
204 }
205
206 return false;
207}
208
Dan Gohman5be18e82009-05-19 02:15:55 +0000209/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000210/// instead of using ptrtoint+arithmetic+inttoptr. This helps
211/// BasicAliasAnalysis analyze the result. However, it suffers from the
212/// underlying bug described in PR2831. Addition in LLVM currently always
213/// has two's complement wrapping guaranteed. However, the semantics for
214/// getelementptr overflow are ambiguous. In the common case though, this
215/// expansion gets used when a GEP in the original code has been converted
216/// into integer arithmetic, in which case the resulting code will be no
217/// more undefined than it was originally.
218///
219/// Design note: It might seem desirable for this function to be more
220/// loop-aware. If some of the indices are loop-invariant while others
221/// aren't, it might seem desirable to emit multiple GEPs, keeping the
222/// loop-invariant portions of the overall computation outside the loop.
223/// However, there are a few reasons this is not done here. Hoisting simple
224/// arithmetic is a low-level optimization that often isn't very
225/// important until late in the optimization process. In fact, passes
226/// like InstructionCombining will combine GEPs, even if it means
227/// pushing loop-invariant computation down into loops, so even if the
228/// GEPs were split here, the work would quickly be undone. The
229/// LoopStrengthReduction pass, which is usually run quite late (and
230/// after the last InstructionCombining pass), takes care of hoisting
231/// loop-invariant portions of expressions, after considering what
232/// can be folded using target addressing modes.
233///
234Value *SCEVExpander::expandAddToGEP(const SCEVHandle *op_begin,
235 const SCEVHandle *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000236 const PointerType *PTy,
237 const Type *Ty,
238 Value *V) {
239 const Type *ElTy = PTy->getElementType();
240 SmallVector<Value *, 4> GepIndices;
Dan Gohman453aa4f2009-05-24 18:06:31 +0000241 std::vector<SCEVHandle> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000242 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000243
244 // Decend down the pointer's type and attempt to convert the other
245 // operands into GEP indices, at each level. The first index in a GEP
246 // indexes into the array implied by the pointer operand; the rest of
247 // the indices index into the element or field type selected by the
248 // preceding index.
249 for (;;) {
250 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
251 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
252 std::vector<SCEVHandle> NewOps;
253 std::vector<SCEVHandle> ScaledOps;
254 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000255 // Split AddRecs up into parts as either of the parts may be usable
256 // without the other.
257 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
258 if (!A->getStart()->isZero()) {
259 SCEVHandle Start = A->getStart();
260 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
261 A->getStepRecurrence(SE),
262 A->getLoop()));
263 Ops[i] = Start;
264 ++e;
265 }
266 // If the scale size is not 0, attempt to factor out a scale.
Dan Gohman5be18e82009-05-19 02:15:55 +0000267 if (ElSize != 0) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000268 SCEVHandle Op = Ops[i];
Dan Gohman4a4f7672009-05-27 02:00:53 +0000269 SCEVHandle Remainder = SE.getIntegerSCEV(0, Op->getType());
270 if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000271 ScaledOps.push_back(Op); // Op now has ElSize factored out.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000272 NewOps.push_back(Remainder);
Dan Gohman5be18e82009-05-19 02:15:55 +0000273 continue;
274 }
275 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000276 // If the operand was not divisible, add it to the list of operands
277 // we'll scan next iteration.
Dan Gohman5be18e82009-05-19 02:15:55 +0000278 NewOps.push_back(Ops[i]);
279 }
280 Ops = NewOps;
281 AnyNonZeroIndices |= !ScaledOps.empty();
282 Value *Scaled = ScaledOps.empty() ?
283 Constant::getNullValue(Ty) :
284 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
285 GepIndices.push_back(Scaled);
286
287 // Collect struct field index operands.
288 if (!Ops.empty())
289 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
290 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
291 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
292 const StructLayout &SL = *SE.TD->getStructLayout(STy);
293 uint64_t FullOffset = C->getValue()->getZExtValue();
294 if (FullOffset < SL.getSizeInBytes()) {
295 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
296 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
297 ElTy = STy->getTypeAtIndex(ElIdx);
298 Ops[0] =
299 SE.getConstant(ConstantInt::get(Ty,
300 FullOffset -
301 SL.getElementOffset(ElIdx)));
302 AnyNonZeroIndices = true;
303 continue;
304 }
305 }
306 break;
307 }
308
309 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
310 ElTy = ATy->getElementType();
311 continue;
312 }
313 break;
314 }
315
316 // If none of the operands were convertable to proper GEP indices, cast
317 // the base to i8* and do an ugly getelementptr with that. It's still
318 // better than ptrtoint+arithmetic+inttoptr at least.
319 if (!AnyNonZeroIndices) {
320 V = InsertNoopCastOfTo(V,
321 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
322 Value *Idx = expand(SE.getAddExpr(Ops));
323 Idx = InsertNoopCastOfTo(Idx, Ty);
324
325 // Fold a GEP with constant operands.
326 if (Constant *CLHS = dyn_cast<Constant>(V))
327 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000328 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000329
330 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
331 unsigned ScanLimit = 6;
332 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
333 if (InsertPt != BlockBegin) {
334 // Scanning starts from the last instruction before InsertPt.
335 BasicBlock::iterator IP = InsertPt;
336 --IP;
337 for (; ScanLimit; --IP, --ScanLimit) {
338 if (IP->getOpcode() == Instruction::GetElementPtr &&
339 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
340 return IP;
341 if (IP == BlockBegin) break;
342 }
343 }
344
345 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
346 InsertedValues.insert(GEP);
347 return GEP;
348 }
349
350 // Insert a pretty getelementptr.
351 Value *GEP = GetElementPtrInst::Create(V,
352 GepIndices.begin(),
353 GepIndices.end(),
354 "scevgep", InsertPt);
355 Ops.push_back(SE.getUnknown(GEP));
356 InsertedValues.insert(GEP);
357 return expand(SE.getAddExpr(Ops));
358}
359
Dan Gohman890f92b2009-04-18 17:56:28 +0000360Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000361 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000362 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000363
Dan Gohman453aa4f2009-05-24 18:06:31 +0000364 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
365 // comments on expandAddToGEP for details.
Dan Gohman5be18e82009-05-19 02:15:55 +0000366 if (SE.TD)
Dan Gohman453aa4f2009-05-24 18:06:31 +0000367 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
368 const std::vector<SCEVHandle> &Ops = S->getOperands();
Dan Gohmanfb5a3412009-05-24 19:02:45 +0000369 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1],
Dan Gohman453aa4f2009-05-24 18:06:31 +0000370 PTy, Ty, V);
371 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000372
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000373 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000374
375 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000376 for (int i = S->getNumOperands()-2; i >= 0; --i) {
377 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000378 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000379 V = InsertBinop(Instruction::Add, V, W, InsertPt);
380 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000381 return V;
382}
Dan Gohman5be18e82009-05-19 02:15:55 +0000383
Dan Gohman890f92b2009-04-18 17:56:28 +0000384Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000385 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000386 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000387 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000388 if (SC->getValue()->isAllOnesValue())
389 FirstOp = 1;
390
391 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000392 Value *V = expand(S->getOperand(i+1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000393 V = InsertNoopCastOfTo(V, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000394
395 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000396 for (; i >= FirstOp; --i) {
397 Value *W = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000398 W = InsertNoopCastOfTo(W, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000399 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
400 }
401
Nate Begeman36f891b2005-07-30 00:12:19 +0000402 // -1 * ... ---> 0 - ...
403 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000404 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000405 return V;
406}
407
Dan Gohman890f92b2009-04-18 17:56:28 +0000408Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000409 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000410
Nick Lewycky6177fd42008-07-08 05:05:37 +0000411 Value *LHS = expand(S->getLHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000412 LHS = InsertNoopCastOfTo(LHS, Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000413 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000414 const APInt &RHS = SC->getValue()->getValue();
415 if (RHS.isPowerOf2())
416 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000417 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000418 InsertPt);
419 }
420
421 Value *RHS = expand(S->getRHS());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000422 RHS = InsertNoopCastOfTo(RHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000423 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
424}
425
Dan Gohman453aa4f2009-05-24 18:06:31 +0000426/// Move parts of Base into Rest to leave Base with the minimal
427/// expression that provides a pointer operand suitable for a
428/// GEP expansion.
429static void ExposePointerBase(SCEVHandle &Base, SCEVHandle &Rest,
430 ScalarEvolution &SE) {
431 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
432 Base = A->getStart();
433 Rest = SE.getAddExpr(Rest,
434 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
435 A->getStepRecurrence(SE),
436 A->getLoop()));
437 }
438 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
439 Base = A->getOperand(A->getNumOperands()-1);
440 std::vector<SCEVHandle> NewAddOps(A->op_begin(), A->op_end());
441 NewAddOps.back() = Rest;
442 Rest = SE.getAddExpr(NewAddOps);
443 ExposePointerBase(Base, Rest, SE);
444 }
445}
446
Dan Gohman890f92b2009-04-18 17:56:28 +0000447Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000448 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000449 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000450
451 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000452 if (!S->getStart()->isZero()) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000453 std::vector<SCEVHandle> NewOps(S->getOperands());
Dan Gohman246b2562007-10-22 18:31:58 +0000454 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000455 SCEVHandle Rest = SE.getAddRecExpr(NewOps, L);
456
457 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
458 // comments on expandAddToGEP for details.
459 if (SE.TD) {
460 SCEVHandle Base = S->getStart();
Dan Gohmanf1a80482009-05-27 02:07:15 +0000461 SCEVHandle RestArray[1] = { Rest };
Dan Gohman453aa4f2009-05-24 18:06:31 +0000462 // Dig into the expression to find the pointer base for a GEP.
463 ExposePointerBase(Base, RestArray[0], SE);
464 // If we found a pointer, expand the AddRec with a GEP.
465 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanf876ad02009-05-26 17:41:16 +0000466 // Make sure the Base isn't something exotic, such as a multiplied
467 // or divided pointer value. In those cases, the result type isn't
468 // actually a pointer type.
469 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
470 Value *StartV = expand(Base);
471 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
472 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
473 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000474 }
475 }
476
477 Value *RestV = expand(Rest);
478 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(RestV)));
Nate Begeman36f891b2005-07-30 00:12:19 +0000479 }
480
481 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000482 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000483 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000484 // Create and insert the PHI node for the induction variable in the
485 // specified loop.
486 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000487 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000488 InsertedValues.insert(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000489 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
490
491 pred_iterator HPI = pred_begin(Header);
492 assert(HPI != pred_end(Header) && "Loop with zero preds???");
493 if (!L->contains(*HPI)) ++HPI;
494 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
495 "No backedge in loop?");
496
497 // Insert a unit add instruction right before the terminator corresponding
498 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000499 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000500 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000501 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000502 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000503
504 pred_iterator PI = pred_begin(Header);
505 if (*PI == L->getLoopPreheader())
506 ++PI;
507 PN->addIncoming(Add, *PI);
508 return PN;
509 }
510
511 // Get the canonical induction variable I for this loop.
512 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
513
Chris Lattnerdf14a042005-10-30 06:24:33 +0000514 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000515 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000516 Value *F = expand(S->getOperand(1));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000517 F = InsertNoopCastOfTo(F, Ty);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000518
519 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000520 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000521 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000522 return I;
523
524 // If the insert point is directly inside of the loop, emit the multiply at
525 // the insert point. Otherwise, L is a loop that is a parent of the insert
526 // point loop. If we can, move the multiply to the outer most loop that it
527 // is safe to be in.
Dan Gohman6cdc7272009-04-22 16:05:50 +0000528 BasicBlock::iterator MulInsertPt = getInsertionPoint();
Dan Gohman5be18e82009-05-19 02:15:55 +0000529 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
Chris Lattnerdf14a042005-10-30 06:24:33 +0000530 if (InsertPtLoop != L && InsertPtLoop &&
531 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000532 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000533 // If we cannot hoist the multiply out of this loop, don't.
534 if (!InsertPtLoop->isLoopInvariant(F)) break;
535
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000536 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
537
538 // If this loop hasn't got a preheader, we aren't able to hoist the
539 // multiply.
540 if (!InsertPtLoopPH)
541 break;
542
543 // Otherwise, move the insert point to the preheader.
544 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000545 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000546 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000547 }
548
Chris Lattner7fec90e2007-04-13 05:04:18 +0000549 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000550 }
551
552 // If this is a chain of recurrences, turn it into a closed form, using the
553 // folders, then expandCodeFor the closed form. This allows the folders to
554 // simplify the expression without having to build a bunch of special code
555 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000556 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000557
Dan Gohman246b2562007-10-22 18:31:58 +0000558 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000559 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000560
Dan Gohmand19534a2007-06-15 14:38:12 +0000561 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000562}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000563
Dan Gohman890f92b2009-04-18 17:56:28 +0000564Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000565 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000566 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000567 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000568 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
569 InsertedValues.insert(I);
570 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000571}
572
Dan Gohman890f92b2009-04-18 17:56:28 +0000573Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000574 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000575 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000576 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000577 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
578 InsertedValues.insert(I);
579 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000580}
581
Dan Gohman890f92b2009-04-18 17:56:28 +0000582Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000583 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000584 Value *V = expand(S->getOperand());
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000585 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000586 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
587 InsertedValues.insert(I);
588 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000589}
590
Dan Gohman890f92b2009-04-18 17:56:28 +0000591Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000592 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000593 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000594 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000595 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
596 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000597 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000598 Instruction *ICmp =
599 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
600 InsertedValues.insert(ICmp);
601 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
602 InsertedValues.insert(Sel);
603 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000604 }
605 return LHS;
606}
607
Dan Gohman890f92b2009-04-18 17:56:28 +0000608Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000609 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000610 Value *LHS = expand(S->getOperand(0));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000611 LHS = InsertNoopCastOfTo(LHS, Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000612 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
613 Value *RHS = expand(S->getOperand(i));
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000614 RHS = InsertNoopCastOfTo(RHS, Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000615 Instruction *ICmp =
616 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
617 InsertedValues.insert(ICmp);
618 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
619 InsertedValues.insert(Sel);
620 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000621 }
622 return LHS;
623}
624
Dan Gohman752ec7d2009-04-23 15:16:49 +0000625Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000626 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000627 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000628 if (Ty) {
629 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
630 "non-trivial casts should be done with the SCEVs directly!");
631 V = InsertNoopCastOfTo(V, Ty);
632 }
633 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000634}
635
Dan Gohman890f92b2009-04-18 17:56:28 +0000636Value *SCEVExpander::expand(const SCEV *S) {
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000637 // Check to see if we already expanded this.
Torok Edwin3790fb02009-05-24 19:36:09 +0000638 std::map<SCEVHandle, AssertingVH<Value> >::iterator I =
639 InsertedExpressions.find(S);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000640 if (I != InsertedExpressions.end())
641 return I->second;
642
643 Value *V = visit(S);
644 InsertedExpressions[S] = V;
645 return V;
646}
Dan Gohman1d09de32009-06-05 16:35:53 +0000647
648/// getOrInsertCanonicalInductionVariable - This method returns the
649/// canonical induction variable of the specified type for the specified
650/// loop (inserting one if there is none). A canonical induction variable
651/// starts at zero and steps by one on each iteration.
652Value *
653SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
654 const Type *Ty) {
655 assert(Ty->isInteger() && "Can only insert integer induction variables!");
656 SCEVHandle H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
657 SE.getIntegerSCEV(1, Ty), L);
658 return expand(H);
659}