blob: 8dc8eb68ff4d84711b5392e28d31a826cbb84cdb [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"
Andrew Trickc5701912011-10-07 23:46:21 +000020#include "llvm/Support/Debug.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000021#include "llvm/Target/TargetData.h"
Andrew Trickee98aa82012-01-07 01:12:09 +000022#include "llvm/Target/TargetLowering.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000023#include "llvm/ADT/STLExtras.h"
Andrew Trickd152d032011-07-16 00:59:39 +000024
Nate Begeman36f891b2005-07-30 00:12:19 +000025using namespace llvm;
26
Gabor Greif19e5ada2010-07-09 16:42:04 +000027/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000028/// reusing an existing cast if a suitable one exists, moving an existing
29/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000030/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000031Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000032 Instruction::CastOps Op,
33 BasicBlock::iterator IP) {
34 // Check to see if there is already a cast!
35 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000036 UI != E; ++UI) {
37 User *U = *UI;
38 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000039 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000040 if (CI->getOpcode() == Op) {
41 // If the cast isn't where we want it, fix it.
42 if (BasicBlock::iterator(CI) != IP) {
43 // Create a new cast, and leave the old cast in place in case
44 // it is being used as an insert point. Clear its operand
45 // so that it doesn't hold anything live.
46 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
47 NewCI->takeName(CI);
48 CI->replaceAllUsesWith(NewCI);
49 CI->setOperand(0, UndefValue::get(V->getType()));
50 rememberInstruction(NewCI);
51 return NewCI;
52 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000053 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000054 return CI;
55 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000056 }
Dan Gohman485c43f2010-06-19 13:25:23 +000057
58 // Create a new cast.
59 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
60 rememberInstruction(I);
61 return I;
62}
63
Dan Gohman267a3852009-06-27 21:18:18 +000064/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
65/// which must be possible with a noop cast, doing what we can to share
66/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000067Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000068 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
69 assert((Op == Instruction::BitCast ||
70 Op == Instruction::PtrToInt ||
71 Op == Instruction::IntToPtr) &&
72 "InsertNoopCastOfTo cannot perform non-noop casts!");
73 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
74 "InsertNoopCastOfTo cannot change sizes!");
75
Dan Gohman2d1be872009-04-16 03:18:22 +000076 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-12-14 22:07:19 +000077 if (Op == Instruction::BitCast) {
78 if (V->getType() == Ty)
79 return V;
80 if (CastInst *CI = dyn_cast<CastInst>(V)) {
81 if (CI->getOperand(0)->getType() == Ty)
82 return CI->getOperand(0);
83 }
84 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000085 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000086 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000087 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000088 if (CastInst *CI = dyn_cast<CastInst>(V))
89 if ((CI->getOpcode() == Instruction::PtrToInt ||
90 CI->getOpcode() == Instruction::IntToPtr) &&
91 SE.getTypeSizeInBits(CI->getType()) ==
92 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
93 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000094 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
95 if ((CE->getOpcode() == Instruction::PtrToInt ||
96 CE->getOpcode() == Instruction::IntToPtr) &&
97 SE.getTypeSizeInBits(CE->getType()) ==
98 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
99 return CE->getOperand(0);
100 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000101
Dan Gohman485c43f2010-06-19 13:25:23 +0000102 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000103 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000104 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000105
Dan Gohman485c43f2010-06-19 13:25:23 +0000106 // Cast the argument at the beginning of the entry block, after
107 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000108 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000109 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
110 while ((isa<BitCastInst>(IP) &&
111 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
112 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000113 isa<DbgInfoIntrinsic>(IP) ||
114 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000115 ++IP;
116 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000117 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000118
Dan Gohman485c43f2010-06-19 13:25:23 +0000119 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000120 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000121 BasicBlock::iterator IP = I; ++IP;
122 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
123 IP = II->getNormalDest()->begin();
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000124 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
125 isa<LandingPadInst>(IP))
126 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000127 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000128}
129
Chris Lattner7fec90e2007-04-13 05:04:18 +0000130/// InsertBinop - Insert the specified binary operator, doing a small amount
131/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000132Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
133 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000134 // Fold a binop with constant operands.
135 if (Constant *CLHS = dyn_cast<Constant>(LHS))
136 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000137 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000138
Chris Lattner7fec90e2007-04-13 05:04:18 +0000139 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
140 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000141 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
142 // Scanning starts from the last instruction before the insertion point.
143 BasicBlock::iterator IP = Builder.GetInsertPoint();
144 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000145 --IP;
146 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000147 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
148 // generated code.
149 if (isa<DbgInfoIntrinsic>(IP))
150 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000151 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
152 IP->getOperand(1) == RHS)
153 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000154 if (IP == BlockBegin) break;
155 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000156 }
Dan Gohman267a3852009-06-27 21:18:18 +0000157
Dan Gohman087bd1e2010-03-03 05:29:13 +0000158 // Save the original insertion point so we can restore it when we're done.
159 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
160 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
161
162 // Move the insertion point out of as many loops as we can.
163 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
164 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
165 BasicBlock *Preheader = L->getLoopPreheader();
166 if (!Preheader) break;
167
168 // Ok, move up a level.
169 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
170 }
171
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000172 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000173 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000174 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000175 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000176
177 // Restore the original insert point.
178 if (SaveInsertBB)
179 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
180
Dan Gohmancf5ab822009-05-01 17:13:31 +0000181 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000182}
183
Dan Gohman4a4f7672009-05-27 02:00:53 +0000184/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000185/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000186/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000187/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000188/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
189/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
190/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000191static bool FactorOutConstant(const SCEV *&S,
192 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000193 const SCEV *Factor,
194 ScalarEvolution &SE,
195 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000196 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000197 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000198 return true;
199
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000200 // x/x == 1.
201 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000202 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000203 return true;
204 }
205
Dan Gohman453aa4f2009-05-24 18:06:31 +0000206 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000207 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000208 // 0/x == 0.
209 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000210 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000211 // Check for divisibility.
212 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
213 ConstantInt *CI =
214 ConstantInt::get(SE.getContext(),
215 C->getValue()->getValue().sdiv(
216 FC->getValue()->getValue()));
217 // If the quotient is zero and the remainder is non-zero, reject
218 // the value at this scale. It will be considered for subsequent
219 // smaller scales.
220 if (!CI->isZero()) {
221 const SCEV *Div = SE.getConstant(CI);
222 S = Div;
223 Remainder =
224 SE.getAddExpr(Remainder,
225 SE.getConstant(C->getValue()->getValue().srem(
226 FC->getValue()->getValue())));
227 return true;
228 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000229 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000230 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000231
232 // In a Mul, check if there is a constant operand which is a multiple
233 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000234 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
235 if (TD) {
236 // With TargetData, the size is known. Check if there is a constant
237 // operand which is a multiple of the given factor. If so, we can
238 // factor it.
239 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
240 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
241 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000242 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000243 NewMulOps[0] =
244 SE.getConstant(C->getValue()->getValue().sdiv(
245 FC->getValue()->getValue()));
246 S = SE.getMulExpr(NewMulOps);
247 return true;
248 }
249 } else {
250 // Without TargetData, check if Factor can be factored out of any of the
251 // Mul's operands. If so, we can just remove it.
252 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
253 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000254 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000255 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
256 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000257 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000258 NewMulOps[i] = SOp;
259 S = SE.getMulExpr(NewMulOps);
260 return true;
261 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000262 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 }
264 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000265
266 // In an AddRec, check if both start and step are divisible.
267 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000268 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000269 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000270 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000271 return false;
272 if (!StepRem->isZero())
273 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000274 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000275 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000276 return false;
Andrew Trick3228cc22011-03-14 16:50:06 +0000277 // FIXME: can use A->getNoWrapFlags(FlagNW)
278 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000279 return true;
280 }
281
282 return false;
283}
284
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000285/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
286/// is the number of SCEVAddRecExprs present, which are kept at the end of
287/// the list.
288///
289static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000290 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000291 ScalarEvolution &SE) {
292 unsigned NumAddRecs = 0;
293 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
294 ++NumAddRecs;
295 // Group Ops into non-addrecs and addrecs.
296 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
297 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
298 // Let ScalarEvolution sort and simplify the non-addrecs list.
299 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000300 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000301 SE.getAddExpr(NoAddRecs);
302 // If it returned an add, use the operands. Otherwise it simplified
303 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000304 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000305 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000306 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000307 else if (!Sum->isZero())
308 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000309 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000310 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000311}
312
313/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
314/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
315/// This helps expose more opportunities for folding parts of the expressions
316/// into GEP indices.
317///
318static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000319 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000320 ScalarEvolution &SE) {
321 // Find the addrecs.
322 SmallVector<const SCEV *, 8> AddRecs;
323 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
324 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
325 const SCEV *Start = A->getStart();
326 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000327 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000328 AddRecs.push_back(SE.getAddRecExpr(Zero,
329 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000330 A->getLoop(),
331 // FIXME: A->getNoWrapFlags(FlagNW)
332 SCEV::FlagAnyWrap));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000333 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
334 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000335 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000336 e += Add->getNumOperands();
337 } else {
338 Ops[i] = Start;
339 }
340 }
341 if (!AddRecs.empty()) {
342 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000343 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000344 // Resort the operand list, moving any constants to the front.
345 SimplifyAddOperands(Ops, Ty, SE);
346 }
347}
348
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000349/// expandAddToGEP - Expand an addition expression with a pointer type into
350/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
351/// BasicAliasAnalysis and other passes analyze the result. See the rules
352/// for getelementptr vs. inttoptr in
353/// http://llvm.org/docs/LangRef.html#pointeraliasing
354/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000355///
Dan Gohman3abf9052010-01-19 22:26:02 +0000356/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000357/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
358/// they may introduce pointer arithmetic which may not be safely converted
359/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000360///
361/// Design note: It might seem desirable for this function to be more
362/// loop-aware. If some of the indices are loop-invariant while others
363/// aren't, it might seem desirable to emit multiple GEPs, keeping the
364/// loop-invariant portions of the overall computation outside the loop.
365/// However, there are a few reasons this is not done here. Hoisting simple
366/// arithmetic is a low-level optimization that often isn't very
367/// important until late in the optimization process. In fact, passes
368/// like InstructionCombining will combine GEPs, even if it means
369/// pushing loop-invariant computation down into loops, so even if the
370/// GEPs were split here, the work would quickly be undone. The
371/// LoopStrengthReduction pass, which is usually run quite late (and
372/// after the last InstructionCombining pass), takes care of hoisting
373/// loop-invariant portions of expressions, after considering what
374/// can be folded using target addressing modes.
375///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000376Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
377 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000378 PointerType *PTy,
379 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000380 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000381 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000382 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000383 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000384 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000385
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000386 // Split AddRecs up into parts as either of the parts may be usable
387 // without the other.
388 SplitAddRecs(Ops, Ty, SE);
389
Bob Wilsoneb356992009-12-04 01:33:04 +0000390 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000391 // operands into GEP indices, at each level. The first index in a GEP
392 // indexes into the array implied by the pointer operand; the rest of
393 // the indices index into the element or field type selected by the
394 // preceding index.
395 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000396 // If the scale size is not 0, attempt to factor out a scale for
397 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000398 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000399 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000400 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000401 if (!ElSize->isZero()) {
402 SmallVector<const SCEV *, 8> NewOps;
403 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
404 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000405 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000406 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
407 // Op now has ElSize factored out.
408 ScaledOps.push_back(Op);
409 if (!Remainder->isZero())
410 NewOps.push_back(Remainder);
411 AnyNonZeroIndices = true;
412 } else {
413 // The operand was not divisible, so add it to the list of operands
414 // we'll scan next iteration.
415 NewOps.push_back(Ops[i]);
416 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000417 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000418 // If we made any changes, update Ops.
419 if (!ScaledOps.empty()) {
420 Ops = NewOps;
421 SimplifyAddOperands(Ops, Ty, SE);
422 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000423 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000424 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000425
426 // Record the scaled array index for this level of the type. If
427 // we didn't find any operands that could be factored, tentatively
428 // assume that element zero was selected (since the zero offset
429 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000430 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000431 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000432 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
433 GepIndices.push_back(Scaled);
434
435 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000436 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000437 bool FoundFieldNo = false;
438 // An empty struct has no fields.
439 if (STy->getNumElements() == 0) break;
440 if (SE.TD) {
441 // With TargetData, field offsets are known. See if a constant offset
442 // falls within any of the struct fields.
443 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000444 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
445 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
446 const StructLayout &SL = *SE.TD->getStructLayout(STy);
447 uint64_t FullOffset = C->getValue()->getZExtValue();
448 if (FullOffset < SL.getSizeInBytes()) {
449 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000450 GepIndices.push_back(
451 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000452 ElTy = STy->getTypeAtIndex(ElIdx);
453 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000454 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000455 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000456 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000457 }
458 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000459 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000460 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 // appropriate struct type.
462 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000463 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000464 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000465 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000466 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000467 GepIndices.push_back(FieldNo);
468 ElTy =
469 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000470 Ops[i] = SE.getConstant(Ty, 0);
471 AnyNonZeroIndices = true;
472 FoundFieldNo = true;
473 break;
474 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000475 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000477 // If no struct field offsets were found, tentatively assume that
478 // field zero was selected (since the zero offset would obviously
479 // be folded away).
480 if (!FoundFieldNo) {
481 ElTy = STy->getTypeAtIndex(0u);
482 GepIndices.push_back(
483 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
484 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000485 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000486
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000487 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000488 ElTy = ATy->getElementType();
489 else
490 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000491 }
492
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000493 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000494 // the base to i8* and do an ugly getelementptr with that. It's still
495 // better than ptrtoint+arithmetic+inttoptr at least.
496 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000497 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000498 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000499 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000500
501 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000502 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000503
504 // Fold a GEP with constant operands.
505 if (Constant *CLHS = dyn_cast<Constant>(V))
506 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000507 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000508
509 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
510 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000511 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
512 // Scanning starts from the last instruction before the insertion point.
513 BasicBlock::iterator IP = Builder.GetInsertPoint();
514 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000515 --IP;
516 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000517 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
518 // generated code.
519 if (isa<DbgInfoIntrinsic>(IP))
520 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000521 if (IP->getOpcode() == Instruction::GetElementPtr &&
522 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
523 return IP;
524 if (IP == BlockBegin) break;
525 }
526 }
527
Dan Gohman087bd1e2010-03-03 05:29:13 +0000528 // Save the original insertion point so we can restore it when we're done.
529 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
530 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
531
532 // Move the insertion point out of as many loops as we can.
533 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
534 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
535 BasicBlock *Preheader = L->getLoopPreheader();
536 if (!Preheader) break;
537
538 // Ok, move up a level.
539 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
540 }
541
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000542 // Emit a GEP.
543 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000544 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000545
546 // Restore the original insert point.
547 if (SaveInsertBB)
548 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
549
Dan Gohman5be18e82009-05-19 02:15:55 +0000550 return GEP;
551 }
552
Dan Gohman087bd1e2010-03-03 05:29:13 +0000553 // Save the original insertion point so we can restore it when we're done.
554 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
555 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
556
557 // Move the insertion point out of as many loops as we can.
558 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
559 if (!L->isLoopInvariant(V)) break;
560
561 bool AnyIndexNotLoopInvariant = false;
562 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
563 E = GepIndices.end(); I != E; ++I)
564 if (!L->isLoopInvariant(*I)) {
565 AnyIndexNotLoopInvariant = true;
566 break;
567 }
568 if (AnyIndexNotLoopInvariant)
569 break;
570
571 BasicBlock *Preheader = L->getLoopPreheader();
572 if (!Preheader) break;
573
574 // Ok, move up a level.
575 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
576 }
577
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000578 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
579 // because ScalarEvolution may have changed the address arithmetic to
580 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000581 Value *Casted = V;
582 if (V->getType() != PTy)
583 Casted = InsertNoopCastOfTo(Casted, PTy);
584 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000585 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000586 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000587 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000588 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000589
590 // Restore the original insert point.
591 if (SaveInsertBB)
592 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
593
Dan Gohman5be18e82009-05-19 02:15:55 +0000594 return expand(SE.getAddExpr(Ops));
595}
596
Dan Gohman087bd1e2010-03-03 05:29:13 +0000597/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
598/// SCEV expansion. If they are nested, this is the most nested. If they are
599/// neighboring, pick the later.
600static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
601 DominatorTree &DT) {
602 if (!A) return B;
603 if (!B) return A;
604 if (A->contains(B)) return B;
605 if (B->contains(A)) return A;
606 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
607 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
608 return A; // Arbitrarily break the tie.
609}
610
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000611/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000612/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000613const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
614 // Test whether we've already computed the most relevant loop for this SCEV.
615 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
616 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
617 if (!Pair.second)
618 return Pair.first->second;
619
Dan Gohman087bd1e2010-03-03 05:29:13 +0000620 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000621 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000622 return 0;
623 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
624 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000625 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
626 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000627 return 0;
628 }
629 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
630 const Loop *L = 0;
631 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
632 L = AR->getLoop();
633 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
634 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000635 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
636 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000637 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000638 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
639 const Loop *Result = getRelevantLoop(C->getOperand());
640 return RelevantLoops[C] = Result;
641 }
642 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
643 const Loop *Result =
644 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
645 getRelevantLoop(D->getRHS()),
646 *SE.DT);
647 return RelevantLoops[D] = Result;
648 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000649 llvm_unreachable("Unexpected SCEV type!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000650 return 0;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000651}
652
Dan Gohmanb3579832010-04-15 17:08:50 +0000653namespace {
654
Dan Gohman087bd1e2010-03-03 05:29:13 +0000655/// LoopCompare - Compare loops by PickMostRelevantLoop.
656class LoopCompare {
657 DominatorTree &DT;
658public:
659 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
660
661 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
662 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000663 // Keep pointer operands sorted at the end.
664 if (LHS.second->getType()->isPointerTy() !=
665 RHS.second->getType()->isPointerTy())
666 return LHS.second->getType()->isPointerTy();
667
Dan Gohman087bd1e2010-03-03 05:29:13 +0000668 // Compare loops with PickMostRelevantLoop.
669 if (LHS.first != RHS.first)
670 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
671
672 // If one operand is a non-constant negative and the other is not,
673 // put the non-constant negative on the right so that a sub can
674 // be used instead of a negate and add.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000675 if (LHS.second->isNonConstantNegative()) {
676 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000677 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000678 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000679 return true;
680
681 // Otherwise they are equivalent according to this comparison.
682 return false;
683 }
684};
685
Dan Gohmanb3579832010-04-15 17:08:50 +0000686}
687
Dan Gohman890f92b2009-04-18 17:56:28 +0000688Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000689 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000690
Dan Gohman087bd1e2010-03-03 05:29:13 +0000691 // Collect all the add operands in a loop, along with their associated loops.
692 // Iterate in reverse so that constants are emitted last, all else equal, and
693 // so that pointer operands are inserted first, which the code below relies on
694 // to form more involved GEPs.
695 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
696 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
697 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000698 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000699
Dan Gohman087bd1e2010-03-03 05:29:13 +0000700 // Sort by loop. Use a stable sort so that constants follow non-constants and
701 // pointer operands precede non-pointer operands.
702 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000703
Dan Gohman087bd1e2010-03-03 05:29:13 +0000704 // Emit instructions to add all the operands. Hoist as much as possible
705 // out of loops, and form meaningful getelementptrs where possible.
706 Value *Sum = 0;
707 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
708 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
709 const Loop *CurLoop = I->first;
710 const SCEV *Op = I->second;
711 if (!Sum) {
712 // This is the first operand. Just expand it.
713 Sum = expand(Op);
714 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000715 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000716 // The running sum expression is a pointer. Try to form a getelementptr
717 // at this level with that as the base.
718 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000719 for (; I != E && I->first == CurLoop; ++I) {
720 // If the operand is SCEVUnknown and not instructions, peek through
721 // it, to enable more of it to be folded into the GEP.
722 const SCEV *X = I->second;
723 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
724 if (!isa<Instruction>(U->getValue()))
725 X = SE.getSCEV(U->getValue());
726 NewOps.push_back(X);
727 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000728 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000729 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000730 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000731 // Try to form a getelementptr. If the running sum is instructions,
732 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000733 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000734 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
735 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000736 for (++I; I != E && I->first == CurLoop; ++I)
737 NewOps.push_back(I->second);
738 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000739 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000740 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000741 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000742 Sum = InsertNoopCastOfTo(Sum, Ty);
743 Sum = InsertBinop(Instruction::Sub, Sum, W);
744 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000745 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000746 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000747 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000748 Sum = InsertNoopCastOfTo(Sum, Ty);
749 // Canonicalize a constant to the RHS.
750 if (isa<Constant>(Sum)) std::swap(Sum, W);
751 Sum = InsertBinop(Instruction::Add, Sum, W);
752 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000753 }
754 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000755
756 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000757}
Dan Gohman5be18e82009-05-19 02:15:55 +0000758
Dan Gohman890f92b2009-04-18 17:56:28 +0000759Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000760 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000761
Dan Gohman087bd1e2010-03-03 05:29:13 +0000762 // Collect all the mul operands in a loop, along with their associated loops.
763 // Iterate in reverse so that constants are emitted last, all else equal.
764 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
765 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
766 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000767 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000768
Dan Gohman087bd1e2010-03-03 05:29:13 +0000769 // Sort by loop. Use a stable sort so that constants follow non-constants.
770 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
771
772 // Emit instructions to mul all the operands. Hoist as much as possible
773 // out of loops.
774 Value *Prod = 0;
775 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
776 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
777 const SCEV *Op = I->second;
778 if (!Prod) {
779 // This is the first operand. Just expand it.
780 Prod = expand(Op);
781 ++I;
782 } else if (Op->isAllOnesValue()) {
783 // Instead of doing a multiply by negative one, just do a negate.
784 Prod = InsertNoopCastOfTo(Prod, Ty);
785 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
786 ++I;
787 } else {
788 // A simple mul.
789 Value *W = expandCodeFor(Op, Ty);
790 Prod = InsertNoopCastOfTo(Prod, Ty);
791 // Canonicalize a constant to the RHS.
792 if (isa<Constant>(Prod)) std::swap(Prod, W);
793 Prod = InsertBinop(Instruction::Mul, Prod, W);
794 ++I;
795 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000796 }
797
Dan Gohman087bd1e2010-03-03 05:29:13 +0000798 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000799}
800
Dan Gohman890f92b2009-04-18 17:56:28 +0000801Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000802 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000803
Dan Gohman92fcdca2009-06-09 17:18:38 +0000804 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000805 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000806 const APInt &RHS = SC->getValue()->getValue();
807 if (RHS.isPowerOf2())
808 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000809 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000810 }
811
Dan Gohman92fcdca2009-06-09 17:18:38 +0000812 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000813 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000814}
815
Dan Gohman453aa4f2009-05-24 18:06:31 +0000816/// Move parts of Base into Rest to leave Base with the minimal
817/// expression that provides a pointer operand suitable for a
818/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000819static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000820 ScalarEvolution &SE) {
821 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
822 Base = A->getStart();
823 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000824 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000825 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000826 A->getLoop(),
827 // FIXME: A->getNoWrapFlags(FlagNW)
828 SCEV::FlagAnyWrap));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000829 }
830 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
831 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000832 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000833 NewAddOps.back() = Rest;
834 Rest = SE.getAddExpr(NewAddOps);
835 ExposePointerBase(Base, Rest, SE);
836 }
837}
838
Andrew Trickc5701912011-10-07 23:46:21 +0000839/// Determine if this is a well-behaved chain of instructions leading back to
840/// the PHI. If so, it may be reused by expanded expressions.
841bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
842 const Loop *L) {
843 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
844 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
845 return false;
846 // If any of the operands don't dominate the insert position, bail.
847 // Addrec operands are always loop-invariant, so this can only happen
848 // if there are instructions which haven't been hoisted.
849 if (L == IVIncInsertLoop) {
850 for (User::op_iterator OI = IncV->op_begin()+1,
851 OE = IncV->op_end(); OI != OE; ++OI)
852 if (Instruction *OInst = dyn_cast<Instruction>(OI))
853 if (!SE.DT->dominates(OInst, IVIncInsertPos))
854 return false;
855 }
856 // Advance to the next instruction.
857 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
858 if (!IncV)
859 return false;
860
861 if (IncV->mayHaveSideEffects())
862 return false;
863
864 if (IncV != PN)
865 return true;
866
867 return isNormalAddRecExprPHI(PN, IncV, L);
868}
869
870/// Determine if this cyclic phi is in a form that would have been generated by
871/// LSR. We don't care if the phi was actually expanded in this pass, as long
872/// as it is in a low-cost form, for example, no implied multiplication. This
873/// should match any patterns generated by getAddRecExprPHILiterally and
874/// expandAddtoGEP.
875bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000876 const Loop *L) {
Andrew Trick64925c52012-01-10 01:45:08 +0000877 if (ChainedPhis.count(PN))
878 return true;
879
Andrew Trickc5701912011-10-07 23:46:21 +0000880 switch (IncV->getOpcode()) {
881 // Check for a simple Add/Sub or GEP of a loop invariant step.
882 case Instruction::Add:
883 case Instruction::Sub:
884 return IncV->getOperand(0) == PN
885 && L->isLoopInvariant(IncV->getOperand(1));
886 case Instruction::BitCast:
887 IncV = dyn_cast<GetElementPtrInst>(IncV->getOperand(0));
888 if (!IncV)
889 return false;
890 // fall-thru to GEP handling
891 case Instruction::GetElementPtr: {
892 // This must be a pointer addition of constants (pretty) or some number of
893 // address-size elements (ugly).
894 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
895 I != E; ++I) {
896 if (isa<Constant>(*I))
897 continue;
898 // ugly geps have 2 operands.
899 // i1* is used by the expander to represent an address-size element.
900 if (IncV->getNumOperands() != 2)
901 return false;
Andrew Trick365c9f12011-10-15 06:19:55 +0000902 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
Andrew Trickc5701912011-10-07 23:46:21 +0000903 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
904 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
905 return false;
Andrew Trick94794dd2011-10-08 02:16:39 +0000906 // Ensure the operands dominate the insertion point. I don't know of a
907 // case when this would not be true, so this is somewhat untested.
908 if (L == IVIncInsertLoop) {
909 for (User::op_iterator OI = IncV->op_begin()+1,
910 OE = IncV->op_end(); OI != OE; ++OI)
911 if (Instruction *OInst = dyn_cast<Instruction>(OI))
912 if (!SE.DT->dominates(OInst, IVIncInsertPos))
913 return false;
914 }
Andrew Trickc5701912011-10-07 23:46:21 +0000915 break;
916 }
917 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
918 if (IncV && IncV->getOpcode() == Instruction::BitCast)
919 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
920 return IncV == PN;
921 }
922 default:
923 return false;
924 }
925}
926
Andrew Trick553fe052011-11-30 06:07:54 +0000927/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
928/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
929/// need to materialize IV increments elsewhere to handle difficult situations.
930Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
931 Type *ExpandTy, Type *IntTy,
932 bool useSubtract) {
933 Value *IncV;
934 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
935 if (ExpandTy->isPointerTy()) {
936 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
937 // If the step isn't constant, don't use an implicitly scaled GEP, because
938 // that would require a multiply inside the loop.
939 if (!isa<ConstantInt>(StepV))
940 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
941 GEPPtrTy->getAddressSpace());
942 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
943 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
944 if (IncV->getType() != PN->getType()) {
945 IncV = Builder.CreateBitCast(IncV, PN->getType());
946 rememberInstruction(IncV);
947 }
948 } else {
949 IncV = useSubtract ?
950 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
951 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
952 rememberInstruction(IncV);
953 }
954 return IncV;
955}
956
Dan Gohmana10756e2010-01-21 02:09:26 +0000957/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
958/// the base addrec, which is the addrec without any non-loop-dominating
959/// values, and return the PHI.
960PHINode *
961SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
962 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000963 Type *ExpandTy,
964 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +0000965 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +0000966
Dan Gohmana10756e2010-01-21 02:09:26 +0000967 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +0000968 BasicBlock *LatchBlock = L->getLoopLatch();
969 if (LatchBlock) {
970 for (BasicBlock::iterator I = L->getHeader()->begin();
971 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
972 if (!SE.isSCEVable(PN->getType()) ||
973 (SE.getEffectiveSCEVType(PN->getType()) !=
974 SE.getEffectiveSCEVType(Normalized->getType())) ||
975 SE.getSCEV(PN) != Normalized)
976 continue;
Dan Gohman22e62192010-02-16 00:20:08 +0000977
Andrew Trickc5701912011-10-07 23:46:21 +0000978 Instruction *IncV =
979 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +0000980
Andrew Trickc5701912011-10-07 23:46:21 +0000981 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +0000982 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +0000983 continue;
Dan Gohman572645c2010-02-12 10:34:29 +0000984 }
Andrew Trickc5701912011-10-07 23:46:21 +0000985 else {
986 if (!isNormalAddRecExprPHI(PN, IncV, L))
987 continue;
988 }
989 // Ok, the add recurrence looks usable.
990 // Remember this PHI, even in post-inc mode.
991 InsertedValues.insert(PN);
992 // Remember the increment.
993 rememberInstruction(IncV);
994 if (L == IVIncInsertLoop)
995 do {
996 if (SE.DT->dominates(IncV, IVIncInsertPos))
997 break;
998 // Make sure the increment is where we want it. But don't move it
999 // down past a potential existing post-inc user.
1000 IncV->moveBefore(IVIncInsertPos);
1001 IVIncInsertPos = IncV;
1002 IncV = cast<Instruction>(IncV->getOperand(0));
1003 } while (IncV != PN);
1004 return PN;
1005 }
1006 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001007
1008 // Save the original insertion point so we can restore it when we're done.
1009 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1010 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1011
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001012 // Another AddRec may need to be recursively expanded below. For example, if
1013 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1014 // loop. Remove this loop from the PostIncLoops set before expanding such
1015 // AddRecs. Otherwise, we cannot find a valid position for the step
1016 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1017 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1018 // so it's not worth implementing SmallPtrSet::swap.
1019 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1020 PostIncLoops.clear();
1021
Dan Gohmana10756e2010-01-21 02:09:26 +00001022 // Expand code for the start value.
1023 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1024 L->getHeader()->begin());
1025
Andrew Trickd152d032011-07-16 00:59:39 +00001026 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001027 assert(!isa<Instruction>(StartV) ||
1028 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1029 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001030
Andrew Trick553fe052011-11-30 06:07:54 +00001031 // Expand code for the step value. Do this before creating the PHI so that PHI
1032 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001033 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001034 // If the stride is negative, insert a sub instead of an add for the increment
1035 // (unless it's a constant, because subtracts of constants are canonicalized
1036 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001037 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001038 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001039 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001040 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001041 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1042
1043 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001044 BasicBlock *Header = L->getHeader();
1045 Builder.SetInsertPoint(Header, Header->begin());
1046 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001047 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001048 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001049 rememberInstruction(PN);
1050
1051 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001052 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001053 BasicBlock *Pred = *HPI;
1054
1055 // Add a start value.
1056 if (!L->contains(Pred)) {
1057 PN->addIncoming(StartV, Pred);
1058 continue;
1059 }
1060
Andrew Trick553fe052011-11-30 06:07:54 +00001061 // Create a step value and add it to the PHI.
1062 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1063 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001064 Instruction *InsertPos = L == IVIncInsertLoop ?
1065 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001066 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001067 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1068
Dan Gohmana10756e2010-01-21 02:09:26 +00001069 PN->addIncoming(IncV, Pred);
1070 }
1071
1072 // Restore the original insert point.
1073 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001074 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001075
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001076 // After expanding subexpressions, restore the PostIncLoops set so the caller
1077 // can ensure that IVIncrement dominates the current uses.
1078 PostIncLoops = SavedPostIncLoops;
1079
Dan Gohmana10756e2010-01-21 02:09:26 +00001080 // Remember this PHI, even in post-inc mode.
1081 InsertedValues.insert(PN);
1082
1083 return PN;
1084}
1085
1086Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001087 Type *STy = S->getType();
1088 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001089 const Loop *L = S->getLoop();
1090
1091 // Determine a normalized form of this expression, which is the expression
1092 // before any post-inc adjustment is made.
1093 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001094 if (PostIncLoops.count(L)) {
1095 PostIncLoopSet Loops;
1096 Loops.insert(L);
1097 Normalized =
1098 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1099 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001100 }
1101
1102 // Strip off any non-loop-dominating component from the addrec start.
1103 const SCEV *Start = Normalized->getStart();
1104 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001105 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001106 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001107 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001108 Normalized = cast<SCEVAddRecExpr>(
1109 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1110 Normalized->getLoop(),
1111 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1112 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001113 }
1114
1115 // Strip off any non-loop-dominating component from the addrec step.
1116 const SCEV *Step = Normalized->getStepRecurrence(SE);
1117 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001118 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001119 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001120 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001121 Normalized =
1122 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
Andrew Trick3228cc22011-03-14 16:50:06 +00001123 Normalized->getLoop(),
1124 // FIXME: Normalized
1125 // ->getNoWrapFlags(FlagNW)
1126 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001127 }
1128
1129 // Expand the core addrec. If we need post-loop scaling, force it to
1130 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001131 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001132 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1133
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001134 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001135 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001136 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001137 Result = PN;
1138 else {
1139 // In PostInc mode, use the post-incremented value.
1140 BasicBlock *LatchBlock = L->getLoopLatch();
1141 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1142 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001143
1144 // For an expansion to use the postinc form, the client must call
1145 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1146 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001147 if (isa<Instruction>(Result)
1148 && !SE.DT->dominates(cast<Instruction>(Result),
1149 Builder.GetInsertPoint())) {
1150 // The induction variable's postinc expansion does not dominate this use.
1151 // IVUsers tries to prevent this case, so it is rare. However, it can
1152 // happen when an IVUser outside the loop is not dominated by the latch
1153 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1154 // all cases. Consider a phi outide whose operand is replaced during
1155 // expansion with the value of the postinc user. Without fundamentally
1156 // changing the way postinc users are tracked, the only remedy is
1157 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1158 // but hopefully expandCodeFor handles that.
1159 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001160 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001161 if (useSubtract)
1162 Step = SE.getNegativeSCEV(Step);
1163 // Expand the step somewhere that dominates the loop header.
1164 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1165 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1166 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1167 // Restore the insertion point to the place where the caller has
1168 // determined dominates all uses.
1169 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1170 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1171 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001172 }
1173
1174 // Re-apply any non-loop-dominating scale.
1175 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001176 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001177 Result = Builder.CreateMul(Result,
1178 expandCodeFor(PostLoopScale, IntTy));
1179 rememberInstruction(Result);
1180 }
1181
1182 // Re-apply any non-loop-dominating offset.
1183 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001184 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001185 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1186 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1187 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001188 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001189 Result = Builder.CreateAdd(Result,
1190 expandCodeFor(PostLoopOffset, IntTy));
1191 rememberInstruction(Result);
1192 }
1193 }
1194
1195 return Result;
1196}
1197
Dan Gohman890f92b2009-04-18 17:56:28 +00001198Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001199 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1200
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001201 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001202 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001203
Dan Gohman4d8414f2009-06-13 16:25:49 +00001204 // First check for an existing canonical IV in a suitable type.
1205 PHINode *CanonicalIV = 0;
1206 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001207 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001208 CanonicalIV = PN;
1209
1210 // Rewrite an AddRec in terms of the canonical induction variable, if
1211 // its type is more narrow.
1212 if (CanonicalIV &&
1213 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1214 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001215 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1216 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1217 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001218 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1219 // FIXME: S->getNoWrapFlags(FlagNW)
1220 SCEV::FlagAnyWrap));
Dan Gohman267a3852009-06-27 21:18:18 +00001221 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1222 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001223 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001224 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001225 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1226 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001227 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001228 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1229 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001230 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001231 return V;
1232 }
1233
Nate Begeman36f891b2005-07-30 00:12:19 +00001234 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001235 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001236 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001237 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001238 // FIXME: can use S->getNoWrapFlags()
1239 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001240
1241 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1242 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001243 const SCEV *Base = S->getStart();
1244 const SCEV *RestArray[1] = { Rest };
1245 // Dig into the expression to find the pointer base for a GEP.
1246 ExposePointerBase(Base, RestArray[0], SE);
1247 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001248 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001249 // Make sure the Base isn't something exotic, such as a multiplied
1250 // or divided pointer value. In those cases, the result type isn't
1251 // actually a pointer type.
1252 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1253 Value *StartV = expand(Base);
1254 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1255 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001256 }
1257 }
1258
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001259 // Just do a normal add. Pre-expand the operands to suppress folding.
1260 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1261 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001262 }
1263
Dan Gohman6ebfd722010-07-26 18:28:14 +00001264 // If we don't yet have a canonical IV, create one.
1265 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001266 // Create and insert the PHI node for the induction variable in the
1267 // specified loop.
1268 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001269 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001270 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1271 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001272 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001273
Owen Andersoneed707b2009-07-24 23:12:02 +00001274 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001275 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001276 BasicBlock *HP = *HPI;
1277 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001278 // Insert a unit add instruction right before the terminator
1279 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001280 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1281 "indvar.next",
1282 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001283 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001284 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001285 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001286 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001287 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001288 }
Gabor Greif76560182010-07-09 15:40:10 +00001289 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001290 }
1291
Dan Gohman6ebfd722010-07-26 18:28:14 +00001292 // {0,+,1} --> Insert a canonical induction variable into the loop!
1293 if (S->isAffine() && S->getOperand(1)->isOne()) {
1294 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1295 "IVs with types different from the canonical IV should "
1296 "already have been handled!");
1297 return CanonicalIV;
1298 }
1299
Dan Gohman4d8414f2009-06-13 16:25:49 +00001300 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001301
Chris Lattnerdf14a042005-10-30 06:24:33 +00001302 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001303 if (S->isAffine()) // {0,+,F} --> i*F
1304 return
1305 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001306 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001307 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001308 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001309 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001310
1311 // If this is a chain of recurrences, turn it into a closed form, using the
1312 // folders, then expandCodeFor the closed form. This allows the folders to
1313 // simplify the expression without having to build a bunch of special code
1314 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001315 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001316
Dan Gohman4d8414f2009-06-13 16:25:49 +00001317 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001318 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001319 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001320 if (isa<SCEVAddRecExpr>(Ext))
1321 NewS = Ext;
1322
Dan Gohman0bba49c2009-07-07 17:06:11 +00001323 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001324 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001325
Dan Gohman4d8414f2009-06-13 16:25:49 +00001326 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001327 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001328 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001329}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001330
Dan Gohman890f92b2009-04-18 17:56:28 +00001331Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001333 Value *V = expandCodeFor(S->getOperand(),
1334 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001335 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001336 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001337 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001338}
1339
Dan Gohman890f92b2009-04-18 17:56:28 +00001340Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001341 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001342 Value *V = expandCodeFor(S->getOperand(),
1343 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001344 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001345 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001346 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001347}
1348
Dan Gohman890f92b2009-04-18 17:56:28 +00001349Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001350 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001351 Value *V = expandCodeFor(S->getOperand(),
1352 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001353 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001354 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001355 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001356}
1357
Dan Gohman890f92b2009-04-18 17:56:28 +00001358Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001359 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001360 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001361 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1362 // In the case of mixed integer and pointer types, do the
1363 // rest of the comparisons as integer.
1364 if (S->getOperand(i)->getType() != Ty) {
1365 Ty = SE.getEffectiveSCEVType(Ty);
1366 LHS = InsertNoopCastOfTo(LHS, Ty);
1367 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001368 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001369 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001370 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001371 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001372 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001373 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001374 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001375 // In the case of mixed integer and pointer types, cast the
1376 // final result back to the pointer type.
1377 if (LHS->getType() != S->getType())
1378 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001379 return LHS;
1380}
1381
Dan Gohman890f92b2009-04-18 17:56:28 +00001382Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001383 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001384 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001385 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1386 // In the case of mixed integer and pointer types, do the
1387 // rest of the comparisons as integer.
1388 if (S->getOperand(i)->getType() != Ty) {
1389 Ty = SE.getEffectiveSCEVType(Ty);
1390 LHS = InsertNoopCastOfTo(LHS, Ty);
1391 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001392 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001393 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001394 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001395 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001396 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001397 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001398 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001399 // In the case of mixed integer and pointer types, cast the
1400 // final result back to the pointer type.
1401 if (LHS->getType() != S->getType())
1402 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001403 return LHS;
1404}
1405
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001406Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001407 Instruction *I) {
1408 BasicBlock::iterator IP = I;
1409 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1410 ++IP;
1411 Builder.SetInsertPoint(IP->getParent(), IP);
1412 return expandCodeFor(SH, Ty);
1413}
1414
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001415Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001416 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001417 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001418 if (Ty) {
1419 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1420 "non-trivial casts should be done with the SCEVs directly!");
1421 V = InsertNoopCastOfTo(V, Ty);
1422 }
1423 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001424}
1425
Dan Gohman890f92b2009-04-18 17:56:28 +00001426Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001427 // Compute an insertion point for this SCEV object. Hoist the instructions
1428 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001429 Instruction *InsertPt = Builder.GetInsertPoint();
1430 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001431 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001432 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001433 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001434 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001435 InsertPt = Preheader->getTerminator();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001436 else {
1437 // LSR sets the insertion point for AddRec start/step values to the
1438 // block start to simplify value reuse, even though it's an invalid
1439 // position. SCEVExpander must correct for this in all cases.
1440 InsertPt = L->getHeader()->getFirstInsertionPt();
1441 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001442 } else {
1443 // If the SCEV is computable at this level, insert it into the header
1444 // after the PHIs (and after any other instructions that we've inserted
1445 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001446 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1447 InsertPt = L->getHeader()->getFirstInsertionPt();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001448 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001449 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001450 break;
1451 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001452
Dan Gohman667d7872009-06-26 22:53:46 +00001453 // Check to see if we already expanded this here.
1454 std::map<std::pair<const SCEV *, Instruction *>,
1455 AssertingVH<Value> >::iterator I =
1456 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001457 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001458 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001459
1460 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1461 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1462 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001463
1464 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001465 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001466
Dan Gohman667d7872009-06-26 22:53:46 +00001467 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001468 //
1469 // This is independent of PostIncLoops. The mapped value simply materializes
1470 // the expression at this insertion point. If the mapped value happened to be
1471 // a postinc expansion, it could be reused by a non postinc user, but only if
1472 // its insertion point was already at the head of the loop.
1473 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001474
Dan Gohman45598552010-02-15 00:21:43 +00001475 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001476 return V;
1477}
Dan Gohman1d09de32009-06-05 16:35:53 +00001478
Dan Gohman1d826a72010-02-14 03:12:47 +00001479void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001480 if (!PostIncLoops.empty())
1481 InsertedPostIncValues.insert(I);
1482 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001483 InsertedValues.insert(I);
1484
1485 // If we just claimed an existing instruction and that instruction had
Andrew Trick3228cc22011-03-14 16:50:06 +00001486 // been the insert point, adjust the insert point forward so that
Dan Gohman1d826a72010-02-14 03:12:47 +00001487 // subsequently inserted code will be dominated.
1488 if (Builder.GetInsertPoint() == I) {
1489 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001490 do { ++It; } while (isInsertedInstruction(It) ||
1491 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001492 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1493 }
1494}
1495
Dan Gohman45598552010-02-15 00:21:43 +00001496void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001497 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001498 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001499 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001500
1501 Builder.SetInsertPoint(BB, I);
1502}
1503
Dan Gohman1d09de32009-06-05 16:35:53 +00001504/// getOrInsertCanonicalInductionVariable - This method returns the
1505/// canonical induction variable of the specified type for the specified
1506/// loop (inserting one if there is none). A canonical induction variable
1507/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001508PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001509SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001510 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001511 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001512
1513 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001514 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001515 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001516 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001517
1518 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001519 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1520 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001521 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001522 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001523 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001524
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001525 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001526}
Andrew Trick20449412011-10-11 02:28:51 +00001527
1528/// hoistStep - Attempt to hoist an IV increment above a potential use.
1529///
1530/// To successfully hoist, two criteria must be met:
1531/// - IncV operands dominate InsertPos and
1532/// - InsertPos dominates IncV
1533///
1534/// Meeting the second condition means that we don't need to check all of IncV's
1535/// existing uses (it's moving up in the domtree).
1536///
1537/// This does not yet recursively hoist the operands, although that would
1538/// not be difficult.
1539///
1540/// This does not require a SCEVExpander instance and could be replaced by a
1541/// general code-insertion helper.
1542bool SCEVExpander::hoistStep(Instruction *IncV, Instruction *InsertPos,
1543 const DominatorTree *DT) {
1544 if (DT->dominates(IncV, InsertPos))
1545 return true;
1546
1547 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
1548 return false;
1549
1550 if (IncV->mayHaveSideEffects())
1551 return false;
1552
1553 // Attempt to hoist IncV
1554 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
1555 OI != OE; ++OI) {
1556 Instruction *OInst = dyn_cast<Instruction>(OI);
Andrew Trick3326ec12012-01-06 21:23:43 +00001557 if (OInst && (OInst == InsertPos || !DT->dominates(OInst, InsertPos)))
Andrew Trick20449412011-10-11 02:28:51 +00001558 return false;
1559 }
1560 IncV->moveBefore(InsertPos);
1561 return true;
1562}
1563
Andrew Trick139f3332012-01-07 01:29:21 +00001564/// Sort values by integer width for replaceCongruentIVs.
1565static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001566 // Put pointers at the back and make sure pointer < pointer = false.
1567 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1568 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1569 return rhs->getType()->getPrimitiveSizeInBits()
1570 < lhs->getType()->getPrimitiveSizeInBits();
1571}
1572
Andrew Trick20449412011-10-11 02:28:51 +00001573/// replaceCongruentIVs - Check for congruent phis in this loop header and
1574/// replace them with their most canonical representative. Return the number of
1575/// phis eliminated.
1576///
1577/// This does not depend on any SCEVExpander state but should be used in
1578/// the same context that SCEVExpander is used.
1579unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Andrew Trickee98aa82012-01-07 01:12:09 +00001580 SmallVectorImpl<WeakVH> &DeadInsts,
1581 const TargetLowering *TLI) {
1582 // Find integer phis in order of increasing width.
1583 SmallVector<PHINode*, 8> Phis;
1584 for (BasicBlock::iterator I = L->getHeader()->begin();
1585 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1586 Phis.push_back(Phi);
1587 }
1588 if (TLI)
1589 std::sort(Phis.begin(), Phis.end(), width_descending);
1590
Andrew Trick20449412011-10-11 02:28:51 +00001591 unsigned NumElim = 0;
1592 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trickee98aa82012-01-07 01:12:09 +00001593 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1594 // so narrow phis can reuse them.
1595 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1596 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1597 PHINode *Phi = *PIter;
1598
Andrew Trick20449412011-10-11 02:28:51 +00001599 if (!SE.isSCEVable(Phi->getType()))
1600 continue;
1601
1602 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1603 if (!OrigPhiRef) {
1604 OrigPhiRef = Phi;
Andrew Trickee98aa82012-01-07 01:12:09 +00001605 if (Phi->getType()->isIntegerTy() && TLI
1606 && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1607 // This phi can be freely truncated to the narrowest phi type. Map the
1608 // truncated expression to it so it will be reused for narrow types.
1609 const SCEV *TruncExpr =
1610 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1611 ExprToIVMap[TruncExpr] = Phi;
1612 }
Andrew Trick20449412011-10-11 02:28:51 +00001613 continue;
1614 }
1615
Andrew Trickee98aa82012-01-07 01:12:09 +00001616 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1617 // sense.
1618 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001619 continue;
1620
1621 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1622 Instruction *OrigInc =
1623 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1624 Instruction *IsomorphicInc =
1625 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1626
Andrew Trickee98aa82012-01-07 01:12:09 +00001627 // If this phi has the same width but is more canonical, replace the
1628 // original with it.
1629 if (OrigPhiRef->getType() == Phi->getType()
1630 && !isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)
Andrew Trick365c9f12011-10-15 06:19:55 +00001631 && isExpandedAddRecExprPHI(Phi, IsomorphicInc, L)) {
Andrew Trick20449412011-10-11 02:28:51 +00001632 std::swap(OrigPhiRef, Phi);
1633 std::swap(OrigInc, IsomorphicInc);
1634 }
1635 // Replacing the congruent phi is sufficient because acyclic redundancy
1636 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1637 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trick139f3332012-01-07 01:29:21 +00001638 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1639 // common case of a single IV increment so that DeleteDeadPHIs can remove
1640 // cycles that had postinc uses.
Andrew Trickee98aa82012-01-07 01:12:09 +00001641 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1642 IsomorphicInc->getType());
1643 if (OrigInc != IsomorphicInc
Andrew Trick64925c52012-01-10 01:45:08 +00001644 && TruncExpr == SE.getSCEV(IsomorphicInc)
1645 && hoistStep(OrigInc, IsomorphicInc, DT)) {
Andrew Trick20449412011-10-11 02:28:51 +00001646 DEBUG_WITH_TYPE(DebugType, dbgs()
1647 << "INDVARS: Eliminated congruent iv.inc: "
1648 << *IsomorphicInc << '\n');
Andrew Trickee98aa82012-01-07 01:12:09 +00001649 Value *NewInc = OrigInc;
1650 if (OrigInc->getType() != IsomorphicInc->getType()) {
1651 IRBuilder<> Builder(OrigInc->getNextNode());
1652 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1653 NewInc = Builder.
1654 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1655 }
1656 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trick20449412011-10-11 02:28:51 +00001657 DeadInsts.push_back(IsomorphicInc);
1658 }
1659 }
1660 DEBUG_WITH_TYPE(DebugType, dbgs()
1661 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1662 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001663 Value *NewIV = OrigPhiRef;
1664 if (OrigPhiRef->getType() != Phi->getType()) {
1665 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1666 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1667 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1668 }
1669 Phi->replaceAllUsesWith(NewIV);
Andrew Trick20449412011-10-11 02:28:51 +00001670 DeadInsts.push_back(Phi);
1671 }
1672 return NumElim;
1673}