blob: b049f424fa88f82cf22fd30a033a3d4cb0f9d635 [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 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000057 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000058
Chris Lattnerca1a4be2006-02-04 09:51:53 +000059 if (Argument *A = dyn_cast<Argument>(V)) {
60 // Check to see if there is already a cast!
61 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
Dan Gohman40a5a1b2009-06-24 01:18:18 +000062 UI != E; ++UI)
Chris Lattnerca1a4be2006-02-04 09:51:53 +000063 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000064 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000065 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000066 // If the cast isn't the first instruction of the function, move it.
Dan Gohman40a5a1b2009-06-24 01:18:18 +000067 if (BasicBlock::iterator(CI) !=
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000068 A->getParent()->getEntryBlock().begin()) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +000069 // Recreate the cast at the beginning of the entry block.
70 // The old cast is left in place in case it is being used
71 // as an insert point.
72 Instruction *NewCI =
Dan Gohman267a3852009-06-27 21:18:18 +000073 CastInst::Create(Op, V, Ty, "",
Dan Gohman40a5a1b2009-06-24 01:18:18 +000074 A->getParent()->getEntryBlock().begin());
75 NewCI->takeName(CI);
76 CI->replaceAllUsesWith(NewCI);
77 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000078 }
79 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000080 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +000081
Dan Gohman267a3852009-06-27 21:18:18 +000082 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
Dan Gohmancf5ab822009-05-01 17:13:31 +000083 A->getParent()->getEntryBlock().begin());
Dan Gohmana10756e2010-01-21 02:09:26 +000084 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +000085 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000086 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000087
Chris Lattnerca1a4be2006-02-04 09:51:53 +000088 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000089
Chris Lattnerca1a4be2006-02-04 09:51:53 +000090 // Check to see if there is already a cast. If there is, use it.
91 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
92 UI != E; ++UI) {
93 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000094 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000095 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000096 BasicBlock::iterator It = I; ++It;
97 if (isa<InvokeInst>(I))
98 It = cast<InvokeInst>(I)->getNormalDest()->begin();
99 while (isa<PHINode>(It)) ++It;
100 if (It != BasicBlock::iterator(CI)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000101 // Recreate the cast at the beginning of the entry block.
102 // The old cast is left in place in case it is being used
103 // as an insert point.
Dan Gohman267a3852009-06-27 21:18:18 +0000104 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000105 NewCI->takeName(CI);
106 CI->replaceAllUsesWith(NewCI);
107 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000108 }
109 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000110 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 }
112 BasicBlock::iterator IP = I; ++IP;
113 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
114 IP = II->getNormalDest()->begin();
115 while (isa<PHINode>(IP)) ++IP;
Dan Gohman267a3852009-06-27 21:18:18 +0000116 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
Dan Gohmana10756e2010-01-21 02:09:26 +0000117 rememberInstruction(CI);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000118 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000119}
120
Chris Lattner7fec90e2007-04-13 05:04:18 +0000121/// InsertBinop - Insert the specified binary operator, doing a small amount
122/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000123Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
124 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000125 // Fold a binop with constant operands.
126 if (Constant *CLHS = dyn_cast<Constant>(LHS))
127 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000128 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000129
Chris Lattner7fec90e2007-04-13 05:04:18 +0000130 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
131 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000132 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
133 // Scanning starts from the last instruction before the insertion point.
134 BasicBlock::iterator IP = Builder.GetInsertPoint();
135 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000136 --IP;
137 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000138 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
139 IP->getOperand(1) == RHS)
140 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000141 if (IP == BlockBegin) break;
142 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000143 }
Dan Gohman267a3852009-06-27 21:18:18 +0000144
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000145 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000146 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000147 rememberInstruction(BO);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000148 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000149}
150
Dan Gohman4a4f7672009-05-27 02:00:53 +0000151/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000152/// division. If so, update S with Factor divided out and return true.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000153/// S need not be evenly divisble if a reasonable remainder can be
154/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000155/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
156/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
157/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000158static bool FactorOutConstant(const SCEV *&S,
159 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000160 const SCEV *Factor,
161 ScalarEvolution &SE,
162 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000163 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000164 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000165 return true;
166
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000167 // x/x == 1.
168 if (S == Factor) {
169 S = SE.getIntegerSCEV(1, S->getType());
170 return true;
171 }
172
Dan Gohman453aa4f2009-05-24 18:06:31 +0000173 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000174 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000175 // 0/x == 0.
176 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000177 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000178 // Check for divisibility.
179 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
180 ConstantInt *CI =
181 ConstantInt::get(SE.getContext(),
182 C->getValue()->getValue().sdiv(
183 FC->getValue()->getValue()));
184 // If the quotient is zero and the remainder is non-zero, reject
185 // the value at this scale. It will be considered for subsequent
186 // smaller scales.
187 if (!CI->isZero()) {
188 const SCEV *Div = SE.getConstant(CI);
189 S = Div;
190 Remainder =
191 SE.getAddExpr(Remainder,
192 SE.getConstant(C->getValue()->getValue().srem(
193 FC->getValue()->getValue())));
194 return true;
195 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000196 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000197 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000198
199 // In a Mul, check if there is a constant operand which is a multiple
200 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000201 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
202 if (TD) {
203 // With TargetData, the size is known. Check if there is a constant
204 // operand which is a multiple of the given factor. If so, we can
205 // factor it.
206 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
207 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
208 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
209 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
210 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
211 MOperands.end());
212 NewMulOps[0] =
213 SE.getConstant(C->getValue()->getValue().sdiv(
214 FC->getValue()->getValue()));
215 S = SE.getMulExpr(NewMulOps);
216 return true;
217 }
218 } else {
219 // Without TargetData, check if Factor can be factored out of any of the
220 // Mul's operands. If so, we can just remove it.
221 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
222 const SCEV *SOp = M->getOperand(i);
223 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
224 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
225 Remainder->isZero()) {
226 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
227 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
228 MOperands.end());
229 NewMulOps[i] = SOp;
230 S = SE.getMulExpr(NewMulOps);
231 return true;
232 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000233 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000234 }
235 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000236
237 // In an AddRec, check if both start and step are divisible.
238 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000239 const SCEV *Step = A->getStepRecurrence(SE);
240 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000241 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000242 return false;
243 if (!StepRem->isZero())
244 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000245 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000246 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000247 return false;
248 S = SE.getAddRecExpr(Start, Step, A->getLoop());
249 return true;
250 }
251
252 return false;
253}
254
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000255/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
256/// is the number of SCEVAddRecExprs present, which are kept at the end of
257/// the list.
258///
259static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
260 const Type *Ty,
261 ScalarEvolution &SE) {
262 unsigned NumAddRecs = 0;
263 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
264 ++NumAddRecs;
265 // Group Ops into non-addrecs and addrecs.
266 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
267 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
268 // Let ScalarEvolution sort and simplify the non-addrecs list.
269 const SCEV *Sum = NoAddRecs.empty() ?
270 SE.getIntegerSCEV(0, Ty) :
271 SE.getAddExpr(NoAddRecs);
272 // If it returned an add, use the operands. Otherwise it simplified
273 // the sum into a single value, so just use that.
274 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
275 Ops = Add->getOperands();
276 else {
277 Ops.clear();
278 if (!Sum->isZero())
279 Ops.push_back(Sum);
280 }
281 // Then append the addrecs.
282 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
283}
284
285/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
286/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
287/// This helps expose more opportunities for folding parts of the expressions
288/// into GEP indices.
289///
290static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
291 const Type *Ty,
292 ScalarEvolution &SE) {
293 // Find the addrecs.
294 SmallVector<const SCEV *, 8> AddRecs;
295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
296 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
297 const SCEV *Start = A->getStart();
298 if (Start->isZero()) break;
299 const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
300 AddRecs.push_back(SE.getAddRecExpr(Zero,
301 A->getStepRecurrence(SE),
302 A->getLoop()));
303 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
304 Ops[i] = Zero;
305 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
306 e += Add->getNumOperands();
307 } else {
308 Ops[i] = Start;
309 }
310 }
311 if (!AddRecs.empty()) {
312 // Add the addrecs onto the end of the list.
313 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
314 // Resort the operand list, moving any constants to the front.
315 SimplifyAddOperands(Ops, Ty, SE);
316 }
317}
318
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000319/// expandAddToGEP - Expand an addition expression with a pointer type into
320/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
321/// BasicAliasAnalysis and other passes analyze the result. See the rules
322/// for getelementptr vs. inttoptr in
323/// http://llvm.org/docs/LangRef.html#pointeraliasing
324/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000325///
Dan Gohman3abf9052010-01-19 22:26:02 +0000326/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000327/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
328/// they may introduce pointer arithmetic which may not be safely converted
329/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000330///
331/// Design note: It might seem desirable for this function to be more
332/// loop-aware. If some of the indices are loop-invariant while others
333/// aren't, it might seem desirable to emit multiple GEPs, keeping the
334/// loop-invariant portions of the overall computation outside the loop.
335/// However, there are a few reasons this is not done here. Hoisting simple
336/// arithmetic is a low-level optimization that often isn't very
337/// important until late in the optimization process. In fact, passes
338/// like InstructionCombining will combine GEPs, even if it means
339/// pushing loop-invariant computation down into loops, so even if the
340/// GEPs were split here, the work would quickly be undone. The
341/// LoopStrengthReduction pass, which is usually run quite late (and
342/// after the last InstructionCombining pass), takes care of hoisting
343/// loop-invariant portions of expressions, after considering what
344/// can be folded using target addressing modes.
345///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000346Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
347 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000348 const PointerType *PTy,
349 const Type *Ty,
350 Value *V) {
351 const Type *ElTy = PTy->getElementType();
352 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000353 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000354 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000355
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000356 // Split AddRecs up into parts as either of the parts may be usable
357 // without the other.
358 SplitAddRecs(Ops, Ty, SE);
359
Bob Wilsoneb356992009-12-04 01:33:04 +0000360 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000361 // operands into GEP indices, at each level. The first index in a GEP
362 // indexes into the array implied by the pointer operand; the rest of
363 // the indices index into the element or field type selected by the
364 // preceding index.
365 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000366 const SCEV *ElSize = SE.getAllocSizeExpr(ElTy);
367 // If the scale size is not 0, attempt to factor out a scale for
368 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000369 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000370 if (ElTy->isSized() && !ElSize->isZero()) {
371 SmallVector<const SCEV *, 8> NewOps;
372 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000373 const SCEV *Op = Ops[i];
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000374 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
375 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
376 // Op now has ElSize factored out.
377 ScaledOps.push_back(Op);
378 if (!Remainder->isZero())
379 NewOps.push_back(Remainder);
380 AnyNonZeroIndices = true;
381 } else {
382 // The operand was not divisible, so add it to the list of operands
383 // we'll scan next iteration.
384 NewOps.push_back(Ops[i]);
Dan Gohman5be18e82009-05-19 02:15:55 +0000385 }
386 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000387 // If we made any changes, update Ops.
388 if (!ScaledOps.empty()) {
389 Ops = NewOps;
390 SimplifyAddOperands(Ops, Ty, SE);
391 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000392 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000393
394 // Record the scaled array index for this level of the type. If
395 // we didn't find any operands that could be factored, tentatively
396 // assume that element zero was selected (since the zero offset
397 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000398 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000399 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000400 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
401 GepIndices.push_back(Scaled);
402
403 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000404 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
405 bool FoundFieldNo = false;
406 // An empty struct has no fields.
407 if (STy->getNumElements() == 0) break;
408 if (SE.TD) {
409 // With TargetData, field offsets are known. See if a constant offset
410 // falls within any of the struct fields.
411 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000412 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
413 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
414 const StructLayout &SL = *SE.TD->getStructLayout(STy);
415 uint64_t FullOffset = C->getValue()->getZExtValue();
416 if (FullOffset < SL.getSizeInBytes()) {
417 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000418 GepIndices.push_back(
419 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 ElTy = STy->getTypeAtIndex(ElIdx);
421 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000422 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000423 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000424 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000425 }
426 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000427 } else {
428 // Without TargetData, just check for a SCEVFieldOffsetExpr of the
429 // appropriate struct type.
430 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
431 if (const SCEVFieldOffsetExpr *FO =
432 dyn_cast<SCEVFieldOffsetExpr>(Ops[i]))
433 if (FO->getStructType() == STy) {
434 unsigned FieldNo = FO->getFieldNo();
435 GepIndices.push_back(
436 ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
437 FieldNo));
438 ElTy = STy->getTypeAtIndex(FieldNo);
439 Ops[i] = SE.getConstant(Ty, 0);
440 AnyNonZeroIndices = true;
441 FoundFieldNo = true;
442 break;
443 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000444 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000445 // If no struct field offsets were found, tentatively assume that
446 // field zero was selected (since the zero offset would obviously
447 // be folded away).
448 if (!FoundFieldNo) {
449 ElTy = STy->getTypeAtIndex(0u);
450 GepIndices.push_back(
451 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
452 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000453 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000454
455 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
456 ElTy = ATy->getElementType();
457 else
458 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000459 }
460
461 // If none of the operands were convertable to proper GEP indices, cast
462 // the base to i8* and do an ugly getelementptr with that. It's still
463 // better than ptrtoint+arithmetic+inttoptr at least.
464 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000465 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000466 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000467 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000468
469 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000470 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000471
472 // Fold a GEP with constant operands.
473 if (Constant *CLHS = dyn_cast<Constant>(V))
474 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000475 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000476
477 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
478 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000479 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
480 // Scanning starts from the last instruction before the insertion point.
481 BasicBlock::iterator IP = Builder.GetInsertPoint();
482 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000483 --IP;
484 for (; ScanLimit; --IP, --ScanLimit) {
485 if (IP->getOpcode() == Instruction::GetElementPtr &&
486 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
487 return IP;
488 if (IP == BlockBegin) break;
489 }
490 }
491
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000492 // Emit a GEP.
493 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000494 rememberInstruction(GEP);
Dan Gohman5be18e82009-05-19 02:15:55 +0000495 return GEP;
496 }
497
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000498 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
499 // because ScalarEvolution may have changed the address arithmetic to
500 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000501 Value *Casted = V;
502 if (V->getType() != PTy)
503 Casted = InsertNoopCastOfTo(Casted, PTy);
504 Value *GEP = Builder.CreateGEP(Casted,
Dan Gohman267a3852009-06-27 21:18:18 +0000505 GepIndices.begin(),
506 GepIndices.end(),
507 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000508 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000509 rememberInstruction(GEP);
Dan Gohman5be18e82009-05-19 02:15:55 +0000510 return expand(SE.getAddExpr(Ops));
511}
512
Dan Gohmana10756e2010-01-21 02:09:26 +0000513/// isNonConstantNegative - Return true if the specified scev is negated, but
514/// not a constant.
515static bool isNonConstantNegative(const SCEV *F) {
516 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
517 if (!Mul) return false;
518
519 // If there is a constant factor, it will be first.
520 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
521 if (!SC) return false;
522
523 // Return true if the value is negative, this matches things like (-42 * V).
524 return SC->getValue()->getValue().isNegative();
525}
526
Dan Gohman890f92b2009-04-18 17:56:28 +0000527Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanc70c3772009-09-26 16:11:57 +0000528 int NumOperands = S->getNumOperands();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000529 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000530
531 // Find the index of an operand to start with. Choose the operand with
532 // pointer type, if there is one, or the last operand otherwise.
533 int PIdx = 0;
534 for (; PIdx != NumOperands - 1; ++PIdx)
535 if (isa<PointerType>(S->getOperand(PIdx)->getType())) break;
536
537 // Expand code for the operand that we chose.
538 Value *V = expand(S->getOperand(PIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000539
Dan Gohman453aa4f2009-05-24 18:06:31 +0000540 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
541 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000542 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
Dan Gohmanc70c3772009-09-26 16:11:57 +0000543 // Take the operand at PIdx out of the list.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000544 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
Dan Gohmanc70c3772009-09-26 16:11:57 +0000545 SmallVector<const SCEV *, 8> NewOps;
546 NewOps.insert(NewOps.end(), Ops.begin(), Ops.begin() + PIdx);
547 NewOps.insert(NewOps.end(), Ops.begin() + PIdx + 1, Ops.end());
548 // Make a GEP.
549 return expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, V);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000550 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000551
Dan Gohmanc70c3772009-09-26 16:11:57 +0000552 // Otherwise, we'll expand the rest of the SCEVAddExpr as plain integer
553 // arithmetic.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000554 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000555
556 // Emit a bunch of add instructions
Dan Gohmanc70c3772009-09-26 16:11:57 +0000557 for (int i = NumOperands-1; i >= 0; --i) {
558 if (i == PIdx) continue;
Dan Gohmana10756e2010-01-21 02:09:26 +0000559 const SCEV *Op = S->getOperand(i);
560 if (isNonConstantNegative(Op)) {
561 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
562 V = InsertBinop(Instruction::Sub, V, W);
563 } else {
564 Value *W = expandCodeFor(Op, Ty);
565 V = InsertBinop(Instruction::Add, V, W);
566 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000567 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000568 return V;
569}
Dan Gohman5be18e82009-05-19 02:15:55 +0000570
Dan Gohman890f92b2009-04-18 17:56:28 +0000571Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000572 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000573 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000574 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000575 if (SC->getValue()->isAllOnesValue())
576 FirstOp = 1;
577
578 int i = S->getNumOperands()-2;
Dan Gohman92fcdca2009-06-09 17:18:38 +0000579 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000580
581 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000582 for (; i >= FirstOp; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000583 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000584 V = InsertBinop(Instruction::Mul, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000585 }
586
Nate Begeman36f891b2005-07-30 00:12:19 +0000587 // -1 * ... ---> 0 - ...
588 if (FirstOp == 1)
Owen Andersona7235ea2009-07-31 20:28:14 +0000589 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000590 return V;
591}
592
Dan Gohman890f92b2009-04-18 17:56:28 +0000593Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000594 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000595
Dan Gohman92fcdca2009-06-09 17:18:38 +0000596 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000597 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000598 const APInt &RHS = SC->getValue()->getValue();
599 if (RHS.isPowerOf2())
600 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000601 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000602 }
603
Dan Gohman92fcdca2009-06-09 17:18:38 +0000604 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000605 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000606}
607
Dan Gohman453aa4f2009-05-24 18:06:31 +0000608/// Move parts of Base into Rest to leave Base with the minimal
609/// expression that provides a pointer operand suitable for a
610/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000611static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000612 ScalarEvolution &SE) {
613 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
614 Base = A->getStart();
615 Rest = SE.getAddExpr(Rest,
616 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
617 A->getStepRecurrence(SE),
618 A->getLoop()));
619 }
620 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
621 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000622 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000623 NewAddOps.back() = Rest;
624 Rest = SE.getAddExpr(NewAddOps);
625 ExposePointerBase(Base, Rest, SE);
626 }
627}
628
Dan Gohmana10756e2010-01-21 02:09:26 +0000629/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
630/// the base addrec, which is the addrec without any non-loop-dominating
631/// values, and return the PHI.
632PHINode *
633SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
634 const Loop *L,
635 const Type *ExpandTy,
636 const Type *IntTy) {
637 // Reuse a previously-inserted PHI, if present.
638 for (BasicBlock::iterator I = L->getHeader()->begin();
639 PHINode *PN = dyn_cast<PHINode>(I); ++I)
640 if (isInsertedInstruction(PN) && SE.getSCEV(PN) == Normalized)
641 return PN;
642
643 // Save the original insertion point so we can restore it when we're done.
644 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
645 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
646
647 // Expand code for the start value.
648 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
649 L->getHeader()->begin());
650
651 // Expand code for the step value. Insert instructions right before the
652 // terminator corresponding to the back-edge. Do this before creating the PHI
653 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
654 // negative, insert a sub instead of an add for the increment (unless it's a
655 // constant, because subtracts of constants are canonicalized to adds).
656 const SCEV *Step = Normalized->getStepRecurrence(SE);
657 bool isPointer = isa<PointerType>(ExpandTy);
658 bool isNegative = !isPointer && isNonConstantNegative(Step);
659 if (isNegative)
660 Step = SE.getNegativeSCEV(Step);
661 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
662
663 // Create the PHI.
664 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
665 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
666 rememberInstruction(PN);
667
668 // Create the step instructions and populate the PHI.
669 BasicBlock *Header = L->getHeader();
670 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
671 HPI != HPE; ++HPI) {
672 BasicBlock *Pred = *HPI;
673
674 // Add a start value.
675 if (!L->contains(Pred)) {
676 PN->addIncoming(StartV, Pred);
677 continue;
678 }
679
680 // Create a step value and add it to the PHI. If IVIncInsertLoop is
681 // non-null and equal to the addrec's loop, insert the instructions
682 // at IVIncInsertPos.
683 Instruction *InsertPos = L == IVIncInsertLoop ?
684 IVIncInsertPos : Pred->getTerminator();
685 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
686 Value *IncV;
687 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
688 if (isPointer) {
689 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
690 // If the step isn't constant, don't use an implicitly scaled GEP, because
691 // that would require a multiply inside the loop.
692 if (!isa<ConstantInt>(StepV))
693 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
694 GEPPtrTy->getAddressSpace());
695 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
696 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
697 if (IncV->getType() != PN->getType()) {
698 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
699 rememberInstruction(IncV);
700 }
701 } else {
702 IncV = isNegative ?
703 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
704 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
705 rememberInstruction(IncV);
706 }
707 PN->addIncoming(IncV, Pred);
708 }
709
710 // Restore the original insert point.
711 if (SaveInsertBB)
712 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
713
714 // Remember this PHI, even in post-inc mode.
715 InsertedValues.insert(PN);
716
717 return PN;
718}
719
720Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
721 const Type *STy = S->getType();
722 const Type *IntTy = SE.getEffectiveSCEVType(STy);
723 const Loop *L = S->getLoop();
724
725 // Determine a normalized form of this expression, which is the expression
726 // before any post-inc adjustment is made.
727 const SCEVAddRecExpr *Normalized = S;
728 if (L == PostIncLoop) {
729 const SCEV *Step = S->getStepRecurrence(SE);
730 Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
731 }
732
733 // Strip off any non-loop-dominating component from the addrec start.
734 const SCEV *Start = Normalized->getStart();
735 const SCEV *PostLoopOffset = 0;
736 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
737 PostLoopOffset = Start;
738 Start = SE.getIntegerSCEV(0, Normalized->getType());
739 Normalized =
740 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
741 Normalized->getStepRecurrence(SE),
742 Normalized->getLoop()));
743 }
744
745 // Strip off any non-loop-dominating component from the addrec step.
746 const SCEV *Step = Normalized->getStepRecurrence(SE);
747 const SCEV *PostLoopScale = 0;
748 if (!Step->hasComputableLoopEvolution(L) &&
749 !Step->dominates(L->getHeader(), SE.DT)) {
750 PostLoopScale = Step;
751 Step = SE.getIntegerSCEV(1, Normalized->getType());
752 Normalized =
753 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
754 Normalized->getLoop()));
755 }
756
757 // Expand the core addrec. If we need post-loop scaling, force it to
758 // expand to an integer type to avoid the need for additional casting.
759 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
760 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
761
762 // Accomodate post-inc mode, if necessary.
763 Value *Result;
764 if (L != PostIncLoop)
765 Result = PN;
766 else {
767 // In PostInc mode, use the post-incremented value.
768 BasicBlock *LatchBlock = L->getLoopLatch();
769 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
770 Result = PN->getIncomingValueForBlock(LatchBlock);
771 }
772
773 // Re-apply any non-loop-dominating scale.
774 if (PostLoopScale) {
775 Result = Builder.CreateMul(Result,
776 expandCodeFor(PostLoopScale, IntTy));
777 rememberInstruction(Result);
778 }
779
780 // Re-apply any non-loop-dominating offset.
781 if (PostLoopOffset) {
782 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
783 const SCEV *const OffsetArray[1] = { PostLoopOffset };
784 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
785 } else {
786 Result = Builder.CreateAdd(Result,
787 expandCodeFor(PostLoopOffset, IntTy));
788 rememberInstruction(Result);
789 }
790 }
791
792 return Result;
793}
794
Dan Gohman890f92b2009-04-18 17:56:28 +0000795Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +0000796 if (!CanonicalMode) return expandAddRecExprLiterally(S);
797
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000798 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000799 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000800
Dan Gohman4d8414f2009-06-13 16:25:49 +0000801 // First check for an existing canonical IV in a suitable type.
802 PHINode *CanonicalIV = 0;
803 if (PHINode *PN = L->getCanonicalInductionVariable())
804 if (SE.isSCEVable(PN->getType()) &&
805 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
806 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
807 CanonicalIV = PN;
808
809 // Rewrite an AddRec in terms of the canonical induction variable, if
810 // its type is more narrow.
811 if (CanonicalIV &&
812 SE.getTypeSizeInBits(CanonicalIV->getType()) >
813 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf3f1be62009-09-28 21:01:47 +0000814 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
815 SmallVector<const SCEV *, 4> NewOps(Ops.size());
816 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
817 NewOps[i] = SE.getAnyExtendExpr(Ops[i], CanonicalIV->getType());
818 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +0000819 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
820 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000821 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +0000822 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Dan Gohman4d8414f2009-06-13 16:25:49 +0000823 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
824 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
825 NewInsertPt);
Dan Gohman267a3852009-06-27 21:18:18 +0000826 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000827 return V;
828 }
829
Nate Begeman36f891b2005-07-30 00:12:19 +0000830 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000831 if (!S->getStart()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000832 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
833 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +0000834 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000835 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000836
837 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
838 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000839 const SCEV *Base = S->getStart();
840 const SCEV *RestArray[1] = { Rest };
841 // Dig into the expression to find the pointer base for a GEP.
842 ExposePointerBase(Base, RestArray[0], SE);
843 // If we found a pointer, expand the AddRec with a GEP.
844 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
845 // Make sure the Base isn't something exotic, such as a multiplied
846 // or divided pointer value. In those cases, the result type isn't
847 // actually a pointer type.
848 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
849 Value *StartV = expand(Base);
850 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
851 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000852 }
853 }
854
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000855 // Just do a normal add. Pre-expand the operands to suppress folding.
856 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
857 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +0000858 }
859
860 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000861 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000862 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000863 // If there's a canonical IV, just use it.
864 if (CanonicalIV) {
865 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
866 "IVs with types different from the canonical IV should "
867 "already have been handled!");
868 return CanonicalIV;
869 }
870
Nate Begeman36f891b2005-07-30 00:12:19 +0000871 // Create and insert the PHI node for the induction variable in the
872 // specified loop.
873 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000874 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmana10756e2010-01-21 02:09:26 +0000875 rememberInstruction(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000876
Owen Andersoneed707b2009-07-24 23:12:02 +0000877 Constant *One = ConstantInt::get(Ty, 1);
Dan Gohman83d57742009-09-27 17:46:40 +0000878 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
879 HPI != HPE; ++HPI)
880 if (L->contains(*HPI)) {
Dan Gohman3abf9052010-01-19 22:26:02 +0000881 // Insert a unit add instruction right before the terminator
882 // corresponding to the back-edge.
Dan Gohman83d57742009-09-27 17:46:40 +0000883 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
884 (*HPI)->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +0000885 rememberInstruction(Add);
Dan Gohman83d57742009-09-27 17:46:40 +0000886 PN->addIncoming(Add, *HPI);
887 } else {
888 PN->addIncoming(Constant::getNullValue(Ty), *HPI);
889 }
Nate Begeman36f891b2005-07-30 00:12:19 +0000890 }
891
Dan Gohman4d8414f2009-06-13 16:25:49 +0000892 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +0000893 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +0000894 Value *I = CanonicalIV ?
895 CanonicalIV :
896 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000897
Chris Lattnerdf14a042005-10-30 06:24:33 +0000898 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000899 if (S->isAffine()) // {0,+,F} --> i*F
900 return
901 expand(SE.getTruncateOrNoop(
902 SE.getMulExpr(SE.getUnknown(I),
903 SE.getNoopOrAnyExtend(S->getOperand(1),
904 I->getType())),
905 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +0000906
907 // If this is a chain of recurrences, turn it into a closed form, using the
908 // folders, then expandCodeFor the closed form. This allows the folders to
909 // simplify the expression without having to build a bunch of special code
910 // into this folder.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000911 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000912
Dan Gohman4d8414f2009-06-13 16:25:49 +0000913 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000914 const SCEV *NewS = S;
915 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000916 if (isa<SCEVAddRecExpr>(Ext))
917 NewS = Ext;
918
Dan Gohman0bba49c2009-07-07 17:06:11 +0000919 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000920 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000921
Dan Gohman4d8414f2009-06-13 16:25:49 +0000922 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000923 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +0000924 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +0000925}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000926
Dan Gohman890f92b2009-04-18 17:56:28 +0000927Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000928 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000929 Value *V = expandCodeFor(S->getOperand(),
930 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000931 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000932 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000933 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000934}
935
Dan Gohman890f92b2009-04-18 17:56:28 +0000936Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000937 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000938 Value *V = expandCodeFor(S->getOperand(),
939 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000940 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000941 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000942 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000943}
944
Dan Gohman890f92b2009-04-18 17:56:28 +0000945Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000946 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000947 Value *V = expandCodeFor(S->getOperand(),
948 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000949 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000950 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000951 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000952}
953
Dan Gohman890f92b2009-04-18 17:56:28 +0000954Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +0000955 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
956 const Type *Ty = LHS->getType();
957 for (int i = S->getNumOperands()-2; i >= 0; --i) {
958 // In the case of mixed integer and pointer types, do the
959 // rest of the comparisons as integer.
960 if (S->getOperand(i)->getType() != Ty) {
961 Ty = SE.getEffectiveSCEVType(Ty);
962 LHS = InsertNoopCastOfTo(LHS, Ty);
963 }
Dan Gohman92fcdca2009-06-09 17:18:38 +0000964 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000965 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000966 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000967 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +0000968 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000969 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000970 }
Dan Gohman0196dc52009-07-14 20:57:04 +0000971 // In the case of mixed integer and pointer types, cast the
972 // final result back to the pointer type.
973 if (LHS->getType() != S->getType())
974 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000975 return LHS;
976}
977
Dan Gohman890f92b2009-04-18 17:56:28 +0000978Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +0000979 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
980 const Type *Ty = LHS->getType();
981 for (int i = S->getNumOperands()-2; i >= 0; --i) {
982 // In the case of mixed integer and pointer types, do the
983 // rest of the comparisons as integer.
984 if (S->getOperand(i)->getType() != Ty) {
985 Ty = SE.getEffectiveSCEVType(Ty);
986 LHS = InsertNoopCastOfTo(LHS, Ty);
987 }
Dan Gohman92fcdca2009-06-09 17:18:38 +0000988 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000989 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000990 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000991 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +0000992 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000993 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000994 }
Dan Gohman0196dc52009-07-14 20:57:04 +0000995 // In the case of mixed integer and pointer types, cast the
996 // final result back to the pointer type.
997 if (LHS->getType() != S->getType())
998 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +0000999 return LHS;
1000}
1001
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001002Value *SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr *S) {
1003 return ConstantExpr::getOffsetOf(S->getStructType(), S->getFieldNo());
1004}
1005
1006Value *SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr *S) {
1007 return ConstantExpr::getSizeOf(S->getAllocType());
1008}
1009
Dan Gohman0bba49c2009-07-07 17:06:11 +00001010Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001011 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001012 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001013 if (Ty) {
1014 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1015 "non-trivial casts should be done with the SCEVs directly!");
1016 V = InsertNoopCastOfTo(V, Ty);
1017 }
1018 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001019}
1020
Dan Gohman890f92b2009-04-18 17:56:28 +00001021Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001022 // Compute an insertion point for this SCEV object. Hoist the instructions
1023 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001024 Instruction *InsertPt = Builder.GetInsertPoint();
1025 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001026 L = L->getParentLoop())
1027 if (S->isLoopInvariant(L)) {
1028 if (!L) break;
1029 if (BasicBlock *Preheader = L->getLoopPreheader())
1030 InsertPt = Preheader->getTerminator();
1031 } else {
1032 // If the SCEV is computable at this level, insert it into the header
1033 // after the PHIs (and after any other instructions that we've inserted
1034 // there) so that it is guaranteed to dominate any user inside the loop.
1035 if (L && S->hasComputableLoopEvolution(L))
1036 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman267a3852009-06-27 21:18:18 +00001037 while (isInsertedInstruction(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001038 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001039 break;
1040 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001041
Dan Gohman667d7872009-06-26 22:53:46 +00001042 // Check to see if we already expanded this here.
1043 std::map<std::pair<const SCEV *, Instruction *>,
1044 AssertingVH<Value> >::iterator I =
1045 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001046 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001047 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001048
1049 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1050 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1051 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001052
1053 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001054 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001055
Dan Gohman667d7872009-06-26 22:53:46 +00001056 // Remember the expanded value for this SCEV at this location.
Dan Gohmana10756e2010-01-21 02:09:26 +00001057 if (!PostIncLoop)
1058 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001059
Dan Gohman267a3852009-06-27 21:18:18 +00001060 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001061 return V;
1062}
Dan Gohman1d09de32009-06-05 16:35:53 +00001063
1064/// getOrInsertCanonicalInductionVariable - This method returns the
1065/// canonical induction variable of the specified type for the specified
1066/// loop (inserting one if there is none). A canonical induction variable
1067/// starts at zero and steps by one on each iteration.
1068Value *
1069SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1070 const Type *Ty) {
1071 assert(Ty->isInteger() && "Can only insert integer induction variables!");
Dan Gohman0bba49c2009-07-07 17:06:11 +00001072 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001073 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +00001074 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1075 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001076 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +00001077 if (SaveInsertBB)
1078 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001079 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001080}