blob: fbb532695029b2b7d464d2b611c19ee1589aa803 [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"
Owen Anderson76f600b2009-07-06 22:37:39 +000018#include "llvm/LLVMContext.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000019#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000020#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000021using namespace llvm;
22
Dan Gohman267a3852009-06-27 21:18:18 +000023/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24/// which must be possible with a noop cast, doing what we can to share
25/// the casts.
26Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
27 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
28 assert((Op == Instruction::BitCast ||
29 Op == Instruction::PtrToInt ||
30 Op == Instruction::IntToPtr) &&
31 "InsertNoopCastOfTo cannot perform non-noop casts!");
32 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
33 "InsertNoopCastOfTo cannot change sizes!");
34
Dan Gohman2d1be872009-04-16 03:18:22 +000035 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000036 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000037 return V;
38
Dan Gohmanf04fa482009-04-16 15:52:57 +000039 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000040 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000041 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000042 if (CastInst *CI = dyn_cast<CastInst>(V))
43 if ((CI->getOpcode() == Instruction::PtrToInt ||
44 CI->getOpcode() == Instruction::IntToPtr) &&
45 SE.getTypeSizeInBits(CI->getType()) ==
46 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
47 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000048 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
49 if ((CE->getOpcode() == Instruction::PtrToInt ||
50 CE->getOpcode() == Instruction::IntToPtr) &&
51 SE.getTypeSizeInBits(CE->getType()) ==
52 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
53 return CE->getOperand(0);
54 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000055
Chris Lattnerca1a4be2006-02-04 09:51:53 +000056 // FIXME: keep track of the cast instruction.
57 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson76f600b2009-07-06 22:37:39 +000058 return getContext()->getConstantExprCast(Op, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000059
60 if (Argument *A = dyn_cast<Argument>(V)) {
61 // Check to see if there is already a cast!
62 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
Dan Gohman40a5a1b2009-06-24 01:18:18 +000063 UI != E; ++UI)
Chris Lattnerca1a4be2006-02-04 09:51:53 +000064 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000065 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000066 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000067 // If the cast isn't the first instruction of the function, move it.
Dan Gohman40a5a1b2009-06-24 01:18:18 +000068 if (BasicBlock::iterator(CI) !=
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000069 A->getParent()->getEntryBlock().begin()) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +000070 // Recreate the cast at the beginning of the entry block.
71 // The old cast is left in place in case it is being used
72 // as an insert point.
73 Instruction *NewCI =
Dan Gohman267a3852009-06-27 21:18:18 +000074 CastInst::Create(Op, V, Ty, "",
Dan Gohman40a5a1b2009-06-24 01:18:18 +000075 A->getParent()->getEntryBlock().begin());
76 NewCI->takeName(CI);
77 CI->replaceAllUsesWith(NewCI);
78 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000079 }
80 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000081 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +000082
Dan Gohman267a3852009-06-27 21:18:18 +000083 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
Dan Gohmancf5ab822009-05-01 17:13:31 +000084 A->getParent()->getEntryBlock().begin());
85 InsertedValues.insert(I);
86 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000087 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000088
Chris Lattnerca1a4be2006-02-04 09:51:53 +000089 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000090
Chris Lattnerca1a4be2006-02-04 09:51:53 +000091 // Check to see if there is already a cast. If there is, use it.
92 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
93 UI != E; ++UI) {
94 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000095 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000096 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000097 BasicBlock::iterator It = I; ++It;
98 if (isa<InvokeInst>(I))
99 It = cast<InvokeInst>(I)->getNormalDest()->begin();
100 while (isa<PHINode>(It)) ++It;
101 if (It != BasicBlock::iterator(CI)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000102 // Recreate the cast at the beginning of the entry block.
103 // The old cast is left in place in case it is being used
104 // as an insert point.
Dan Gohman267a3852009-06-27 21:18:18 +0000105 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000106 NewCI->takeName(CI);
107 CI->replaceAllUsesWith(NewCI);
108 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000109 }
110 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000112 }
113 BasicBlock::iterator IP = I; ++IP;
114 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
115 IP = II->getNormalDest()->begin();
116 while (isa<PHINode>(IP)) ++IP;
Dan Gohman267a3852009-06-27 21:18:18 +0000117 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000118 InsertedValues.insert(CI);
119 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000120}
121
Chris Lattner7fec90e2007-04-13 05:04:18 +0000122/// InsertBinop - Insert the specified binary operator, doing a small amount
123/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000124Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
125 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000126 // Fold a binop with constant operands.
127 if (Constant *CLHS = dyn_cast<Constant>(LHS))
128 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson76f600b2009-07-06 22:37:39 +0000129 return getContext()->getConstantExpr(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000130
Chris Lattner7fec90e2007-04-13 05:04:18 +0000131 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
132 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000133 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
134 // Scanning starts from the last instruction before the insertion point.
135 BasicBlock::iterator IP = Builder.GetInsertPoint();
136 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000137 --IP;
138 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000139 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
140 IP->getOperand(1) == RHS)
141 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000142 if (IP == BlockBegin) break;
143 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000144 }
Dan Gohman267a3852009-06-27 21:18:18 +0000145
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000146 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000147 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000148 InsertedValues.insert(BO);
149 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000150}
151
Dan Gohman4a4f7672009-05-27 02:00:53 +0000152/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000153/// division. If so, update S with Factor divided out and return true.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000154/// S need not be evenly divisble if a reasonable remainder can be
155/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000156/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
157/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
158/// check to see if the divide was folded.
Owen Anderson372b46c2009-06-22 21:39:50 +0000159static bool FactorOutConstant(const SCEV* &S,
160 const SCEV* &Remainder,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000161 const APInt &Factor,
162 ScalarEvolution &SE) {
163 // Everything is divisible by one.
164 if (Factor == 1)
165 return true;
166
167 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000168 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
169 ConstantInt *CI =
Owen Anderson76f600b2009-07-06 22:37:39 +0000170 SE.getContext()->getConstantInt(C->getValue()->getValue().sdiv(Factor));
Dan Gohman4a4f7672009-05-27 02:00:53 +0000171 // If the quotient is zero and the remainder is non-zero, reject
172 // the value at this scale. It will be considered for subsequent
173 // smaller scales.
174 if (C->isZero() || !CI->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000175 const SCEV* Div = SE.getConstant(CI);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000176 S = Div;
Dan Gohman4a4f7672009-05-27 02:00:53 +0000177 Remainder =
178 SE.getAddExpr(Remainder,
179 SE.getConstant(C->getValue()->getValue().srem(Factor)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000180 return true;
181 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000182 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000183
184 // In a Mul, check if there is a constant operand which is a multiple
185 // of the given factor.
186 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
187 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
188 if (!C->getValue()->getValue().srem(Factor)) {
Dan Gohman5001c212009-06-30 01:25:30 +0000189 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
190 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
191 MOperands.end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000192 NewMulOps[0] =
193 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
194 S = SE.getMulExpr(NewMulOps);
195 return true;
196 }
197
198 // In an AddRec, check if both start and step are divisible.
199 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000200 const SCEV* Step = A->getStepRecurrence(SE);
201 const SCEV* StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohman4a4f7672009-05-27 02:00:53 +0000202 if (!FactorOutConstant(Step, StepRem, Factor, SE))
203 return false;
204 if (!StepRem->isZero())
205 return false;
Owen Anderson372b46c2009-06-22 21:39:50 +0000206 const SCEV* Start = A->getStart();
Dan Gohman4a4f7672009-05-27 02:00:53 +0000207 if (!FactorOutConstant(Start, Remainder, Factor, SE))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000208 return false;
209 S = SE.getAddRecExpr(Start, Step, A->getLoop());
210 return true;
211 }
212
213 return false;
214}
215
Dan Gohman5be18e82009-05-19 02:15:55 +0000216/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000217/// instead of using ptrtoint+arithmetic+inttoptr. This helps
218/// BasicAliasAnalysis analyze the result. However, it suffers from the
219/// underlying bug described in PR2831. Addition in LLVM currently always
220/// has two's complement wrapping guaranteed. However, the semantics for
221/// getelementptr overflow are ambiguous. In the common case though, this
222/// expansion gets used when a GEP in the original code has been converted
223/// into integer arithmetic, in which case the resulting code will be no
224/// more undefined than it was originally.
225///
226/// Design note: It might seem desirable for this function to be more
227/// loop-aware. If some of the indices are loop-invariant while others
228/// aren't, it might seem desirable to emit multiple GEPs, keeping the
229/// loop-invariant portions of the overall computation outside the loop.
230/// However, there are a few reasons this is not done here. Hoisting simple
231/// arithmetic is a low-level optimization that often isn't very
232/// important until late in the optimization process. In fact, passes
233/// like InstructionCombining will combine GEPs, even if it means
234/// pushing loop-invariant computation down into loops, so even if the
235/// GEPs were split here, the work would quickly be undone. The
236/// LoopStrengthReduction pass, which is usually run quite late (and
237/// after the last InstructionCombining pass), takes care of hoisting
238/// loop-invariant portions of expressions, after considering what
239/// can be folded using target addressing modes.
240///
Owen Anderson372b46c2009-06-22 21:39:50 +0000241Value *SCEVExpander::expandAddToGEP(const SCEV* const *op_begin,
242 const SCEV* const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000243 const PointerType *PTy,
244 const Type *Ty,
245 Value *V) {
246 const Type *ElTy = PTy->getElementType();
247 SmallVector<Value *, 4> GepIndices;
Owen Anderson372b46c2009-06-22 21:39:50 +0000248 SmallVector<const SCEV*, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000249 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000250
251 // Decend down the pointer's type and attempt to convert the other
252 // operands into GEP indices, at each level. The first index in a GEP
253 // indexes into the array implied by the pointer operand; the rest of
254 // the indices index into the element or field type selected by the
255 // preceding index.
256 for (;;) {
257 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
258 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
Owen Anderson372b46c2009-06-22 21:39:50 +0000259 SmallVector<const SCEV*, 8> NewOps;
260 SmallVector<const SCEV*, 8> ScaledOps;
Dan Gohman5be18e82009-05-19 02:15:55 +0000261 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000262 // Split AddRecs up into parts as either of the parts may be usable
263 // without the other.
264 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
265 if (!A->getStart()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000266 const SCEV* Start = A->getStart();
Dan Gohman453aa4f2009-05-24 18:06:31 +0000267 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
268 A->getStepRecurrence(SE),
269 A->getLoop()));
270 Ops[i] = Start;
271 ++e;
272 }
273 // If the scale size is not 0, attempt to factor out a scale.
Dan Gohman5be18e82009-05-19 02:15:55 +0000274 if (ElSize != 0) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000275 const SCEV* Op = Ops[i];
276 const SCEV* Remainder = SE.getIntegerSCEV(0, Op->getType());
Dan Gohman4a4f7672009-05-27 02:00:53 +0000277 if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000278 ScaledOps.push_back(Op); // Op now has ElSize factored out.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000279 NewOps.push_back(Remainder);
Dan Gohman5be18e82009-05-19 02:15:55 +0000280 continue;
281 }
282 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000283 // If the operand was not divisible, add it to the list of operands
284 // we'll scan next iteration.
Dan Gohman5be18e82009-05-19 02:15:55 +0000285 NewOps.push_back(Ops[i]);
286 }
287 Ops = NewOps;
288 AnyNonZeroIndices |= !ScaledOps.empty();
289 Value *Scaled = ScaledOps.empty() ?
Owen Anderson76f600b2009-07-06 22:37:39 +0000290 getContext()->getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000291 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
292 GepIndices.push_back(Scaled);
293
294 // Collect struct field index operands.
295 if (!Ops.empty())
296 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
297 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
298 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
299 const StructLayout &SL = *SE.TD->getStructLayout(STy);
300 uint64_t FullOffset = C->getValue()->getZExtValue();
301 if (FullOffset < SL.getSizeInBytes()) {
302 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson76f600b2009-07-06 22:37:39 +0000303 GepIndices.push_back(
304 getContext()->getConstantInt(Type::Int32Ty, ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000305 ElTy = STy->getTypeAtIndex(ElIdx);
306 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000307 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000308 AnyNonZeroIndices = true;
309 continue;
310 }
311 }
312 break;
313 }
314
315 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
316 ElTy = ATy->getElementType();
317 continue;
318 }
319 break;
320 }
321
322 // If none of the operands were convertable to proper GEP indices, cast
323 // the base to i8* and do an ugly getelementptr with that. It's still
324 // better than ptrtoint+arithmetic+inttoptr at least.
325 if (!AnyNonZeroIndices) {
326 V = InsertNoopCastOfTo(V,
327 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
Dan Gohman92fcdca2009-06-09 17:18:38 +0000328 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000329
330 // Fold a GEP with constant operands.
331 if (Constant *CLHS = dyn_cast<Constant>(V))
332 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Anderson76f600b2009-07-06 22:37:39 +0000333 return getContext()->getConstantExprGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000334
335 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
336 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000337 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
338 // Scanning starts from the last instruction before the insertion point.
339 BasicBlock::iterator IP = Builder.GetInsertPoint();
340 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000341 --IP;
342 for (; ScanLimit; --IP, --ScanLimit) {
343 if (IP->getOpcode() == Instruction::GetElementPtr &&
344 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
345 return IP;
346 if (IP == BlockBegin) break;
347 }
348 }
349
Dan Gohman267a3852009-06-27 21:18:18 +0000350 Value *GEP = Builder.CreateGEP(V, Idx, "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000351 InsertedValues.insert(GEP);
352 return GEP;
353 }
354
355 // Insert a pretty getelementptr.
Dan Gohman267a3852009-06-27 21:18:18 +0000356 Value *GEP = Builder.CreateGEP(V,
357 GepIndices.begin(),
358 GepIndices.end(),
359 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000360 Ops.push_back(SE.getUnknown(GEP));
361 InsertedValues.insert(GEP);
362 return expand(SE.getAddExpr(Ops));
363}
364
Dan Gohman890f92b2009-04-18 17:56:28 +0000365Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000366 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000367 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000368
Dan Gohman453aa4f2009-05-24 18:06:31 +0000369 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
370 // comments on expandAddToGEP for details.
Dan Gohman5be18e82009-05-19 02:15:55 +0000371 if (SE.TD)
Dan Gohman453aa4f2009-05-24 18:06:31 +0000372 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000373 const SmallVectorImpl<const SCEV*> &Ops = S->getOperands();
Dan Gohman5001c212009-06-30 01:25:30 +0000374 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000375 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000376
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000377 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000378
379 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000380 for (int i = S->getNumOperands()-2; i >= 0; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000381 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000382 V = InsertBinop(Instruction::Add, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000383 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000384 return V;
385}
Dan Gohman5be18e82009-05-19 02:15:55 +0000386
Dan Gohman890f92b2009-04-18 17:56:28 +0000387Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000388 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000389 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000391 if (SC->getValue()->isAllOnesValue())
392 FirstOp = 1;
393
394 int i = S->getNumOperands()-2;
Dan Gohman92fcdca2009-06-09 17:18:38 +0000395 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000396
397 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000398 for (; i >= FirstOp; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000399 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000400 V = InsertBinop(Instruction::Mul, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000401 }
402
Nate Begeman36f891b2005-07-30 00:12:19 +0000403 // -1 * ... ---> 0 - ...
404 if (FirstOp == 1)
Owen Anderson76f600b2009-07-06 22:37:39 +0000405 V = InsertBinop(Instruction::Sub, getContext()->getNullValue(Ty), V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000406 return V;
407}
408
Dan Gohman890f92b2009-04-18 17:56:28 +0000409Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000410 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000411
Dan Gohman92fcdca2009-06-09 17:18:38 +0000412 Value *LHS = expandCodeFor(S->getLHS(), 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,
Owen Anderson76f600b2009-07-06 22:37:39 +0000417 getContext()->getConstantInt(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000418 }
419
Dan Gohman92fcdca2009-06-09 17:18:38 +0000420 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000421 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000422}
423
Dan Gohman453aa4f2009-05-24 18:06:31 +0000424/// Move parts of Base into Rest to leave Base with the minimal
425/// expression that provides a pointer operand suitable for a
426/// GEP expansion.
Owen Anderson372b46c2009-06-22 21:39:50 +0000427static void ExposePointerBase(const SCEV* &Base, const SCEV* &Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000428 ScalarEvolution &SE) {
429 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
430 Base = A->getStart();
431 Rest = SE.getAddExpr(Rest,
432 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
433 A->getStepRecurrence(SE),
434 A->getLoop()));
435 }
436 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
437 Base = A->getOperand(A->getNumOperands()-1);
Owen Anderson372b46c2009-06-22 21:39:50 +0000438 SmallVector<const SCEV*, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000439 NewAddOps.back() = Rest;
440 Rest = SE.getAddExpr(NewAddOps);
441 ExposePointerBase(Base, Rest, SE);
442 }
443}
444
Dan Gohman890f92b2009-04-18 17:56:28 +0000445Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000446 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000447 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000448
Dan Gohman4d8414f2009-06-13 16:25:49 +0000449 // First check for an existing canonical IV in a suitable type.
450 PHINode *CanonicalIV = 0;
451 if (PHINode *PN = L->getCanonicalInductionVariable())
452 if (SE.isSCEVable(PN->getType()) &&
453 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
454 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
455 CanonicalIV = PN;
456
457 // Rewrite an AddRec in terms of the canonical induction variable, if
458 // its type is more narrow.
459 if (CanonicalIV &&
460 SE.getTypeSizeInBits(CanonicalIV->getType()) >
461 SE.getTypeSizeInBits(Ty)) {
Dan Gohman5001c212009-06-30 01:25:30 +0000462 const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
463 CanonicalIV->getType());
464 const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
Dan Gohman4d8414f2009-06-13 16:25:49 +0000465 CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000466 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +0000467 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
468 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000469 BasicBlock::iterator NewInsertPt =
470 next(BasicBlock::iterator(cast<Instruction>(V)));
471 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
472 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
473 NewInsertPt);
Dan Gohman267a3852009-06-27 21:18:18 +0000474 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000475 return V;
476 }
477
Nate Begeman36f891b2005-07-30 00:12:19 +0000478 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000479 if (!S->getStart()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000480 const SmallVectorImpl<const SCEV*> &SOperands = S->getOperands();
481 SmallVector<const SCEV*, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +0000482 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +0000483 const SCEV* Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000484
485 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
486 // comments on expandAddToGEP for details.
487 if (SE.TD) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000488 const SCEV* Base = S->getStart();
489 const SCEV* RestArray[1] = { Rest };
Dan Gohman453aa4f2009-05-24 18:06:31 +0000490 // Dig into the expression to find the pointer base for a GEP.
491 ExposePointerBase(Base, RestArray[0], SE);
492 // If we found a pointer, expand the AddRec with a GEP.
493 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanf876ad02009-05-26 17:41:16 +0000494 // Make sure the Base isn't something exotic, such as a multiplied
495 // or divided pointer value. In those cases, the result type isn't
496 // actually a pointer type.
497 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
498 Value *StartV = expand(Base);
499 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
500 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
501 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000502 }
503 }
504
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000505 // Just do a normal add. Pre-expand the operands to suppress folding.
506 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
507 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +0000508 }
509
510 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000511 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000512 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000513 // If there's a canonical IV, just use it.
514 if (CanonicalIV) {
515 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
516 "IVs with types different from the canonical IV should "
517 "already have been handled!");
518 return CanonicalIV;
519 }
520
Nate Begeman36f891b2005-07-30 00:12:19 +0000521 // Create and insert the PHI node for the induction variable in the
522 // specified loop.
523 BasicBlock *Header = L->getHeader();
Dan Gohman267a3852009-06-27 21:18:18 +0000524 BasicBlock *Preheader = L->getLoopPreheader();
Gabor Greif051a9502008-04-06 20:25:17 +0000525 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000526 InsertedValues.insert(PN);
Owen Anderson76f600b2009-07-06 22:37:39 +0000527 PN->addIncoming(getContext()->getNullValue(Ty), Preheader);
Nate Begeman36f891b2005-07-30 00:12:19 +0000528
529 pred_iterator HPI = pred_begin(Header);
530 assert(HPI != pred_end(Header) && "Loop with zero preds???");
531 if (!L->contains(*HPI)) ++HPI;
532 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
533 "No backedge in loop?");
534
535 // Insert a unit add instruction right before the terminator corresponding
536 // to the back-edge.
Owen Anderson76f600b2009-07-06 22:37:39 +0000537 Constant *One = getContext()->getConstantInt(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000538 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000539 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000540 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000541
542 pred_iterator PI = pred_begin(Header);
Dan Gohman267a3852009-06-27 21:18:18 +0000543 if (*PI == Preheader)
Nate Begeman36f891b2005-07-30 00:12:19 +0000544 ++PI;
545 PN->addIncoming(Add, *PI);
546 return PN;
547 }
548
Dan Gohman4d8414f2009-06-13 16:25:49 +0000549 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +0000550 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +0000551 Value *I = CanonicalIV ?
552 CanonicalIV :
553 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000554
Chris Lattnerdf14a042005-10-30 06:24:33 +0000555 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000556 if (S->isAffine()) // {0,+,F} --> i*F
557 return
558 expand(SE.getTruncateOrNoop(
559 SE.getMulExpr(SE.getUnknown(I),
560 SE.getNoopOrAnyExtend(S->getOperand(1),
561 I->getType())),
562 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +0000563
564 // If this is a chain of recurrences, turn it into a closed form, using the
565 // folders, then expandCodeFor the closed form. This allows the folders to
566 // simplify the expression without having to build a bunch of special code
567 // into this folder.
Owen Anderson372b46c2009-06-22 21:39:50 +0000568 const SCEV* IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000569
Dan Gohman4d8414f2009-06-13 16:25:49 +0000570 // Promote S up to the canonical IV type, if the cast is foldable.
Owen Anderson372b46c2009-06-22 21:39:50 +0000571 const SCEV* NewS = S;
572 const SCEV* Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000573 if (isa<SCEVAddRecExpr>(Ext))
574 NewS = Ext;
575
Owen Anderson372b46c2009-06-22 21:39:50 +0000576 const SCEV* V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000577 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000578
Dan Gohman4d8414f2009-06-13 16:25:49 +0000579 // Truncate the result down to the original type, if needed.
Owen Anderson372b46c2009-06-22 21:39:50 +0000580 const SCEV* T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +0000581 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +0000582}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000583
Dan Gohman890f92b2009-04-18 17:56:28 +0000584Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000585 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000586 Value *V = expandCodeFor(S->getOperand(),
587 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000588 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000589 InsertedValues.insert(I);
590 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000591}
592
Dan Gohman890f92b2009-04-18 17:56:28 +0000593Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000594 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000595 Value *V = expandCodeFor(S->getOperand(),
596 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000597 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000598 InsertedValues.insert(I);
599 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000600}
601
Dan Gohman890f92b2009-04-18 17:56:28 +0000602Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000603 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000604 Value *V = expandCodeFor(S->getOperand(),
605 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000606 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000607 InsertedValues.insert(I);
608 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000609}
610
Dan Gohman890f92b2009-04-18 17:56:28 +0000611Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000612 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000613 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000614 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000615 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000616 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000617 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000618 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000619 InsertedValues.insert(Sel);
620 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000621 }
622 return LHS;
623}
624
Dan Gohman890f92b2009-04-18 17:56:28 +0000625Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000626 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000627 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000628 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000629 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000630 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000631 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000632 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000633 InsertedValues.insert(Sel);
634 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000635 }
636 return LHS;
637}
638
Owen Anderson372b46c2009-06-22 21:39:50 +0000639Value *SCEVExpander::expandCodeFor(const SCEV* SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000640 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000641 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000642 if (Ty) {
643 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
644 "non-trivial casts should be done with the SCEVs directly!");
645 V = InsertNoopCastOfTo(V, Ty);
646 }
647 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000648}
649
Dan Gohman890f92b2009-04-18 17:56:28 +0000650Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000651 // Compute an insertion point for this SCEV object. Hoist the instructions
652 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +0000653 Instruction *InsertPt = Builder.GetInsertPoint();
654 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000655 L = L->getParentLoop())
656 if (S->isLoopInvariant(L)) {
657 if (!L) break;
658 if (BasicBlock *Preheader = L->getLoopPreheader())
659 InsertPt = Preheader->getTerminator();
660 } else {
661 // If the SCEV is computable at this level, insert it into the header
662 // after the PHIs (and after any other instructions that we've inserted
663 // there) so that it is guaranteed to dominate any user inside the loop.
664 if (L && S->hasComputableLoopEvolution(L))
665 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman267a3852009-06-27 21:18:18 +0000666 while (isInsertedInstruction(InsertPt))
667 InsertPt = next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000668 break;
669 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000670
Dan Gohman667d7872009-06-26 22:53:46 +0000671 // Check to see if we already expanded this here.
672 std::map<std::pair<const SCEV *, Instruction *>,
673 AssertingVH<Value> >::iterator I =
674 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +0000675 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +0000676 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +0000677
678 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
679 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
680 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +0000681
682 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000683 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000684
Dan Gohman667d7872009-06-26 22:53:46 +0000685 // Remember the expanded value for this SCEV at this location.
686 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
687
Dan Gohman267a3852009-06-27 21:18:18 +0000688 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000689 return V;
690}
Dan Gohman1d09de32009-06-05 16:35:53 +0000691
692/// getOrInsertCanonicalInductionVariable - This method returns the
693/// canonical induction variable of the specified type for the specified
694/// loop (inserting one if there is none). A canonical induction variable
695/// starts at zero and steps by one on each iteration.
696Value *
697SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
698 const Type *Ty) {
699 assert(Ty->isInteger() && "Can only insert integer induction variables!");
Owen Anderson372b46c2009-06-22 21:39:50 +0000700 const SCEV* H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000701 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +0000702 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
703 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000704 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +0000705 if (SaveInsertBB)
706 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000707 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +0000708}