blob: 2e18ceac525eb50175ec7d0aa11d5ac90db5d466 [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"
Dale Johannesen8d50ea72010-03-05 21:12:40 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000019#include "llvm/LLVMContext.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000020#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000021#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000022using namespace llvm;
23
Dan Gohman267a3852009-06-27 21:18:18 +000024/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
25/// which must be possible with a noop cast, doing what we can to share
26/// the casts.
27Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
28 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
29 assert((Op == Instruction::BitCast ||
30 Op == Instruction::PtrToInt ||
31 Op == Instruction::IntToPtr) &&
32 "InsertNoopCastOfTo cannot perform non-noop casts!");
33 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
34 "InsertNoopCastOfTo cannot change sizes!");
35
Dan Gohman2d1be872009-04-16 03:18:22 +000036 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000037 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000038 return V;
39
Dan Gohmanf04fa482009-04-16 15:52:57 +000040 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000041 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000042 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000043 if (CastInst *CI = dyn_cast<CastInst>(V))
44 if ((CI->getOpcode() == Instruction::PtrToInt ||
45 CI->getOpcode() == Instruction::IntToPtr) &&
46 SE.getTypeSizeInBits(CI->getType()) ==
47 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
48 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
50 if ((CE->getOpcode() == Instruction::PtrToInt ||
51 CE->getOpcode() == Instruction::IntToPtr) &&
52 SE.getTypeSizeInBits(CE->getType()) ==
53 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
54 return CE->getOperand(0);
55 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000056
Chris Lattnerca1a4be2006-02-04 09:51:53 +000057 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000058 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000059
Chris Lattnerca1a4be2006-02-04 09:51:53 +000060 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());
Dan Gohmana10756e2010-01-21 02:09:26 +000085 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +000086 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 Gohmanc37e3d52010-01-21 10:08:42 +0000102 // Recreate the cast after the user.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000103 // 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);
Dan Gohmanc37e3d52010-01-21 10:08:42 +0000108 rememberInstruction(NewCI);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000109 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000110 }
Dan Gohmanc37e3d52010-01-21 10:08:42 +0000111 rememberInstruction(CI);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000112 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000113 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000114 }
115 BasicBlock::iterator IP = I; ++IP;
116 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
117 IP = II->getNormalDest()->begin();
118 while (isa<PHINode>(IP)) ++IP;
Dan Gohman267a3852009-06-27 21:18:18 +0000119 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
Dan Gohmana10756e2010-01-21 02:09:26 +0000120 rememberInstruction(CI);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000121 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000122}
123
Chris Lattner7fec90e2007-04-13 05:04:18 +0000124/// InsertBinop - Insert the specified binary operator, doing a small amount
125/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000126Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
127 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000128 // Fold a binop with constant operands.
129 if (Constant *CLHS = dyn_cast<Constant>(LHS))
130 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000131 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000132
Chris Lattner7fec90e2007-04-13 05:04:18 +0000133 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
134 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000135 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
136 // Scanning starts from the last instruction before the insertion point.
137 BasicBlock::iterator IP = Builder.GetInsertPoint();
138 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000139 --IP;
140 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000141 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
142 // generated code.
143 if (isa<DbgInfoIntrinsic>(IP))
144 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000145 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
146 IP->getOperand(1) == RHS)
147 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000148 if (IP == BlockBegin) break;
149 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000150 }
Dan Gohman267a3852009-06-27 21:18:18 +0000151
Dan Gohman087bd1e2010-03-03 05:29:13 +0000152 // Save the original insertion point so we can restore it when we're done.
153 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
154 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
155
156 // Move the insertion point out of as many loops as we can.
157 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
158 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
159 BasicBlock *Preheader = L->getLoopPreheader();
160 if (!Preheader) break;
161
162 // Ok, move up a level.
163 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
164 }
165
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000166 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000167 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000168 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000169
170 // Restore the original insert point.
171 if (SaveInsertBB)
172 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
173
Dan Gohmancf5ab822009-05-01 17:13:31 +0000174 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000175}
176
Dan Gohman4a4f7672009-05-27 02:00:53 +0000177/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000178/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000179/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000180/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000181/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000184static bool FactorOutConstant(const SCEV *&S,
185 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000186 const SCEV *Factor,
187 ScalarEvolution &SE,
188 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000189 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000190 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000191 return true;
192
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000193 // x/x == 1.
194 if (S == Factor) {
195 S = SE.getIntegerSCEV(1, S->getType());
196 return true;
197 }
198
Dan Gohman453aa4f2009-05-24 18:06:31 +0000199 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000200 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000201 // 0/x == 0.
202 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000203 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000204 // Check for divisibility.
205 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
206 ConstantInt *CI =
207 ConstantInt::get(SE.getContext(),
208 C->getValue()->getValue().sdiv(
209 FC->getValue()->getValue()));
210 // If the quotient is zero and the remainder is non-zero, reject
211 // the value at this scale. It will be considered for subsequent
212 // smaller scales.
213 if (!CI->isZero()) {
214 const SCEV *Div = SE.getConstant(CI);
215 S = Div;
216 Remainder =
217 SE.getAddExpr(Remainder,
218 SE.getConstant(C->getValue()->getValue().srem(
219 FC->getValue()->getValue())));
220 return true;
221 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000222 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000223 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000224
225 // In a Mul, check if there is a constant operand which is a multiple
226 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000227 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
228 if (TD) {
229 // With TargetData, the size is known. Check if there is a constant
230 // operand which is a multiple of the given factor. If so, we can
231 // factor it.
232 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000235 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000236 NewMulOps[0] =
237 SE.getConstant(C->getValue()->getValue().sdiv(
238 FC->getValue()->getValue()));
239 S = SE.getMulExpr(NewMulOps);
240 return true;
241 }
242 } else {
243 // Without TargetData, check if Factor can be factored out of any of the
244 // Mul's operands. If so, we can just remove it.
245 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246 const SCEV *SOp = M->getOperand(i);
247 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
248 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000250 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000251 NewMulOps[i] = SOp;
252 S = SE.getMulExpr(NewMulOps);
253 return true;
254 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000255 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000256 }
257 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000258
259 // In an AddRec, check if both start and step are divisible.
260 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000261 const SCEV *Step = A->getStepRecurrence(SE);
262 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000264 return false;
265 if (!StepRem->isZero())
266 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000267 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000268 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000269 return false;
270 S = SE.getAddRecExpr(Start, Step, A->getLoop());
271 return true;
272 }
273
274 return false;
275}
276
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000277/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
278/// is the number of SCEVAddRecExprs present, which are kept at the end of
279/// the list.
280///
281static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
282 const Type *Ty,
283 ScalarEvolution &SE) {
284 unsigned NumAddRecs = 0;
285 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
286 ++NumAddRecs;
287 // Group Ops into non-addrecs and addrecs.
288 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
289 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
290 // Let ScalarEvolution sort and simplify the non-addrecs list.
291 const SCEV *Sum = NoAddRecs.empty() ?
292 SE.getIntegerSCEV(0, Ty) :
293 SE.getAddExpr(NoAddRecs);
294 // If it returned an add, use the operands. Otherwise it simplified
295 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000296 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000297 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmanf9e64722010-03-18 01:17:13 +0000298 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
299 else if (!Sum->isZero())
300 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000301 // Then append the addrecs.
302 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
303}
304
305/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
306/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
307/// This helps expose more opportunities for folding parts of the expressions
308/// into GEP indices.
309///
310static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
311 const Type *Ty,
312 ScalarEvolution &SE) {
313 // Find the addrecs.
314 SmallVector<const SCEV *, 8> AddRecs;
315 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
316 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
317 const SCEV *Start = A->getStart();
318 if (Start->isZero()) break;
319 const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
320 AddRecs.push_back(SE.getAddRecExpr(Zero,
321 A->getStepRecurrence(SE),
322 A->getLoop()));
323 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
324 Ops[i] = Zero;
325 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
326 e += Add->getNumOperands();
327 } else {
328 Ops[i] = Start;
329 }
330 }
331 if (!AddRecs.empty()) {
332 // Add the addrecs onto the end of the list.
333 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
334 // Resort the operand list, moving any constants to the front.
335 SimplifyAddOperands(Ops, Ty, SE);
336 }
337}
338
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000339/// expandAddToGEP - Expand an addition expression with a pointer type into
340/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
341/// BasicAliasAnalysis and other passes analyze the result. See the rules
342/// for getelementptr vs. inttoptr in
343/// http://llvm.org/docs/LangRef.html#pointeraliasing
344/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000345///
Dan Gohman3abf9052010-01-19 22:26:02 +0000346/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000347/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
348/// they may introduce pointer arithmetic which may not be safely converted
349/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000350///
351/// Design note: It might seem desirable for this function to be more
352/// loop-aware. If some of the indices are loop-invariant while others
353/// aren't, it might seem desirable to emit multiple GEPs, keeping the
354/// loop-invariant portions of the overall computation outside the loop.
355/// However, there are a few reasons this is not done here. Hoisting simple
356/// arithmetic is a low-level optimization that often isn't very
357/// important until late in the optimization process. In fact, passes
358/// like InstructionCombining will combine GEPs, even if it means
359/// pushing loop-invariant computation down into loops, so even if the
360/// GEPs were split here, the work would quickly be undone. The
361/// LoopStrengthReduction pass, which is usually run quite late (and
362/// after the last InstructionCombining pass), takes care of hoisting
363/// loop-invariant portions of expressions, after considering what
364/// can be folded using target addressing modes.
365///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000366Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
367 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000368 const PointerType *PTy,
369 const Type *Ty,
370 Value *V) {
371 const Type *ElTy = PTy->getElementType();
372 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000373 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000374 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000375
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000376 // Split AddRecs up into parts as either of the parts may be usable
377 // without the other.
378 SplitAddRecs(Ops, Ty, SE);
379
Bob Wilsoneb356992009-12-04 01:33:04 +0000380 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000381 // operands into GEP indices, at each level. The first index in a GEP
382 // indexes into the array implied by the pointer operand; the rest of
383 // the indices index into the element or field type selected by the
384 // preceding index.
385 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000386 // If the scale size is not 0, attempt to factor out a scale for
387 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000388 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000389 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000390 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000391 if (!ElSize->isZero()) {
392 SmallVector<const SCEV *, 8> NewOps;
393 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
394 const SCEV *Op = Ops[i];
395 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
396 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
397 // Op now has ElSize factored out.
398 ScaledOps.push_back(Op);
399 if (!Remainder->isZero())
400 NewOps.push_back(Remainder);
401 AnyNonZeroIndices = true;
402 } else {
403 // The operand was not divisible, so add it to the list of operands
404 // we'll scan next iteration.
405 NewOps.push_back(Ops[i]);
406 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000407 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000408 // If we made any changes, update Ops.
409 if (!ScaledOps.empty()) {
410 Ops = NewOps;
411 SimplifyAddOperands(Ops, Ty, SE);
412 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000413 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000414 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000415
416 // Record the scaled array index for this level of the type. If
417 // we didn't find any operands that could be factored, tentatively
418 // assume that element zero was selected (since the zero offset
419 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000421 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000422 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
423 GepIndices.push_back(Scaled);
424
425 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000426 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
427 bool FoundFieldNo = false;
428 // An empty struct has no fields.
429 if (STy->getNumElements() == 0) break;
430 if (SE.TD) {
431 // With TargetData, field offsets are known. See if a constant offset
432 // falls within any of the struct fields.
433 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000434 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
435 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
436 const StructLayout &SL = *SE.TD->getStructLayout(STy);
437 uint64_t FullOffset = C->getValue()->getZExtValue();
438 if (FullOffset < SL.getSizeInBytes()) {
439 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000440 GepIndices.push_back(
441 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000442 ElTy = STy->getTypeAtIndex(ElIdx);
443 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000444 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000445 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000446 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000447 }
448 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000449 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000450 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000451 // appropriate struct type.
452 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000453 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000454 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000455 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000456 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000457 GepIndices.push_back(FieldNo);
458 ElTy =
459 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000460 Ops[i] = SE.getConstant(Ty, 0);
461 AnyNonZeroIndices = true;
462 FoundFieldNo = true;
463 break;
464 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000465 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000466 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000467 // If no struct field offsets were found, tentatively assume that
468 // field zero was selected (since the zero offset would obviously
469 // be folded away).
470 if (!FoundFieldNo) {
471 ElTy = STy->getTypeAtIndex(0u);
472 GepIndices.push_back(
473 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
474 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000475 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000476
477 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
478 ElTy = ATy->getElementType();
479 else
480 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000481 }
482
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000483 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000484 // the base to i8* and do an ugly getelementptr with that. It's still
485 // better than ptrtoint+arithmetic+inttoptr at least.
486 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000487 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000488 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000489 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000490
491 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000492 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000493
494 // Fold a GEP with constant operands.
495 if (Constant *CLHS = dyn_cast<Constant>(V))
496 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000497 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000498
499 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
500 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000501 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
502 // Scanning starts from the last instruction before the insertion point.
503 BasicBlock::iterator IP = Builder.GetInsertPoint();
504 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000505 --IP;
506 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000507 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
508 // generated code.
509 if (isa<DbgInfoIntrinsic>(IP))
510 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000511 if (IP->getOpcode() == Instruction::GetElementPtr &&
512 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
513 return IP;
514 if (IP == BlockBegin) break;
515 }
516 }
517
Dan Gohman087bd1e2010-03-03 05:29:13 +0000518 // Save the original insertion point so we can restore it when we're done.
519 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
520 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
521
522 // Move the insertion point out of as many loops as we can.
523 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
524 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
525 BasicBlock *Preheader = L->getLoopPreheader();
526 if (!Preheader) break;
527
528 // Ok, move up a level.
529 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
530 }
531
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000532 // Emit a GEP.
533 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000534 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000535
536 // Restore the original insert point.
537 if (SaveInsertBB)
538 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
539
Dan Gohman5be18e82009-05-19 02:15:55 +0000540 return GEP;
541 }
542
Dan Gohman087bd1e2010-03-03 05:29:13 +0000543 // Save the original insertion point so we can restore it when we're done.
544 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
545 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
546
547 // Move the insertion point out of as many loops as we can.
548 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
549 if (!L->isLoopInvariant(V)) break;
550
551 bool AnyIndexNotLoopInvariant = false;
552 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
553 E = GepIndices.end(); I != E; ++I)
554 if (!L->isLoopInvariant(*I)) {
555 AnyIndexNotLoopInvariant = true;
556 break;
557 }
558 if (AnyIndexNotLoopInvariant)
559 break;
560
561 BasicBlock *Preheader = L->getLoopPreheader();
562 if (!Preheader) break;
563
564 // Ok, move up a level.
565 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
566 }
567
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000568 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
569 // because ScalarEvolution may have changed the address arithmetic to
570 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000571 Value *Casted = V;
572 if (V->getType() != PTy)
573 Casted = InsertNoopCastOfTo(Casted, PTy);
574 Value *GEP = Builder.CreateGEP(Casted,
Dan Gohman267a3852009-06-27 21:18:18 +0000575 GepIndices.begin(),
576 GepIndices.end(),
577 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000578 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000579 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000580
581 // Restore the original insert point.
582 if (SaveInsertBB)
583 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
584
Dan Gohman5be18e82009-05-19 02:15:55 +0000585 return expand(SE.getAddExpr(Ops));
586}
587
Dan Gohmana10756e2010-01-21 02:09:26 +0000588/// isNonConstantNegative - Return true if the specified scev is negated, but
589/// not a constant.
590static bool isNonConstantNegative(const SCEV *F) {
591 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
592 if (!Mul) return false;
593
594 // If there is a constant factor, it will be first.
595 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
596 if (!SC) return false;
597
598 // Return true if the value is negative, this matches things like (-42 * V).
599 return SC->getValue()->getValue().isNegative();
600}
601
Dan Gohman087bd1e2010-03-03 05:29:13 +0000602/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
603/// SCEV expansion. If they are nested, this is the most nested. If they are
604/// neighboring, pick the later.
605static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
606 DominatorTree &DT) {
607 if (!A) return B;
608 if (!B) return A;
609 if (A->contains(B)) return B;
610 if (B->contains(A)) return A;
611 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
612 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
613 return A; // Arbitrarily break the tie.
614}
615
616/// GetRelevantLoop - Get the most relevant loop associated with the given
617/// expression, according to PickMostRelevantLoop.
618static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
619 DominatorTree &DT) {
620 if (isa<SCEVConstant>(S))
621 return 0;
622 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
623 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
624 return LI.getLoopFor(I->getParent());
625 return 0;
626 }
627 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
628 const Loop *L = 0;
629 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
630 L = AR->getLoop();
631 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
632 I != E; ++I)
633 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
634 return L;
635 }
636 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
637 return GetRelevantLoop(C->getOperand(), LI, DT);
638 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
639 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
640 GetRelevantLoop(D->getRHS(), LI, DT),
641 DT);
642 llvm_unreachable("Unexpected SCEV type!");
643}
644
645/// LoopCompare - Compare loops by PickMostRelevantLoop.
646class LoopCompare {
647 DominatorTree &DT;
648public:
649 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
650
651 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
652 std::pair<const Loop *, const SCEV *> RHS) const {
653 // Compare loops with PickMostRelevantLoop.
654 if (LHS.first != RHS.first)
655 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
656
657 // If one operand is a non-constant negative and the other is not,
658 // put the non-constant negative on the right so that a sub can
659 // be used instead of a negate and add.
660 if (isNonConstantNegative(LHS.second)) {
661 if (!isNonConstantNegative(RHS.second))
662 return false;
663 } else if (isNonConstantNegative(RHS.second))
664 return true;
665
666 // Otherwise they are equivalent according to this comparison.
667 return false;
668 }
669};
670
Dan Gohman890f92b2009-04-18 17:56:28 +0000671Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000672 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000673
Dan Gohman087bd1e2010-03-03 05:29:13 +0000674 // Collect all the add operands in a loop, along with their associated loops.
675 // Iterate in reverse so that constants are emitted last, all else equal, and
676 // so that pointer operands are inserted first, which the code below relies on
677 // to form more involved GEPs.
678 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
679 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
680 E(S->op_begin()); I != E; ++I)
681 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
682 *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000683
Dan Gohman087bd1e2010-03-03 05:29:13 +0000684 // Sort by loop. Use a stable sort so that constants follow non-constants and
685 // pointer operands precede non-pointer operands.
686 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000687
Dan Gohman087bd1e2010-03-03 05:29:13 +0000688 // Emit instructions to add all the operands. Hoist as much as possible
689 // out of loops, and form meaningful getelementptrs where possible.
690 Value *Sum = 0;
691 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
692 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
693 const Loop *CurLoop = I->first;
694 const SCEV *Op = I->second;
695 if (!Sum) {
696 // This is the first operand. Just expand it.
697 Sum = expand(Op);
698 ++I;
699 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
700 // The running sum expression is a pointer. Try to form a getelementptr
701 // at this level with that as the base.
702 SmallVector<const SCEV *, 4> NewOps;
703 for (; I != E && I->first == CurLoop; ++I)
704 NewOps.push_back(I->second);
705 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707 // The running sum is an integer, and there's a pointer at this level.
708 // Try to form a getelementptr.
709 SmallVector<const SCEV *, 4> NewOps;
710 NewOps.push_back(SE.getUnknown(Sum));
711 for (++I; I != E && I->first == CurLoop; ++I)
712 NewOps.push_back(I->second);
713 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
714 } else if (isNonConstantNegative(Op)) {
715 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000716 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000717 Sum = InsertNoopCastOfTo(Sum, Ty);
718 Sum = InsertBinop(Instruction::Sub, Sum, W);
719 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000720 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000721 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000722 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000723 Sum = InsertNoopCastOfTo(Sum, Ty);
724 // Canonicalize a constant to the RHS.
725 if (isa<Constant>(Sum)) std::swap(Sum, W);
726 Sum = InsertBinop(Instruction::Add, Sum, W);
727 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000728 }
729 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000730
731 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000732}
Dan Gohman5be18e82009-05-19 02:15:55 +0000733
Dan Gohman890f92b2009-04-18 17:56:28 +0000734Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000735 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000736
Dan Gohman087bd1e2010-03-03 05:29:13 +0000737 // Collect all the mul operands in a loop, along with their associated loops.
738 // Iterate in reverse so that constants are emitted last, all else equal.
739 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
740 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
741 E(S->op_begin()); I != E; ++I)
742 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
743 *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000744
Dan Gohman087bd1e2010-03-03 05:29:13 +0000745 // Sort by loop. Use a stable sort so that constants follow non-constants.
746 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
747
748 // Emit instructions to mul all the operands. Hoist as much as possible
749 // out of loops.
750 Value *Prod = 0;
751 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
752 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
753 const SCEV *Op = I->second;
754 if (!Prod) {
755 // This is the first operand. Just expand it.
756 Prod = expand(Op);
757 ++I;
758 } else if (Op->isAllOnesValue()) {
759 // Instead of doing a multiply by negative one, just do a negate.
760 Prod = InsertNoopCastOfTo(Prod, Ty);
761 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
762 ++I;
763 } else {
764 // A simple mul.
765 Value *W = expandCodeFor(Op, Ty);
766 Prod = InsertNoopCastOfTo(Prod, Ty);
767 // Canonicalize a constant to the RHS.
768 if (isa<Constant>(Prod)) std::swap(Prod, W);
769 Prod = InsertBinop(Instruction::Mul, Prod, W);
770 ++I;
771 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000772 }
773
Dan Gohman087bd1e2010-03-03 05:29:13 +0000774 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000775}
776
Dan Gohman890f92b2009-04-18 17:56:28 +0000777Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000778 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000779
Dan Gohman92fcdca2009-06-09 17:18:38 +0000780 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000781 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000782 const APInt &RHS = SC->getValue()->getValue();
783 if (RHS.isPowerOf2())
784 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000785 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000786 }
787
Dan Gohman92fcdca2009-06-09 17:18:38 +0000788 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000789 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000790}
791
Dan Gohman453aa4f2009-05-24 18:06:31 +0000792/// Move parts of Base into Rest to leave Base with the minimal
793/// expression that provides a pointer operand suitable for a
794/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000795static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000796 ScalarEvolution &SE) {
797 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
798 Base = A->getStart();
799 Rest = SE.getAddExpr(Rest,
800 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
801 A->getStepRecurrence(SE),
802 A->getLoop()));
803 }
804 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
805 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000806 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000807 NewAddOps.back() = Rest;
808 Rest = SE.getAddExpr(NewAddOps);
809 ExposePointerBase(Base, Rest, SE);
810 }
811}
812
Dan Gohmana10756e2010-01-21 02:09:26 +0000813/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
814/// the base addrec, which is the addrec without any non-loop-dominating
815/// values, and return the PHI.
816PHINode *
817SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
818 const Loop *L,
819 const Type *ExpandTy,
820 const Type *IntTy) {
821 // Reuse a previously-inserted PHI, if present.
822 for (BasicBlock::iterator I = L->getHeader()->begin();
823 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohman572645c2010-02-12 10:34:29 +0000824 if (SE.isSCEVable(PN->getType()) &&
825 (SE.getEffectiveSCEVType(PN->getType()) ==
826 SE.getEffectiveSCEVType(Normalized->getType())) &&
827 SE.getSCEV(PN) == Normalized)
828 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Dan Gohman572645c2010-02-12 10:34:29 +0000829 Instruction *IncV =
Dan Gohman22e62192010-02-16 00:20:08 +0000830 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
831
832 // Determine if this is a well-behaved chain of instructions leading
833 // back to the PHI. It probably will be, if we're scanning an inner
834 // loop already visited by LSR for example, but it wouldn't have
835 // to be.
836 do {
837 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
838 IncV = 0;
839 break;
840 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000841 // If any of the operands don't dominate the insert position, bail.
842 // Addrec operands are always loop-invariant, so this can only happen
843 // if there are instructions which haven't been hoisted.
844 for (User::op_iterator OI = IncV->op_begin()+1,
845 OE = IncV->op_end(); OI != OE; ++OI)
846 if (Instruction *OInst = dyn_cast<Instruction>(OI))
847 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
848 IncV = 0;
849 break;
850 }
851 if (!IncV)
852 break;
853 // Advance to the next instruction.
Dan Gohman22e62192010-02-16 00:20:08 +0000854 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
855 if (!IncV)
856 break;
857 if (IncV->mayHaveSideEffects()) {
858 IncV = 0;
859 break;
860 }
861 } while (IncV != PN);
862
863 if (IncV) {
864 // Ok, the add recurrence looks usable.
865 // Remember this PHI, even in post-inc mode.
866 InsertedValues.insert(PN);
867 // Remember the increment.
868 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
869 rememberInstruction(IncV);
870 if (L == IVIncInsertLoop)
871 do {
872 if (SE.DT->dominates(IncV, IVIncInsertPos))
873 break;
874 // Make sure the increment is where we want it. But don't move it
875 // down past a potential existing post-inc user.
876 IncV->moveBefore(IVIncInsertPos);
877 IVIncInsertPos = IncV;
878 IncV = cast<Instruction>(IncV->getOperand(0));
879 } while (IncV != PN);
880 return PN;
881 }
Dan Gohman572645c2010-02-12 10:34:29 +0000882 }
Dan Gohmana10756e2010-01-21 02:09:26 +0000883
884 // Save the original insertion point so we can restore it when we're done.
885 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
886 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
887
888 // Expand code for the start value.
889 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
890 L->getHeader()->begin());
891
892 // Expand code for the step value. Insert instructions right before the
893 // terminator corresponding to the back-edge. Do this before creating the PHI
894 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
895 // negative, insert a sub instead of an add for the increment (unless it's a
896 // constant, because subtracts of constants are canonicalized to adds).
897 const SCEV *Step = Normalized->getStepRecurrence(SE);
Duncan Sands1df98592010-02-16 11:11:14 +0000898 bool isPointer = ExpandTy->isPointerTy();
Dan Gohmana10756e2010-01-21 02:09:26 +0000899 bool isNegative = !isPointer && isNonConstantNegative(Step);
900 if (isNegative)
901 Step = SE.getNegativeSCEV(Step);
902 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
903
904 // Create the PHI.
905 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
906 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
907 rememberInstruction(PN);
908
909 // Create the step instructions and populate the PHI.
910 BasicBlock *Header = L->getHeader();
911 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
912 HPI != HPE; ++HPI) {
913 BasicBlock *Pred = *HPI;
914
915 // Add a start value.
916 if (!L->contains(Pred)) {
917 PN->addIncoming(StartV, Pred);
918 continue;
919 }
920
921 // Create a step value and add it to the PHI. If IVIncInsertLoop is
922 // non-null and equal to the addrec's loop, insert the instructions
923 // at IVIncInsertPos.
924 Instruction *InsertPos = L == IVIncInsertLoop ?
925 IVIncInsertPos : Pred->getTerminator();
926 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
927 Value *IncV;
928 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
929 if (isPointer) {
930 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
931 // If the step isn't constant, don't use an implicitly scaled GEP, because
932 // that would require a multiply inside the loop.
933 if (!isa<ConstantInt>(StepV))
934 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
935 GEPPtrTy->getAddressSpace());
936 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
937 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
938 if (IncV->getType() != PN->getType()) {
939 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
940 rememberInstruction(IncV);
941 }
942 } else {
943 IncV = isNegative ?
944 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
945 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
946 rememberInstruction(IncV);
947 }
948 PN->addIncoming(IncV, Pred);
949 }
950
951 // Restore the original insert point.
952 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +0000953 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +0000954
955 // Remember this PHI, even in post-inc mode.
956 InsertedValues.insert(PN);
957
958 return PN;
959}
960
961Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
962 const Type *STy = S->getType();
963 const Type *IntTy = SE.getEffectiveSCEVType(STy);
964 const Loop *L = S->getLoop();
965
966 // Determine a normalized form of this expression, which is the expression
967 // before any post-inc adjustment is made.
968 const SCEVAddRecExpr *Normalized = S;
969 if (L == PostIncLoop) {
970 const SCEV *Step = S->getStepRecurrence(SE);
971 Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
972 }
973
974 // Strip off any non-loop-dominating component from the addrec start.
975 const SCEV *Start = Normalized->getStart();
976 const SCEV *PostLoopOffset = 0;
977 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
978 PostLoopOffset = Start;
979 Start = SE.getIntegerSCEV(0, Normalized->getType());
980 Normalized =
981 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
982 Normalized->getStepRecurrence(SE),
983 Normalized->getLoop()));
984 }
985
986 // Strip off any non-loop-dominating component from the addrec step.
987 const SCEV *Step = Normalized->getStepRecurrence(SE);
988 const SCEV *PostLoopScale = 0;
989 if (!Step->hasComputableLoopEvolution(L) &&
990 !Step->dominates(L->getHeader(), SE.DT)) {
991 PostLoopScale = Step;
992 Step = SE.getIntegerSCEV(1, Normalized->getType());
993 Normalized =
994 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
995 Normalized->getLoop()));
996 }
997
998 // Expand the core addrec. If we need post-loop scaling, force it to
999 // expand to an integer type to avoid the need for additional casting.
1000 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1001 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1002
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001003 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001004 Value *Result;
1005 if (L != PostIncLoop)
1006 Result = PN;
1007 else {
1008 // In PostInc mode, use the post-incremented value.
1009 BasicBlock *LatchBlock = L->getLoopLatch();
1010 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1011 Result = PN->getIncomingValueForBlock(LatchBlock);
1012 }
1013
1014 // Re-apply any non-loop-dominating scale.
1015 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001016 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001017 Result = Builder.CreateMul(Result,
1018 expandCodeFor(PostLoopScale, IntTy));
1019 rememberInstruction(Result);
1020 }
1021
1022 // Re-apply any non-loop-dominating offset.
1023 if (PostLoopOffset) {
1024 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1025 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1026 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1027 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001028 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001029 Result = Builder.CreateAdd(Result,
1030 expandCodeFor(PostLoopOffset, IntTy));
1031 rememberInstruction(Result);
1032 }
1033 }
1034
1035 return Result;
1036}
1037
Dan Gohman890f92b2009-04-18 17:56:28 +00001038Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001039 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1040
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001041 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001042 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001043
Dan Gohman4d8414f2009-06-13 16:25:49 +00001044 // First check for an existing canonical IV in a suitable type.
1045 PHINode *CanonicalIV = 0;
1046 if (PHINode *PN = L->getCanonicalInductionVariable())
1047 if (SE.isSCEVable(PN->getType()) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001048 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
Dan Gohman4d8414f2009-06-13 16:25:49 +00001049 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1050 CanonicalIV = PN;
1051
1052 // Rewrite an AddRec in terms of the canonical induction variable, if
1053 // its type is more narrow.
1054 if (CanonicalIV &&
1055 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1056 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001057 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1058 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1059 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Dan Gohmanf3f1be62009-09-28 21:01:47 +00001060 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +00001061 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1062 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001063 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001064 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Dan Gohman4d8414f2009-06-13 16:25:49 +00001065 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
1066 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1067 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001068 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001069 return V;
1070 }
1071
Nate Begeman36f891b2005-07-30 00:12:19 +00001072 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001073 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001074 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001075 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001076 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001077
1078 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1079 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001080 const SCEV *Base = S->getStart();
1081 const SCEV *RestArray[1] = { Rest };
1082 // Dig into the expression to find the pointer base for a GEP.
1083 ExposePointerBase(Base, RestArray[0], SE);
1084 // If we found a pointer, expand the AddRec with a GEP.
1085 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1086 // Make sure the Base isn't something exotic, such as a multiplied
1087 // or divided pointer value. In those cases, the result type isn't
1088 // actually a pointer type.
1089 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1090 Value *StartV = expand(Base);
1091 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1092 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001093 }
1094 }
1095
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001096 // Just do a normal add. Pre-expand the operands to suppress folding.
1097 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1098 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001099 }
1100
1101 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +00001102 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +00001103 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001104 // If there's a canonical IV, just use it.
1105 if (CanonicalIV) {
1106 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1107 "IVs with types different from the canonical IV should "
1108 "already have been handled!");
1109 return CanonicalIV;
1110 }
1111
Nate Begeman36f891b2005-07-30 00:12:19 +00001112 // Create and insert the PHI node for the induction variable in the
1113 // specified loop.
1114 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +00001115 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmana10756e2010-01-21 02:09:26 +00001116 rememberInstruction(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +00001117
Owen Andersoneed707b2009-07-24 23:12:02 +00001118 Constant *One = ConstantInt::get(Ty, 1);
Dan Gohman83d57742009-09-27 17:46:40 +00001119 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1120 HPI != HPE; ++HPI)
1121 if (L->contains(*HPI)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001122 // Insert a unit add instruction right before the terminator
1123 // corresponding to the back-edge.
Dan Gohman83d57742009-09-27 17:46:40 +00001124 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1125 (*HPI)->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +00001126 rememberInstruction(Add);
Dan Gohman83d57742009-09-27 17:46:40 +00001127 PN->addIncoming(Add, *HPI);
1128 } else {
1129 PN->addIncoming(Constant::getNullValue(Ty), *HPI);
1130 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001131 }
1132
Dan Gohman4d8414f2009-06-13 16:25:49 +00001133 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001134 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +00001135 Value *I = CanonicalIV ?
1136 CanonicalIV :
1137 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +00001138
Chris Lattnerdf14a042005-10-30 06:24:33 +00001139 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001140 if (S->isAffine()) // {0,+,F} --> i*F
1141 return
1142 expand(SE.getTruncateOrNoop(
1143 SE.getMulExpr(SE.getUnknown(I),
1144 SE.getNoopOrAnyExtend(S->getOperand(1),
1145 I->getType())),
1146 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001147
1148 // If this is a chain of recurrences, turn it into a closed form, using the
1149 // folders, then expandCodeFor the closed form. This allows the folders to
1150 // simplify the expression without having to build a bunch of special code
1151 // into this folder.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001152 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001153
Dan Gohman4d8414f2009-06-13 16:25:49 +00001154 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001155 const SCEV *NewS = S;
1156 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001157 if (isa<SCEVAddRecExpr>(Ext))
1158 NewS = Ext;
1159
Dan Gohman0bba49c2009-07-07 17:06:11 +00001160 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001161 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001162
Dan Gohman4d8414f2009-06-13 16:25:49 +00001163 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001164 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001165 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001166}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001167
Dan Gohman890f92b2009-04-18 17:56:28 +00001168Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001169 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001170 Value *V = expandCodeFor(S->getOperand(),
1171 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001172 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001173 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001174 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001175}
1176
Dan Gohman890f92b2009-04-18 17:56:28 +00001177Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001178 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001179 Value *V = expandCodeFor(S->getOperand(),
1180 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001181 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001182 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001183 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001184}
1185
Dan Gohman890f92b2009-04-18 17:56:28 +00001186Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001187 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001188 Value *V = expandCodeFor(S->getOperand(),
1189 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001190 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001191 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001192 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001193}
1194
Dan Gohman890f92b2009-04-18 17:56:28 +00001195Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001196 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1197 const Type *Ty = LHS->getType();
1198 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1199 // In the case of mixed integer and pointer types, do the
1200 // rest of the comparisons as integer.
1201 if (S->getOperand(i)->getType() != Ty) {
1202 Ty = SE.getEffectiveSCEVType(Ty);
1203 LHS = InsertNoopCastOfTo(LHS, Ty);
1204 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001205 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001206 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001207 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001208 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001209 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001210 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001211 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001212 // In the case of mixed integer and pointer types, cast the
1213 // final result back to the pointer type.
1214 if (LHS->getType() != S->getType())
1215 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001216 return LHS;
1217}
1218
Dan Gohman890f92b2009-04-18 17:56:28 +00001219Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001220 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1221 const Type *Ty = LHS->getType();
1222 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1223 // In the case of mixed integer and pointer types, do the
1224 // rest of the comparisons as integer.
1225 if (S->getOperand(i)->getType() != Ty) {
1226 Ty = SE.getEffectiveSCEVType(Ty);
1227 LHS = InsertNoopCastOfTo(LHS, Ty);
1228 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001229 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001230 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001231 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001232 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001233 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001234 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001235 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001236 // In the case of mixed integer and pointer types, cast the
1237 // final result back to the pointer type.
1238 if (LHS->getType() != S->getType())
1239 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001240 return LHS;
1241}
1242
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001243Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1244 Instruction *I) {
1245 BasicBlock::iterator IP = I;
1246 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1247 ++IP;
1248 Builder.SetInsertPoint(IP->getParent(), IP);
1249 return expandCodeFor(SH, Ty);
1250}
1251
Dan Gohman0bba49c2009-07-07 17:06:11 +00001252Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001253 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001254 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001255 if (Ty) {
1256 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1257 "non-trivial casts should be done with the SCEVs directly!");
1258 V = InsertNoopCastOfTo(V, Ty);
1259 }
1260 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001261}
1262
Dan Gohman890f92b2009-04-18 17:56:28 +00001263Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001264 // Compute an insertion point for this SCEV object. Hoist the instructions
1265 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001266 Instruction *InsertPt = Builder.GetInsertPoint();
1267 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001268 L = L->getParentLoop())
1269 if (S->isLoopInvariant(L)) {
1270 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001271 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001272 InsertPt = Preheader->getTerminator();
1273 } else {
1274 // If the SCEV is computable at this level, insert it into the header
1275 // after the PHIs (and after any other instructions that we've inserted
1276 // there) so that it is guaranteed to dominate any user inside the loop.
Dan Gohman069d6f32010-03-02 01:59:21 +00001277 if (L && S->hasComputableLoopEvolution(L) && L != PostIncLoop)
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001278 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001279 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001280 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001281 break;
1282 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001283
Dan Gohman667d7872009-06-26 22:53:46 +00001284 // Check to see if we already expanded this here.
1285 std::map<std::pair<const SCEV *, Instruction *>,
1286 AssertingVH<Value> >::iterator I =
1287 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001288 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001289 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001290
1291 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1292 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1293 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001294
1295 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001296 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001297
Dan Gohman667d7872009-06-26 22:53:46 +00001298 // Remember the expanded value for this SCEV at this location.
Dan Gohmana10756e2010-01-21 02:09:26 +00001299 if (!PostIncLoop)
1300 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001301
Dan Gohman45598552010-02-15 00:21:43 +00001302 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001303 return V;
1304}
Dan Gohman1d09de32009-06-05 16:35:53 +00001305
Dan Gohman1d826a72010-02-14 03:12:47 +00001306void SCEVExpander::rememberInstruction(Value *I) {
1307 if (!PostIncLoop)
1308 InsertedValues.insert(I);
1309
1310 // If we just claimed an existing instruction and that instruction had
1311 // been the insert point, adjust the insert point forward so that
1312 // subsequently inserted code will be dominated.
1313 if (Builder.GetInsertPoint() == I) {
1314 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001315 do { ++It; } while (isInsertedInstruction(It) ||
1316 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001317 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1318 }
1319}
1320
Dan Gohman45598552010-02-15 00:21:43 +00001321void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001322 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001323 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001324 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001325
1326 Builder.SetInsertPoint(BB, I);
1327}
1328
Dan Gohman1d09de32009-06-05 16:35:53 +00001329/// getOrInsertCanonicalInductionVariable - This method returns the
1330/// canonical induction variable of the specified type for the specified
1331/// loop (inserting one if there is none). A canonical induction variable
1332/// starts at zero and steps by one on each iteration.
1333Value *
1334SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1335 const Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001336 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman0bba49c2009-07-07 17:06:11 +00001337 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001338 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +00001339 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1340 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001341 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +00001342 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001343 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001344 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001345}