blob: 999fd55c86d3ca538efe071cec55d0e7b0194c52 [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 Andersonbaf3c402009-07-29 18:55:55 +000058 return ConstantExpr::getCast(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 Andersonbaf3c402009-07-29 18:55:55 +0000129 return ConstantExpr::get(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.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000159static bool FactorOutConstant(const SCEV *&S,
160 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000161 const SCEV *Factor,
162 ScalarEvolution &SE,
163 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000164 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000165 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000166 return true;
167
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000168 // x/x == 1.
169 if (S == Factor) {
170 S = SE.getIntegerSCEV(1, S->getType());
171 return true;
172 }
173
Dan Gohman453aa4f2009-05-24 18:06:31 +0000174 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000175 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000176 // 0/x == 0.
177 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000178 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000179 // Check for divisibility.
180 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
181 ConstantInt *CI =
182 ConstantInt::get(SE.getContext(),
183 C->getValue()->getValue().sdiv(
184 FC->getValue()->getValue()));
185 // If the quotient is zero and the remainder is non-zero, reject
186 // the value at this scale. It will be considered for subsequent
187 // smaller scales.
188 if (!CI->isZero()) {
189 const SCEV *Div = SE.getConstant(CI);
190 S = Div;
191 Remainder =
192 SE.getAddExpr(Remainder,
193 SE.getConstant(C->getValue()->getValue().srem(
194 FC->getValue()->getValue())));
195 return true;
196 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000197 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000198 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000199
200 // In a Mul, check if there is a constant operand which is a multiple
201 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000202 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
203 if (TD) {
204 // With TargetData, the size is known. Check if there is a constant
205 // operand which is a multiple of the given factor. If so, we can
206 // factor it.
207 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
208 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
209 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
210 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
211 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
212 MOperands.end());
213 NewMulOps[0] =
214 SE.getConstant(C->getValue()->getValue().sdiv(
215 FC->getValue()->getValue()));
216 S = SE.getMulExpr(NewMulOps);
217 return true;
218 }
219 } else {
220 // Without TargetData, check if Factor can be factored out of any of the
221 // Mul's operands. If so, we can just remove it.
222 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
223 const SCEV *SOp = M->getOperand(i);
224 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
225 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
226 Remainder->isZero()) {
227 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
228 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
229 MOperands.end());
230 NewMulOps[i] = SOp;
231 S = SE.getMulExpr(NewMulOps);
232 return true;
233 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000234 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000235 }
236 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000237
238 // In an AddRec, check if both start and step are divisible.
239 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000240 const SCEV *Step = A->getStepRecurrence(SE);
241 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000242 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000243 return false;
244 if (!StepRem->isZero())
245 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000246 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000247 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000248 return false;
249 S = SE.getAddRecExpr(Start, Step, A->getLoop());
250 return true;
251 }
252
253 return false;
254}
255
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000256/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
257/// is the number of SCEVAddRecExprs present, which are kept at the end of
258/// the list.
259///
260static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
261 const Type *Ty,
262 ScalarEvolution &SE) {
263 unsigned NumAddRecs = 0;
264 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
265 ++NumAddRecs;
266 // Group Ops into non-addrecs and addrecs.
267 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
268 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
269 // Let ScalarEvolution sort and simplify the non-addrecs list.
270 const SCEV *Sum = NoAddRecs.empty() ?
271 SE.getIntegerSCEV(0, Ty) :
272 SE.getAddExpr(NoAddRecs);
273 // If it returned an add, use the operands. Otherwise it simplified
274 // the sum into a single value, so just use that.
275 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
276 Ops = Add->getOperands();
277 else {
278 Ops.clear();
279 if (!Sum->isZero())
280 Ops.push_back(Sum);
281 }
282 // Then append the addrecs.
283 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
284}
285
286/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
287/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
288/// This helps expose more opportunities for folding parts of the expressions
289/// into GEP indices.
290///
291static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
292 const Type *Ty,
293 ScalarEvolution &SE) {
294 // Find the addrecs.
295 SmallVector<const SCEV *, 8> AddRecs;
296 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
297 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
298 const SCEV *Start = A->getStart();
299 if (Start->isZero()) break;
300 const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
301 AddRecs.push_back(SE.getAddRecExpr(Zero,
302 A->getStepRecurrence(SE),
303 A->getLoop()));
304 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
305 Ops[i] = Zero;
306 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
307 e += Add->getNumOperands();
308 } else {
309 Ops[i] = Start;
310 }
311 }
312 if (!AddRecs.empty()) {
313 // Add the addrecs onto the end of the list.
314 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
315 // Resort the operand list, moving any constants to the front.
316 SimplifyAddOperands(Ops, Ty, SE);
317 }
318}
319
Dan Gohman5be18e82009-05-19 02:15:55 +0000320/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000321/// instead of using ptrtoint+arithmetic+inttoptr. This helps
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000322/// BasicAliasAnalysis and other passes analyze the result.
Dan Gohman13c5e352009-07-20 17:44:17 +0000323///
324/// Design note: This depends on ScalarEvolution not recognizing inttoptr
325/// and ptrtoint operators, as they may introduce pointer arithmetic
326/// which may not be safely converted into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000327///
328/// Design note: It might seem desirable for this function to be more
329/// loop-aware. If some of the indices are loop-invariant while others
330/// aren't, it might seem desirable to emit multiple GEPs, keeping the
331/// loop-invariant portions of the overall computation outside the loop.
332/// However, there are a few reasons this is not done here. Hoisting simple
333/// arithmetic is a low-level optimization that often isn't very
334/// important until late in the optimization process. In fact, passes
335/// like InstructionCombining will combine GEPs, even if it means
336/// pushing loop-invariant computation down into loops, so even if the
337/// GEPs were split here, the work would quickly be undone. The
338/// LoopStrengthReduction pass, which is usually run quite late (and
339/// after the last InstructionCombining pass), takes care of hoisting
340/// loop-invariant portions of expressions, after considering what
341/// can be folded using target addressing modes.
342///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000343Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
344 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000345 const PointerType *PTy,
346 const Type *Ty,
347 Value *V) {
348 const Type *ElTy = PTy->getElementType();
349 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000350 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000351 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000352
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000353 // Split AddRecs up into parts as either of the parts may be usable
354 // without the other.
355 SplitAddRecs(Ops, Ty, SE);
356
Dan Gohman5be18e82009-05-19 02:15:55 +0000357 // Decend down the pointer's type and attempt to convert the other
358 // operands into GEP indices, at each level. The first index in a GEP
359 // indexes into the array implied by the pointer operand; the rest of
360 // the indices index into the element or field type selected by the
361 // preceding index.
362 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000363 const SCEV *ElSize = SE.getAllocSizeExpr(ElTy);
364 // If the scale size is not 0, attempt to factor out a scale for
365 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000366 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000367 if (ElTy->isSized() && !ElSize->isZero()) {
368 SmallVector<const SCEV *, 8> NewOps;
369 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000370 const SCEV *Op = Ops[i];
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000371 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
372 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
373 // Op now has ElSize factored out.
374 ScaledOps.push_back(Op);
375 if (!Remainder->isZero())
376 NewOps.push_back(Remainder);
377 AnyNonZeroIndices = true;
378 } else {
379 // The operand was not divisible, so add it to the list of operands
380 // we'll scan next iteration.
381 NewOps.push_back(Ops[i]);
Dan Gohman5be18e82009-05-19 02:15:55 +0000382 }
383 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000384 // If we made any changes, update Ops.
385 if (!ScaledOps.empty()) {
386 Ops = NewOps;
387 SimplifyAddOperands(Ops, Ty, SE);
388 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000389 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000390
391 // Record the scaled array index for this level of the type. If
392 // we didn't find any operands that could be factored, tentatively
393 // assume that element zero was selected (since the zero offset
394 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000395 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000396 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000397 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
398 GepIndices.push_back(Scaled);
399
400 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000401 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
402 bool FoundFieldNo = false;
403 // An empty struct has no fields.
404 if (STy->getNumElements() == 0) break;
405 if (SE.TD) {
406 // With TargetData, field offsets are known. See if a constant offset
407 // falls within any of the struct fields.
408 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000409 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
410 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
411 const StructLayout &SL = *SE.TD->getStructLayout(STy);
412 uint64_t FullOffset = C->getValue()->getZExtValue();
413 if (FullOffset < SL.getSizeInBytes()) {
414 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000415 GepIndices.push_back(
416 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000417 ElTy = STy->getTypeAtIndex(ElIdx);
418 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000419 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000421 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000422 }
423 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000424 } else {
425 // Without TargetData, just check for a SCEVFieldOffsetExpr of the
426 // appropriate struct type.
427 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
428 if (const SCEVFieldOffsetExpr *FO =
429 dyn_cast<SCEVFieldOffsetExpr>(Ops[i]))
430 if (FO->getStructType() == STy) {
431 unsigned FieldNo = FO->getFieldNo();
432 GepIndices.push_back(
433 ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
434 FieldNo));
435 ElTy = STy->getTypeAtIndex(FieldNo);
436 Ops[i] = SE.getConstant(Ty, 0);
437 AnyNonZeroIndices = true;
438 FoundFieldNo = true;
439 break;
440 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000441 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000442 // If no struct field offsets were found, tentatively assume that
443 // field zero was selected (since the zero offset would obviously
444 // be folded away).
445 if (!FoundFieldNo) {
446 ElTy = STy->getTypeAtIndex(0u);
447 GepIndices.push_back(
448 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
449 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000450 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000451
452 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
453 ElTy = ATy->getElementType();
454 else
455 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000456 }
457
458 // If none of the operands were convertable to proper GEP indices, cast
459 // the base to i8* and do an ugly getelementptr with that. It's still
460 // better than ptrtoint+arithmetic+inttoptr at least.
461 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000462 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000463 V = InsertNoopCastOfTo(V,
Owen Anderson1d0be152009-08-13 21:58:54 +0000464 Type::getInt8Ty(Ty->getContext())->getPointerTo(PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000465
466 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000467 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000468
469 // Fold a GEP with constant operands.
470 if (Constant *CLHS = dyn_cast<Constant>(V))
471 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000472 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000473
474 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
475 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000476 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
477 // Scanning starts from the last instruction before the insertion point.
478 BasicBlock::iterator IP = Builder.GetInsertPoint();
479 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000480 --IP;
481 for (; ScanLimit; --IP, --ScanLimit) {
482 if (IP->getOpcode() == Instruction::GetElementPtr &&
483 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
484 return IP;
485 if (IP == BlockBegin) break;
486 }
487 }
488
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000489 // Emit a GEP.
490 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000491 InsertedValues.insert(GEP);
492 return GEP;
493 }
494
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000495 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
496 // because ScalarEvolution may have changed the address arithmetic to
497 // compute a value which is beyond the end of the allocated object.
Dan Gohman267a3852009-06-27 21:18:18 +0000498 Value *GEP = Builder.CreateGEP(V,
499 GepIndices.begin(),
500 GepIndices.end(),
501 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000502 Ops.push_back(SE.getUnknown(GEP));
503 InsertedValues.insert(GEP);
504 return expand(SE.getAddExpr(Ops));
505}
506
Dan Gohman890f92b2009-04-18 17:56:28 +0000507Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000508 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000509 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000510
Dan Gohman453aa4f2009-05-24 18:06:31 +0000511 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
512 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000513 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
514 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
515 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
516 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000517
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000518 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000519
520 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000521 for (int i = S->getNumOperands()-2; i >= 0; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000522 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000523 V = InsertBinop(Instruction::Add, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000524 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000525 return V;
526}
Dan Gohman5be18e82009-05-19 02:15:55 +0000527
Dan Gohman890f92b2009-04-18 17:56:28 +0000528Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000529 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000530 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000531 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000532 if (SC->getValue()->isAllOnesValue())
533 FirstOp = 1;
534
535 int i = S->getNumOperands()-2;
Dan Gohman92fcdca2009-06-09 17:18:38 +0000536 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000537
538 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000539 for (; i >= FirstOp; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000540 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000541 V = InsertBinop(Instruction::Mul, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000542 }
543
Nate Begeman36f891b2005-07-30 00:12:19 +0000544 // -1 * ... ---> 0 - ...
545 if (FirstOp == 1)
Owen Andersona7235ea2009-07-31 20:28:14 +0000546 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000547 return V;
548}
549
Dan Gohman890f92b2009-04-18 17:56:28 +0000550Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000551 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000552
Dan Gohman92fcdca2009-06-09 17:18:38 +0000553 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000554 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000555 const APInt &RHS = SC->getValue()->getValue();
556 if (RHS.isPowerOf2())
557 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000558 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000559 }
560
Dan Gohman92fcdca2009-06-09 17:18:38 +0000561 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000562 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000563}
564
Dan Gohman453aa4f2009-05-24 18:06:31 +0000565/// Move parts of Base into Rest to leave Base with the minimal
566/// expression that provides a pointer operand suitable for a
567/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000568static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000569 ScalarEvolution &SE) {
570 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
571 Base = A->getStart();
572 Rest = SE.getAddExpr(Rest,
573 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
574 A->getStepRecurrence(SE),
575 A->getLoop()));
576 }
577 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
578 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000579 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000580 NewAddOps.back() = Rest;
581 Rest = SE.getAddExpr(NewAddOps);
582 ExposePointerBase(Base, Rest, SE);
583 }
584}
585
Dan Gohman890f92b2009-04-18 17:56:28 +0000586Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000587 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000588 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000589
Dan Gohman4d8414f2009-06-13 16:25:49 +0000590 // First check for an existing canonical IV in a suitable type.
591 PHINode *CanonicalIV = 0;
592 if (PHINode *PN = L->getCanonicalInductionVariable())
593 if (SE.isSCEVable(PN->getType()) &&
594 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
595 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
596 CanonicalIV = PN;
597
598 // Rewrite an AddRec in terms of the canonical induction variable, if
599 // its type is more narrow.
600 if (CanonicalIV &&
601 SE.getTypeSizeInBits(CanonicalIV->getType()) >
602 SE.getTypeSizeInBits(Ty)) {
Dan Gohman5001c212009-06-30 01:25:30 +0000603 const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
604 CanonicalIV->getType());
605 const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
Dan Gohman4d8414f2009-06-13 16:25:49 +0000606 CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000607 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +0000608 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
609 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000610 BasicBlock::iterator NewInsertPt =
611 next(BasicBlock::iterator(cast<Instruction>(V)));
612 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
613 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
614 NewInsertPt);
Dan Gohman267a3852009-06-27 21:18:18 +0000615 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000616 return V;
617 }
618
Nate Begeman36f891b2005-07-30 00:12:19 +0000619 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000620 if (!S->getStart()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000621 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
622 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +0000623 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000624 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000625
626 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
627 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000628 const SCEV *Base = S->getStart();
629 const SCEV *RestArray[1] = { Rest };
630 // Dig into the expression to find the pointer base for a GEP.
631 ExposePointerBase(Base, RestArray[0], SE);
632 // If we found a pointer, expand the AddRec with a GEP.
633 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
634 // Make sure the Base isn't something exotic, such as a multiplied
635 // or divided pointer value. In those cases, the result type isn't
636 // actually a pointer type.
637 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
638 Value *StartV = expand(Base);
639 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
640 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000641 }
642 }
643
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000644 // Just do a normal add. Pre-expand the operands to suppress folding.
645 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
646 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +0000647 }
648
649 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000650 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000651 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000652 // If there's a canonical IV, just use it.
653 if (CanonicalIV) {
654 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
655 "IVs with types different from the canonical IV should "
656 "already have been handled!");
657 return CanonicalIV;
658 }
659
Nate Begeman36f891b2005-07-30 00:12:19 +0000660 // Create and insert the PHI node for the induction variable in the
661 // specified loop.
662 BasicBlock *Header = L->getHeader();
Dan Gohman267a3852009-06-27 21:18:18 +0000663 BasicBlock *Preheader = L->getLoopPreheader();
Gabor Greif051a9502008-04-06 20:25:17 +0000664 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000665 InsertedValues.insert(PN);
Owen Andersona7235ea2009-07-31 20:28:14 +0000666 PN->addIncoming(Constant::getNullValue(Ty), Preheader);
Nate Begeman36f891b2005-07-30 00:12:19 +0000667
668 pred_iterator HPI = pred_begin(Header);
669 assert(HPI != pred_end(Header) && "Loop with zero preds???");
670 if (!L->contains(*HPI)) ++HPI;
671 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
672 "No backedge in loop?");
673
674 // Insert a unit add instruction right before the terminator corresponding
675 // to the back-edge.
Owen Andersoneed707b2009-07-24 23:12:02 +0000676 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000677 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000678 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000679 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000680
681 pred_iterator PI = pred_begin(Header);
Dan Gohman267a3852009-06-27 21:18:18 +0000682 if (*PI == Preheader)
Nate Begeman36f891b2005-07-30 00:12:19 +0000683 ++PI;
684 PN->addIncoming(Add, *PI);
685 return PN;
686 }
687
Dan Gohman4d8414f2009-06-13 16:25:49 +0000688 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +0000689 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +0000690 Value *I = CanonicalIV ?
691 CanonicalIV :
692 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000693
Chris Lattnerdf14a042005-10-30 06:24:33 +0000694 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000695 if (S->isAffine()) // {0,+,F} --> i*F
696 return
697 expand(SE.getTruncateOrNoop(
698 SE.getMulExpr(SE.getUnknown(I),
699 SE.getNoopOrAnyExtend(S->getOperand(1),
700 I->getType())),
701 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +0000702
703 // If this is a chain of recurrences, turn it into a closed form, using the
704 // folders, then expandCodeFor the closed form. This allows the folders to
705 // simplify the expression without having to build a bunch of special code
706 // into this folder.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000707 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000708
Dan Gohman4d8414f2009-06-13 16:25:49 +0000709 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000710 const SCEV *NewS = S;
711 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000712 if (isa<SCEVAddRecExpr>(Ext))
713 NewS = Ext;
714
Dan Gohman0bba49c2009-07-07 17:06:11 +0000715 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000716 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000717
Dan Gohman4d8414f2009-06-13 16:25:49 +0000718 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000719 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +0000720 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +0000721}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000722
Dan Gohman890f92b2009-04-18 17:56:28 +0000723Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000724 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000725 Value *V = expandCodeFor(S->getOperand(),
726 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000727 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000728 InsertedValues.insert(I);
729 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000730}
731
Dan Gohman890f92b2009-04-18 17:56:28 +0000732Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000733 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000734 Value *V = expandCodeFor(S->getOperand(),
735 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000736 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000737 InsertedValues.insert(I);
738 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000739}
740
Dan Gohman890f92b2009-04-18 17:56:28 +0000741Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000742 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000743 Value *V = expandCodeFor(S->getOperand(),
744 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000745 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000746 InsertedValues.insert(I);
747 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000748}
749
Dan Gohman890f92b2009-04-18 17:56:28 +0000750Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +0000751 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
752 const Type *Ty = LHS->getType();
753 for (int i = S->getNumOperands()-2; i >= 0; --i) {
754 // In the case of mixed integer and pointer types, do the
755 // rest of the comparisons as integer.
756 if (S->getOperand(i)->getType() != Ty) {
757 Ty = SE.getEffectiveSCEVType(Ty);
758 LHS = InsertNoopCastOfTo(LHS, Ty);
759 }
Dan Gohman92fcdca2009-06-09 17:18:38 +0000760 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000761 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000762 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000763 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000764 InsertedValues.insert(Sel);
765 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000766 }
Dan Gohman0196dc52009-07-14 20:57:04 +0000767 // In the case of mixed integer and pointer types, cast the
768 // final result back to the pointer type.
769 if (LHS->getType() != S->getType())
770 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000771 return LHS;
772}
773
Dan Gohman890f92b2009-04-18 17:56:28 +0000774Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +0000775 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
776 const Type *Ty = LHS->getType();
777 for (int i = S->getNumOperands()-2; i >= 0; --i) {
778 // In the case of mixed integer and pointer types, do the
779 // rest of the comparisons as integer.
780 if (S->getOperand(i)->getType() != Ty) {
781 Ty = SE.getEffectiveSCEVType(Ty);
782 LHS = InsertNoopCastOfTo(LHS, Ty);
783 }
Dan Gohman92fcdca2009-06-09 17:18:38 +0000784 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000785 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000786 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000787 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000788 InsertedValues.insert(Sel);
789 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000790 }
Dan Gohman0196dc52009-07-14 20:57:04 +0000791 // In the case of mixed integer and pointer types, cast the
792 // final result back to the pointer type.
793 if (LHS->getType() != S->getType())
794 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000795 return LHS;
796}
797
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000798Value *SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr *S) {
799 return ConstantExpr::getOffsetOf(S->getStructType(), S->getFieldNo());
800}
801
802Value *SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr *S) {
803 return ConstantExpr::getSizeOf(S->getAllocType());
804}
805
Dan Gohman0bba49c2009-07-07 17:06:11 +0000806Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000807 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000808 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000809 if (Ty) {
810 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
811 "non-trivial casts should be done with the SCEVs directly!");
812 V = InsertNoopCastOfTo(V, Ty);
813 }
814 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000815}
816
Dan Gohman890f92b2009-04-18 17:56:28 +0000817Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000818 // Compute an insertion point for this SCEV object. Hoist the instructions
819 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +0000820 Instruction *InsertPt = Builder.GetInsertPoint();
821 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000822 L = L->getParentLoop())
823 if (S->isLoopInvariant(L)) {
824 if (!L) break;
825 if (BasicBlock *Preheader = L->getLoopPreheader())
826 InsertPt = Preheader->getTerminator();
827 } else {
828 // If the SCEV is computable at this level, insert it into the header
829 // after the PHIs (and after any other instructions that we've inserted
830 // there) so that it is guaranteed to dominate any user inside the loop.
831 if (L && S->hasComputableLoopEvolution(L))
832 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman267a3852009-06-27 21:18:18 +0000833 while (isInsertedInstruction(InsertPt))
834 InsertPt = next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000835 break;
836 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000837
Dan Gohman667d7872009-06-26 22:53:46 +0000838 // Check to see if we already expanded this here.
839 std::map<std::pair<const SCEV *, Instruction *>,
840 AssertingVH<Value> >::iterator I =
841 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +0000842 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +0000843 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +0000844
845 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
846 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
847 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +0000848
849 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000850 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000851
Dan Gohman667d7872009-06-26 22:53:46 +0000852 // Remember the expanded value for this SCEV at this location.
853 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
854
Dan Gohman267a3852009-06-27 21:18:18 +0000855 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000856 return V;
857}
Dan Gohman1d09de32009-06-05 16:35:53 +0000858
859/// getOrInsertCanonicalInductionVariable - This method returns the
860/// canonical induction variable of the specified type for the specified
861/// loop (inserting one if there is none). A canonical induction variable
862/// starts at zero and steps by one on each iteration.
863Value *
864SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
865 const Type *Ty) {
866 assert(Ty->isInteger() && "Can only insert integer induction variables!");
Dan Gohman0bba49c2009-07-07 17:06:11 +0000867 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000868 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +0000869 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
870 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000871 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +0000872 if (SaveInsertBB)
873 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000874 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +0000875}