blob: ab631f9a8c94b90222eb5ab497984174da2a9648 [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"
Hal Finkel19046ec2013-08-18 00:16:23 +000017#include "llvm/ADT/SmallSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/STLExtras.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000019#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthe4ba75f2013-01-07 14:41:08 +000020#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/LLVMContext.h"
Andrew Trickc5701912011-10-07 23:46:21 +000024#include "llvm/Support/Debug.h"
Andrew Trickd152d032011-07-16 00:59:39 +000025
Nate Begeman36f891b2005-07-30 00:12:19 +000026using namespace llvm;
27
Gabor Greif19e5ada2010-07-09 16:42:04 +000028/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000029/// reusing an existing cast if a suitable one exists, moving an existing
30/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000031/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000032Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000033 Instruction::CastOps Op,
34 BasicBlock::iterator IP) {
Rafael Espindola919a5032012-02-22 03:21:39 +000035 // This function must be called with the builder having a valid insertion
36 // point. It doesn't need to be the actual IP where the uses of the returned
37 // cast will be added, but it must dominate such IP.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000038 // We use this precondition to produce a cast that will dominate all its
39 // uses. In particular, this is crucial for the case where the builder's
40 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +000041 // Since we don't know the builder's insertion point is actually
Rafael Espindola919a5032012-02-22 03:21:39 +000042 // where the uses will be added (only that it dominates it), we are
43 // not allowed to move it.
44 BasicBlock::iterator BIP = Builder.GetInsertPoint();
45
Rafael Espindola23b6ec92012-02-27 02:13:03 +000046 Instruction *Ret = NULL;
Rafael Espindolaef4c80e2012-02-18 17:22:58 +000047
Dan Gohman485c43f2010-06-19 13:25:23 +000048 // Check to see if there is already a cast!
49 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000050 UI != E; ++UI) {
51 User *U = *UI;
52 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000053 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000054 if (CI->getOpcode() == Op) {
Rafael Espindolab84d5402012-02-22 03:44:46 +000055 // If the cast isn't where we want it, create a new cast at IP.
56 // Likewise, do not reuse a cast at BIP because it must dominate
57 // instructions that might be inserted before BIP.
Rafael Espindola919a5032012-02-22 03:21:39 +000058 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohman485c43f2010-06-19 13:25:23 +000059 // Create a new cast, and leave the old cast in place in case
60 // it is being used as an insert point. Clear its operand
61 // so that it doesn't hold anything live.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000062 Ret = CastInst::Create(Op, V, Ty, "", IP);
63 Ret->takeName(CI);
64 CI->replaceAllUsesWith(Ret);
Dan Gohman485c43f2010-06-19 13:25:23 +000065 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola23b6ec92012-02-27 02:13:03 +000066 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000067 }
Rafael Espindola23b6ec92012-02-27 02:13:03 +000068 Ret = CI;
69 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000070 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000071 }
Dan Gohman485c43f2010-06-19 13:25:23 +000072
73 // Create a new cast.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000074 if (!Ret)
75 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
76
77 // We assert at the end of the function since IP might point to an
78 // instruction with different dominance properties than a cast
79 // (an invoke for example) and not dominate BIP (but the cast does).
80 assert(SE.DT->dominates(Ret, BIP));
81
82 rememberInstruction(Ret);
83 return Ret;
Dan Gohman485c43f2010-06-19 13:25:23 +000084}
85
Dan Gohman267a3852009-06-27 21:18:18 +000086/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
87/// which must be possible with a noop cast, doing what we can to share
88/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000089Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000090 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
91 assert((Op == Instruction::BitCast ||
92 Op == Instruction::PtrToInt ||
93 Op == Instruction::IntToPtr) &&
94 "InsertNoopCastOfTo cannot perform non-noop casts!");
95 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
96 "InsertNoopCastOfTo cannot change sizes!");
97
Dan Gohman2d1be872009-04-16 03:18:22 +000098 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-12-14 22:07:19 +000099 if (Op == Instruction::BitCast) {
100 if (V->getType() == Ty)
101 return V;
102 if (CastInst *CI = dyn_cast<CastInst>(V)) {
103 if (CI->getOperand(0)->getType() == Ty)
104 return CI->getOperand(0);
105 }
106 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000107 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +0000108 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +0000109 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000110 if (CastInst *CI = dyn_cast<CastInst>(V))
111 if ((CI->getOpcode() == Instruction::PtrToInt ||
112 CI->getOpcode() == Instruction::IntToPtr) &&
113 SE.getTypeSizeInBits(CI->getType()) ==
114 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
115 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +0000116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
117 if ((CE->getOpcode() == Instruction::PtrToInt ||
118 CE->getOpcode() == Instruction::IntToPtr) &&
119 SE.getTypeSizeInBits(CE->getType()) ==
120 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
121 return CE->getOperand(0);
122 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000123
Dan Gohman485c43f2010-06-19 13:25:23 +0000124 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000125 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000126 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000127
Dan Gohman485c43f2010-06-19 13:25:23 +0000128 // Cast the argument at the beginning of the entry block, after
129 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000130 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000131 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
132 while ((isa<BitCastInst>(IP) &&
133 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
134 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000135 isa<DbgInfoIntrinsic>(IP) ||
136 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000137 ++IP;
138 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000139 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000140
Dan Gohman485c43f2010-06-19 13:25:23 +0000141 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000142 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000143 BasicBlock::iterator IP = I; ++IP;
144 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
145 IP = II->getNormalDest()->begin();
Rafael Espindolaef4c80e2012-02-18 17:22:58 +0000146 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000147 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000148 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000149}
150
Chris Lattner7fec90e2007-04-13 05:04:18 +0000151/// InsertBinop - Insert the specified binary operator, doing a small amount
152/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000153Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
154 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000155 // Fold a binop with constant operands.
156 if (Constant *CLHS = dyn_cast<Constant>(LHS))
157 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000158 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000159
Chris Lattner7fec90e2007-04-13 05:04:18 +0000160 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
161 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000162 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
163 // Scanning starts from the last instruction before the insertion point.
164 BasicBlock::iterator IP = Builder.GetInsertPoint();
165 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000166 --IP;
167 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000168 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
169 // generated code.
170 if (isa<DbgInfoIntrinsic>(IP))
171 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000172 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
173 IP->getOperand(1) == RHS)
174 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000175 if (IP == BlockBegin) break;
176 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000177 }
Dan Gohman267a3852009-06-27 21:18:18 +0000178
Dan Gohman087bd1e2010-03-03 05:29:13 +0000179 // Save the original insertion point so we can restore it when we're done.
180 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
181 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
182
183 // Move the insertion point out of as many loops as we can.
184 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
185 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
186 BasicBlock *Preheader = L->getLoopPreheader();
187 if (!Preheader) break;
188
189 // Ok, move up a level.
190 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
191 }
192
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000193 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000194 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000195 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000196 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000197
198 // Restore the original insert point.
199 if (SaveInsertBB)
200 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
201
Dan Gohmancf5ab822009-05-01 17:13:31 +0000202 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000203}
204
Dan Gohman4a4f7672009-05-27 02:00:53 +0000205/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000206/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000207/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000208/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000209/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
210/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
211/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000212static bool FactorOutConstant(const SCEV *&S,
213 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000214 const SCEV *Factor,
215 ScalarEvolution &SE,
Micah Villmow3574eca2012-10-08 16:38:25 +0000216 const DataLayout *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000217 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000218 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000219 return true;
220
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000221 // x/x == 1.
222 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000223 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000224 return true;
225 }
226
Dan Gohman453aa4f2009-05-24 18:06:31 +0000227 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000228 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000229 // 0/x == 0.
230 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000231 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000232 // Check for divisibility.
233 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
234 ConstantInt *CI =
235 ConstantInt::get(SE.getContext(),
236 C->getValue()->getValue().sdiv(
237 FC->getValue()->getValue()));
238 // If the quotient is zero and the remainder is non-zero, reject
239 // the value at this scale. It will be considered for subsequent
240 // smaller scales.
241 if (!CI->isZero()) {
242 const SCEV *Div = SE.getConstant(CI);
243 S = Div;
244 Remainder =
245 SE.getAddExpr(Remainder,
246 SE.getConstant(C->getValue()->getValue().srem(
247 FC->getValue()->getValue())));
248 return true;
249 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000250 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000251 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000252
253 // In a Mul, check if there is a constant operand which is a multiple
254 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000255 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
256 if (TD) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000257 // With DataLayout, the size is known. Check if there is a constant
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000258 // operand which is a multiple of the given factor. If so, we can
259 // factor it.
260 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
261 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
262 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000263 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000264 NewMulOps[0] =
265 SE.getConstant(C->getValue()->getValue().sdiv(
266 FC->getValue()->getValue()));
267 S = SE.getMulExpr(NewMulOps);
268 return true;
269 }
270 } else {
Micah Villmow3574eca2012-10-08 16:38:25 +0000271 // Without DataLayout, check if Factor can be factored out of any of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000272 // Mul's operands. If so, we can just remove it.
273 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
274 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000275 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000276 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
277 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000278 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000279 NewMulOps[i] = SOp;
280 S = SE.getMulExpr(NewMulOps);
281 return true;
282 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000283 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000284 }
285 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000286
287 // In an AddRec, check if both start and step are divisible.
288 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000289 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000290 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000291 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000292 return false;
293 if (!StepRem->isZero())
294 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000295 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000296 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000297 return false;
Andrew Trick6f71dd72013-07-14 03:10:08 +0000298 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
299 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000300 return true;
301 }
302
303 return false;
304}
305
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000306/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
307/// is the number of SCEVAddRecExprs present, which are kept at the end of
308/// the list.
309///
310static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000311 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000312 ScalarEvolution &SE) {
313 unsigned NumAddRecs = 0;
314 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
315 ++NumAddRecs;
316 // Group Ops into non-addrecs and addrecs.
317 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
318 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
319 // Let ScalarEvolution sort and simplify the non-addrecs list.
320 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000321 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000322 SE.getAddExpr(NoAddRecs);
323 // If it returned an add, use the operands. Otherwise it simplified
324 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000325 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000326 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000327 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000328 else if (!Sum->isZero())
329 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000330 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000331 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000332}
333
334/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
335/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
336/// This helps expose more opportunities for folding parts of the expressions
337/// into GEP indices.
338///
339static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000340 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000341 ScalarEvolution &SE) {
342 // Find the addrecs.
343 SmallVector<const SCEV *, 8> AddRecs;
344 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
345 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
346 const SCEV *Start = A->getStart();
347 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000348 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000349 AddRecs.push_back(SE.getAddRecExpr(Zero,
350 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000351 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000352 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000353 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
354 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000355 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000356 e += Add->getNumOperands();
357 } else {
358 Ops[i] = Start;
359 }
360 }
361 if (!AddRecs.empty()) {
362 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000363 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000364 // Resort the operand list, moving any constants to the front.
365 SimplifyAddOperands(Ops, Ty, SE);
366 }
367}
368
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000369/// expandAddToGEP - Expand an addition expression with a pointer type into
370/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
371/// BasicAliasAnalysis and other passes analyze the result. See the rules
372/// for getelementptr vs. inttoptr in
373/// http://llvm.org/docs/LangRef.html#pointeraliasing
374/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000375///
Dan Gohman3abf9052010-01-19 22:26:02 +0000376/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000377/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
378/// they may introduce pointer arithmetic which may not be safely converted
379/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000380///
381/// Design note: It might seem desirable for this function to be more
382/// loop-aware. If some of the indices are loop-invariant while others
383/// aren't, it might seem desirable to emit multiple GEPs, keeping the
384/// loop-invariant portions of the overall computation outside the loop.
385/// However, there are a few reasons this is not done here. Hoisting simple
386/// arithmetic is a low-level optimization that often isn't very
387/// important until late in the optimization process. In fact, passes
388/// like InstructionCombining will combine GEPs, even if it means
389/// pushing loop-invariant computation down into loops, so even if the
390/// GEPs were split here, the work would quickly be undone. The
391/// LoopStrengthReduction pass, which is usually run quite late (and
392/// after the last InstructionCombining pass), takes care of hoisting
393/// loop-invariant portions of expressions, after considering what
394/// can be folded using target addressing modes.
395///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000396Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
397 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000398 PointerType *PTy,
399 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000400 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000401 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000402 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000403 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000404 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000405
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000406 // Split AddRecs up into parts as either of the parts may be usable
407 // without the other.
408 SplitAddRecs(Ops, Ty, SE);
409
Matt Arsenault14807bd2013-09-10 19:55:24 +0000410 Type *IntPtrTy = SE.TD
411 ? SE.TD->getIntPtrType(PTy)
412 : Type::getInt64Ty(PTy->getContext());
413
Bob Wilsoneb356992009-12-04 01:33:04 +0000414 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000415 // operands into GEP indices, at each level. The first index in a GEP
416 // indexes into the array implied by the pointer operand; the rest of
417 // the indices index into the element or field type selected by the
418 // preceding index.
419 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000420 // If the scale size is not 0, attempt to factor out a scale for
421 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000422 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000423 if (ElTy->isSized()) {
Matt Arsenault14807bd2013-09-10 19:55:24 +0000424 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000425 if (!ElSize->isZero()) {
426 SmallVector<const SCEV *, 8> NewOps;
427 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
428 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000429 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000430 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
431 // Op now has ElSize factored out.
432 ScaledOps.push_back(Op);
433 if (!Remainder->isZero())
434 NewOps.push_back(Remainder);
435 AnyNonZeroIndices = true;
436 } else {
437 // The operand was not divisible, so add it to the list of operands
438 // we'll scan next iteration.
439 NewOps.push_back(Ops[i]);
440 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000441 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000442 // If we made any changes, update Ops.
443 if (!ScaledOps.empty()) {
444 Ops = NewOps;
445 SimplifyAddOperands(Ops, Ty, SE);
446 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000447 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000448 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000449
450 // Record the scaled array index for this level of the type. If
451 // we didn't find any operands that could be factored, tentatively
452 // assume that element zero was selected (since the zero offset
453 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000454 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000455 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000456 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
457 GepIndices.push_back(Scaled);
458
459 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000460 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 bool FoundFieldNo = false;
462 // An empty struct has no fields.
463 if (STy->getNumElements() == 0) break;
464 if (SE.TD) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000465 // With DataLayout, field offsets are known. See if a constant offset
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000466 // falls within any of the struct fields.
467 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000468 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
469 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
470 const StructLayout &SL = *SE.TD->getStructLayout(STy);
471 uint64_t FullOffset = C->getValue()->getZExtValue();
472 if (FullOffset < SL.getSizeInBytes()) {
473 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000474 GepIndices.push_back(
475 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 ElTy = STy->getTypeAtIndex(ElIdx);
477 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000478 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000479 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000480 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000481 }
482 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000483 } else {
Micah Villmow3574eca2012-10-08 16:38:25 +0000484 // Without DataLayout, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000485 // appropriate struct type.
486 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000487 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000488 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000489 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000490 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000491 GepIndices.push_back(FieldNo);
492 ElTy =
493 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000494 Ops[i] = SE.getConstant(Ty, 0);
495 AnyNonZeroIndices = true;
496 FoundFieldNo = true;
497 break;
498 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000499 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000500 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000501 // If no struct field offsets were found, tentatively assume that
502 // field zero was selected (since the zero offset would obviously
503 // be folded away).
504 if (!FoundFieldNo) {
505 ElTy = STy->getTypeAtIndex(0u);
506 GepIndices.push_back(
507 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
508 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000509 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000510
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000512 ElTy = ATy->getElementType();
513 else
514 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000515 }
516
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000517 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000518 // the base to i8* and do an ugly getelementptr with that. It's still
519 // better than ptrtoint+arithmetic+inttoptr at least.
520 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000521 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000522 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000523 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000524
Rafael Espindola705b48d2012-02-21 03:51:14 +0000525 assert(!isa<Instruction>(V) ||
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000526 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola4b045782012-02-21 01:19:51 +0000527
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000528 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000529 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000530
531 // Fold a GEP with constant operands.
532 if (Constant *CLHS = dyn_cast<Constant>(V))
533 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000534 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000535
536 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
537 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000538 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
539 // Scanning starts from the last instruction before the insertion point.
540 BasicBlock::iterator IP = Builder.GetInsertPoint();
541 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000542 --IP;
543 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000544 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
545 // generated code.
546 if (isa<DbgInfoIntrinsic>(IP))
547 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000548 if (IP->getOpcode() == Instruction::GetElementPtr &&
549 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
550 return IP;
551 if (IP == BlockBegin) break;
552 }
553 }
554
Dan Gohman087bd1e2010-03-03 05:29:13 +0000555 // Save the original insertion point so we can restore it when we're done.
556 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
557 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
558
559 // Move the insertion point out of as many loops as we can.
560 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
561 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
562 BasicBlock *Preheader = L->getLoopPreheader();
563 if (!Preheader) break;
564
565 // Ok, move up a level.
566 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
567 }
568
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000569 // Emit a GEP.
570 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000571 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000572
573 // Restore the original insert point.
574 if (SaveInsertBB)
575 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
576
Dan Gohman5be18e82009-05-19 02:15:55 +0000577 return GEP;
578 }
579
Dan Gohman087bd1e2010-03-03 05:29:13 +0000580 // Save the original insertion point so we can restore it when we're done.
581 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
582 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
583
584 // Move the insertion point out of as many loops as we can.
585 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
586 if (!L->isLoopInvariant(V)) break;
587
588 bool AnyIndexNotLoopInvariant = false;
589 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
590 E = GepIndices.end(); I != E; ++I)
591 if (!L->isLoopInvariant(*I)) {
592 AnyIndexNotLoopInvariant = true;
593 break;
594 }
595 if (AnyIndexNotLoopInvariant)
596 break;
597
598 BasicBlock *Preheader = L->getLoopPreheader();
599 if (!Preheader) break;
600
601 // Ok, move up a level.
602 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
603 }
604
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000605 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
606 // because ScalarEvolution may have changed the address arithmetic to
607 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000608 Value *Casted = V;
609 if (V->getType() != PTy)
610 Casted = InsertNoopCastOfTo(Casted, PTy);
611 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000612 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000613 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000614 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000615 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000616
617 // Restore the original insert point.
618 if (SaveInsertBB)
619 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
620
Dan Gohman5be18e82009-05-19 02:15:55 +0000621 return expand(SE.getAddExpr(Ops));
622}
623
Dan Gohman087bd1e2010-03-03 05:29:13 +0000624/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
625/// SCEV expansion. If they are nested, this is the most nested. If they are
626/// neighboring, pick the later.
627static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
628 DominatorTree &DT) {
629 if (!A) return B;
630 if (!B) return A;
631 if (A->contains(B)) return B;
632 if (B->contains(A)) return A;
633 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
634 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
635 return A; // Arbitrarily break the tie.
636}
637
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000638/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000639/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000640const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
641 // Test whether we've already computed the most relevant loop for this SCEV.
642 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
643 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
644 if (!Pair.second)
645 return Pair.first->second;
646
Dan Gohman087bd1e2010-03-03 05:29:13 +0000647 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000648 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000649 return 0;
650 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
651 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000652 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
653 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000654 return 0;
655 }
656 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
657 const Loop *L = 0;
658 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
659 L = AR->getLoop();
660 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
661 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000662 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
663 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000664 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000665 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
666 const Loop *Result = getRelevantLoop(C->getOperand());
667 return RelevantLoops[C] = Result;
668 }
669 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
670 const Loop *Result =
671 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
672 getRelevantLoop(D->getRHS()),
673 *SE.DT);
674 return RelevantLoops[D] = Result;
675 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000676 llvm_unreachable("Unexpected SCEV type!");
677}
678
Dan Gohmanb3579832010-04-15 17:08:50 +0000679namespace {
680
Dan Gohman087bd1e2010-03-03 05:29:13 +0000681/// LoopCompare - Compare loops by PickMostRelevantLoop.
682class LoopCompare {
683 DominatorTree &DT;
684public:
685 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
686
687 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
688 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000689 // Keep pointer operands sorted at the end.
690 if (LHS.second->getType()->isPointerTy() !=
691 RHS.second->getType()->isPointerTy())
692 return LHS.second->getType()->isPointerTy();
693
Dan Gohman087bd1e2010-03-03 05:29:13 +0000694 // Compare loops with PickMostRelevantLoop.
695 if (LHS.first != RHS.first)
696 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
697
698 // If one operand is a non-constant negative and the other is not,
699 // put the non-constant negative on the right so that a sub can
700 // be used instead of a negate and add.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000701 if (LHS.second->isNonConstantNegative()) {
702 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000703 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000704 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000705 return true;
706
707 // Otherwise they are equivalent according to this comparison.
708 return false;
709 }
710};
711
Dan Gohmanb3579832010-04-15 17:08:50 +0000712}
713
Dan Gohman890f92b2009-04-18 17:56:28 +0000714Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000715 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000716
Dan Gohman087bd1e2010-03-03 05:29:13 +0000717 // Collect all the add operands in a loop, along with their associated loops.
718 // Iterate in reverse so that constants are emitted last, all else equal, and
719 // so that pointer operands are inserted first, which the code below relies on
720 // to form more involved GEPs.
721 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
722 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
723 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000724 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000725
Dan Gohman087bd1e2010-03-03 05:29:13 +0000726 // Sort by loop. Use a stable sort so that constants follow non-constants and
727 // pointer operands precede non-pointer operands.
728 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000729
Dan Gohman087bd1e2010-03-03 05:29:13 +0000730 // Emit instructions to add all the operands. Hoist as much as possible
731 // out of loops, and form meaningful getelementptrs where possible.
732 Value *Sum = 0;
733 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
734 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
735 const Loop *CurLoop = I->first;
736 const SCEV *Op = I->second;
737 if (!Sum) {
738 // This is the first operand. Just expand it.
739 Sum = expand(Op);
740 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000741 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000742 // The running sum expression is a pointer. Try to form a getelementptr
743 // at this level with that as the base.
744 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000745 for (; I != E && I->first == CurLoop; ++I) {
746 // If the operand is SCEVUnknown and not instructions, peek through
747 // it, to enable more of it to be folded into the GEP.
748 const SCEV *X = I->second;
749 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
750 if (!isa<Instruction>(U->getValue()))
751 X = SE.getSCEV(U->getValue());
752 NewOps.push_back(X);
753 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000754 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000755 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000756 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000757 // Try to form a getelementptr. If the running sum is instructions,
758 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000759 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000760 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
761 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000762 for (++I; I != E && I->first == CurLoop; ++I)
763 NewOps.push_back(I->second);
764 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000765 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000766 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000767 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000768 Sum = InsertNoopCastOfTo(Sum, Ty);
769 Sum = InsertBinop(Instruction::Sub, Sum, W);
770 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000771 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000772 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000773 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000774 Sum = InsertNoopCastOfTo(Sum, Ty);
775 // Canonicalize a constant to the RHS.
776 if (isa<Constant>(Sum)) std::swap(Sum, W);
777 Sum = InsertBinop(Instruction::Add, Sum, W);
778 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000779 }
780 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000781
782 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000783}
Dan Gohman5be18e82009-05-19 02:15:55 +0000784
Dan Gohman890f92b2009-04-18 17:56:28 +0000785Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000786 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000787
Dan Gohman087bd1e2010-03-03 05:29:13 +0000788 // Collect all the mul operands in a loop, along with their associated loops.
789 // Iterate in reverse so that constants are emitted last, all else equal.
790 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
791 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
792 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000793 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000794
Dan Gohman087bd1e2010-03-03 05:29:13 +0000795 // Sort by loop. Use a stable sort so that constants follow non-constants.
796 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
797
798 // Emit instructions to mul all the operands. Hoist as much as possible
799 // out of loops.
800 Value *Prod = 0;
801 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
802 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
803 const SCEV *Op = I->second;
804 if (!Prod) {
805 // This is the first operand. Just expand it.
806 Prod = expand(Op);
807 ++I;
808 } else if (Op->isAllOnesValue()) {
809 // Instead of doing a multiply by negative one, just do a negate.
810 Prod = InsertNoopCastOfTo(Prod, Ty);
811 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
812 ++I;
813 } else {
814 // A simple mul.
815 Value *W = expandCodeFor(Op, Ty);
816 Prod = InsertNoopCastOfTo(Prod, Ty);
817 // Canonicalize a constant to the RHS.
818 if (isa<Constant>(Prod)) std::swap(Prod, W);
819 Prod = InsertBinop(Instruction::Mul, Prod, W);
820 ++I;
821 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000822 }
823
Dan Gohman087bd1e2010-03-03 05:29:13 +0000824 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000825}
826
Dan Gohman890f92b2009-04-18 17:56:28 +0000827Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000828 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000829
Dan Gohman92fcdca2009-06-09 17:18:38 +0000830 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000831 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000832 const APInt &RHS = SC->getValue()->getValue();
833 if (RHS.isPowerOf2())
834 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000835 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000836 }
837
Dan Gohman92fcdca2009-06-09 17:18:38 +0000838 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000839 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000840}
841
Dan Gohman453aa4f2009-05-24 18:06:31 +0000842/// Move parts of Base into Rest to leave Base with the minimal
843/// expression that provides a pointer operand suitable for a
844/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000845static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000846 ScalarEvolution &SE) {
847 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
848 Base = A->getStart();
849 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000850 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000851 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000852 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000853 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000854 }
855 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
856 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000857 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000858 NewAddOps.back() = Rest;
859 Rest = SE.getAddExpr(NewAddOps);
860 ExposePointerBase(Base, Rest, SE);
861 }
862}
863
Andrew Trickc5701912011-10-07 23:46:21 +0000864/// Determine if this is a well-behaved chain of instructions leading back to
865/// the PHI. If so, it may be reused by expanded expressions.
866bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
867 const Loop *L) {
868 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
869 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
870 return false;
871 // If any of the operands don't dominate the insert position, bail.
872 // Addrec operands are always loop-invariant, so this can only happen
873 // if there are instructions which haven't been hoisted.
874 if (L == IVIncInsertLoop) {
875 for (User::op_iterator OI = IncV->op_begin()+1,
876 OE = IncV->op_end(); OI != OE; ++OI)
877 if (Instruction *OInst = dyn_cast<Instruction>(OI))
878 if (!SE.DT->dominates(OInst, IVIncInsertPos))
879 return false;
880 }
881 // Advance to the next instruction.
882 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
883 if (!IncV)
884 return false;
885
886 if (IncV->mayHaveSideEffects())
887 return false;
888
889 if (IncV != PN)
890 return true;
891
892 return isNormalAddRecExprPHI(PN, IncV, L);
893}
894
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000895/// getIVIncOperand returns an induction variable increment's induction
896/// variable operand.
897///
898/// If allowScale is set, any type of GEP is allowed as long as the nonIV
899/// operands dominate InsertPos.
900///
901/// If allowScale is not set, ensure that a GEP increment conforms to one of the
902/// simple patterns generated by getAddRecExprPHILiterally and
903/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
904Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
905 Instruction *InsertPos,
906 bool allowScale) {
907 if (IncV == InsertPos)
908 return NULL;
909
910 switch (IncV->getOpcode()) {
911 default:
912 return NULL;
913 // Check for a simple Add/Sub or GEP of a loop invariant step.
914 case Instruction::Add:
915 case Instruction::Sub: {
916 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000917 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000918 return dyn_cast<Instruction>(IncV->getOperand(0));
919 return NULL;
920 }
921 case Instruction::BitCast:
922 return dyn_cast<Instruction>(IncV->getOperand(0));
923 case Instruction::GetElementPtr:
924 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
925 I != E; ++I) {
926 if (isa<Constant>(*I))
927 continue;
928 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000929 if (!SE.DT->dominates(OInst, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000930 return NULL;
931 }
932 if (allowScale) {
933 // allow any kind of GEP as long as it can be hoisted.
934 continue;
935 }
936 // This must be a pointer addition of constants (pretty), which is already
937 // handled, or some number of address-size elements (ugly). Ugly geps
938 // have 2 operands. i1* is used by the expander to represent an
939 // address-size element.
940 if (IncV->getNumOperands() != 2)
941 return NULL;
942 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
943 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
944 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
945 return NULL;
946 break;
947 }
948 return dyn_cast<Instruction>(IncV->getOperand(0));
949 }
950}
951
952/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
953/// it available to other uses in this loop. Recursively hoist any operands,
954/// until we reach a value that dominates InsertPos.
955bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000956 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000957 return true;
958
959 // InsertPos must itself dominate IncV so that IncV's new position satisfies
960 // its existing users.
Andrew Trick3de8ad82012-05-22 17:39:59 +0000961 if (isa<PHINode>(InsertPos)
962 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000963 return false;
964
965 // Check that the chain of IV operands leading back to Phi can be hoisted.
966 SmallVector<Instruction*, 4> IVIncs;
967 for(;;) {
968 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
969 if (!Oper)
970 return false;
971 // IncV is safe to hoist.
972 IVIncs.push_back(IncV);
973 IncV = Oper;
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000974 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000975 break;
976 }
977 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
978 E = IVIncs.rend(); I != E; ++I) {
979 (*I)->moveBefore(InsertPos);
980 }
981 return true;
982}
983
Andrew Trickc5701912011-10-07 23:46:21 +0000984/// Determine if this cyclic phi is in a form that would have been generated by
985/// LSR. We don't care if the phi was actually expanded in this pass, as long
986/// as it is in a low-cost form, for example, no implied multiplication. This
987/// should match any patterns generated by getAddRecExprPHILiterally and
988/// expandAddtoGEP.
989bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000990 const Loop *L) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000991 for(Instruction *IVOper = IncV;
992 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
993 /*allowScale=*/false));) {
994 if (IVOper == PN)
995 return true;
Andrew Trickc5701912011-10-07 23:46:21 +0000996 }
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000997 return false;
Andrew Trickc5701912011-10-07 23:46:21 +0000998}
999
Andrew Trick553fe052011-11-30 06:07:54 +00001000/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1001/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1002/// need to materialize IV increments elsewhere to handle difficult situations.
1003Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1004 Type *ExpandTy, Type *IntTy,
1005 bool useSubtract) {
1006 Value *IncV;
1007 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1008 if (ExpandTy->isPointerTy()) {
1009 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1010 // If the step isn't constant, don't use an implicitly scaled GEP, because
1011 // that would require a multiply inside the loop.
1012 if (!isa<ConstantInt>(StepV))
1013 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1014 GEPPtrTy->getAddressSpace());
1015 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1016 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1017 if (IncV->getType() != PN->getType()) {
1018 IncV = Builder.CreateBitCast(IncV, PN->getType());
1019 rememberInstruction(IncV);
1020 }
1021 } else {
1022 IncV = useSubtract ?
1023 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1024 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1025 rememberInstruction(IncV);
1026 }
1027 return IncV;
1028}
1029
Dan Gohmana10756e2010-01-21 02:09:26 +00001030/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1031/// the base addrec, which is the addrec without any non-loop-dominating
1032/// values, and return the PHI.
1033PHINode *
1034SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1035 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 Type *ExpandTy,
1037 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001038 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +00001039
Dan Gohmana10756e2010-01-21 02:09:26 +00001040 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +00001041 BasicBlock *LatchBlock = L->getLoopLatch();
1042 if (LatchBlock) {
1043 for (BasicBlock::iterator I = L->getHeader()->begin();
1044 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1045 if (!SE.isSCEVable(PN->getType()) ||
1046 (SE.getEffectiveSCEVType(PN->getType()) !=
1047 SE.getEffectiveSCEVType(Normalized->getType())) ||
1048 SE.getSCEV(PN) != Normalized)
1049 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001050
Andrew Trickc5701912011-10-07 23:46:21 +00001051 Instruction *IncV =
1052 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +00001053
Andrew Trickc5701912011-10-07 23:46:21 +00001054 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +00001055 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +00001056 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001057 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1058 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001059 }
Andrew Trickc5701912011-10-07 23:46:21 +00001060 else {
1061 if (!isNormalAddRecExprPHI(PN, IncV, L))
1062 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001063 if (L == IVIncInsertLoop)
1064 do {
1065 if (SE.DT->dominates(IncV, IVIncInsertPos))
1066 break;
1067 // Make sure the increment is where we want it. But don't move it
1068 // down past a potential existing post-inc user.
1069 IncV->moveBefore(IVIncInsertPos);
1070 IVIncInsertPos = IncV;
1071 IncV = cast<Instruction>(IncV->getOperand(0));
1072 } while (IncV != PN);
Andrew Trickc5701912011-10-07 23:46:21 +00001073 }
1074 // Ok, the add recurrence looks usable.
1075 // Remember this PHI, even in post-inc mode.
1076 InsertedValues.insert(PN);
1077 // Remember the increment.
1078 rememberInstruction(IncV);
Andrew Trickc5701912011-10-07 23:46:21 +00001079 return PN;
1080 }
1081 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001082
1083 // Save the original insertion point so we can restore it when we're done.
1084 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1085 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1086
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001087 // Another AddRec may need to be recursively expanded below. For example, if
1088 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1089 // loop. Remove this loop from the PostIncLoops set before expanding such
1090 // AddRecs. Otherwise, we cannot find a valid position for the step
1091 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1092 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1093 // so it's not worth implementing SmallPtrSet::swap.
1094 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1095 PostIncLoops.clear();
1096
Dan Gohmana10756e2010-01-21 02:09:26 +00001097 // Expand code for the start value.
1098 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1099 L->getHeader()->begin());
1100
Andrew Trickd152d032011-07-16 00:59:39 +00001101 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001102 assert(!isa<Instruction>(StartV) ||
1103 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1104 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001105
Andrew Trick553fe052011-11-30 06:07:54 +00001106 // Expand code for the step value. Do this before creating the PHI so that PHI
1107 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001108 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001109 // If the stride is negative, insert a sub instead of an add for the increment
1110 // (unless it's a constant, because subtracts of constants are canonicalized
1111 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001112 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001113 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001114 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001115 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001116 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1117
1118 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001119 BasicBlock *Header = L->getHeader();
1120 Builder.SetInsertPoint(Header, Header->begin());
1121 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001122 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001123 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001124 rememberInstruction(PN);
1125
1126 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001127 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001128 BasicBlock *Pred = *HPI;
1129
1130 // Add a start value.
1131 if (!L->contains(Pred)) {
1132 PN->addIncoming(StartV, Pred);
1133 continue;
1134 }
1135
Andrew Trick553fe052011-11-30 06:07:54 +00001136 // Create a step value and add it to the PHI.
1137 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1138 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001139 Instruction *InsertPos = L == IVIncInsertLoop ?
1140 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001141 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001142 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Andrew Trick409443b2013-07-14 02:50:07 +00001143 if (isa<OverflowingBinaryOperator>(IncV)) {
1144 if (Normalized->getNoWrapFlags(SCEV::FlagNUW))
1145 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1146 if (Normalized->getNoWrapFlags(SCEV::FlagNSW))
1147 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1148 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001149 PN->addIncoming(IncV, Pred);
1150 }
1151
1152 // Restore the original insert point.
1153 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001154 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001155
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001156 // After expanding subexpressions, restore the PostIncLoops set so the caller
1157 // can ensure that IVIncrement dominates the current uses.
1158 PostIncLoops = SavedPostIncLoops;
1159
Dan Gohmana10756e2010-01-21 02:09:26 +00001160 // Remember this PHI, even in post-inc mode.
1161 InsertedValues.insert(PN);
1162
1163 return PN;
1164}
1165
1166Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001167 Type *STy = S->getType();
1168 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001169 const Loop *L = S->getLoop();
1170
1171 // Determine a normalized form of this expression, which is the expression
1172 // before any post-inc adjustment is made.
1173 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001174 if (PostIncLoops.count(L)) {
1175 PostIncLoopSet Loops;
1176 Loops.insert(L);
1177 Normalized =
1178 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1179 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001180 }
1181
1182 // Strip off any non-loop-dominating component from the addrec start.
1183 const SCEV *Start = Normalized->getStart();
1184 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001185 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001186 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001187 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001188 Normalized = cast<SCEVAddRecExpr>(
1189 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1190 Normalized->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001191 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001192 }
1193
1194 // Strip off any non-loop-dominating component from the addrec step.
1195 const SCEV *Step = Normalized->getStepRecurrence(SE);
1196 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001197 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001198 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001199 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001200 Normalized =
Andrew Trick6f71dd72013-07-14 03:10:08 +00001201 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1202 Start, Step, Normalized->getLoop(),
1203 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001204 }
1205
1206 // Expand the core addrec. If we need post-loop scaling, force it to
1207 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001208 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001209 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1210
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001211 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001212 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001213 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001214 Result = PN;
1215 else {
1216 // In PostInc mode, use the post-incremented value.
1217 BasicBlock *LatchBlock = L->getLoopLatch();
1218 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1219 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001220
1221 // For an expansion to use the postinc form, the client must call
1222 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1223 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001224 if (isa<Instruction>(Result)
1225 && !SE.DT->dominates(cast<Instruction>(Result),
1226 Builder.GetInsertPoint())) {
1227 // The induction variable's postinc expansion does not dominate this use.
1228 // IVUsers tries to prevent this case, so it is rare. However, it can
1229 // happen when an IVUser outside the loop is not dominated by the latch
1230 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1231 // all cases. Consider a phi outide whose operand is replaced during
1232 // expansion with the value of the postinc user. Without fundamentally
1233 // changing the way postinc users are tracked, the only remedy is
1234 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1235 // but hopefully expandCodeFor handles that.
1236 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001237 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001238 if (useSubtract)
1239 Step = SE.getNegativeSCEV(Step);
1240 // Expand the step somewhere that dominates the loop header.
1241 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1242 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1243 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1244 // Restore the insertion point to the place where the caller has
1245 // determined dominates all uses.
1246 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1247 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1248 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001249 }
1250
1251 // Re-apply any non-loop-dominating scale.
1252 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001253 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001254 Result = Builder.CreateMul(Result,
1255 expandCodeFor(PostLoopScale, IntTy));
1256 rememberInstruction(Result);
1257 }
1258
1259 // Re-apply any non-loop-dominating offset.
1260 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001261 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001262 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1263 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1264 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001265 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001266 Result = Builder.CreateAdd(Result,
1267 expandCodeFor(PostLoopOffset, IntTy));
1268 rememberInstruction(Result);
1269 }
1270 }
1271
1272 return Result;
1273}
1274
Dan Gohman890f92b2009-04-18 17:56:28 +00001275Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001276 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1277
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001278 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001279 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001280
Dan Gohman4d8414f2009-06-13 16:25:49 +00001281 // First check for an existing canonical IV in a suitable type.
1282 PHINode *CanonicalIV = 0;
1283 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001284 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001285 CanonicalIV = PN;
1286
1287 // Rewrite an AddRec in terms of the canonical induction variable, if
1288 // its type is more narrow.
1289 if (CanonicalIV &&
1290 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1291 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001292 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1293 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1294 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001295 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001296 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman267a3852009-06-27 21:18:18 +00001297 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1298 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001299 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001300 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001301 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1302 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001303 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001304 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1305 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001306 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001307 return V;
1308 }
1309
Nate Begeman36f891b2005-07-30 00:12:19 +00001310 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001311 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001312 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001313 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick6f71dd72013-07-14 03:10:08 +00001314 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1315 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +00001316
1317 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1318 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001319 const SCEV *Base = S->getStart();
1320 const SCEV *RestArray[1] = { Rest };
1321 // Dig into the expression to find the pointer base for a GEP.
1322 ExposePointerBase(Base, RestArray[0], SE);
1323 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001324 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001325 // Make sure the Base isn't something exotic, such as a multiplied
1326 // or divided pointer value. In those cases, the result type isn't
1327 // actually a pointer type.
1328 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1329 Value *StartV = expand(Base);
1330 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1331 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001332 }
1333 }
1334
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001335 // Just do a normal add. Pre-expand the operands to suppress folding.
1336 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1337 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001338 }
1339
Dan Gohman6ebfd722010-07-26 18:28:14 +00001340 // If we don't yet have a canonical IV, create one.
1341 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001342 // Create and insert the PHI node for the induction variable in the
1343 // specified loop.
1344 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001345 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001346 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1347 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001348 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001349
Hal Finkel19046ec2013-08-18 00:16:23 +00001350 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersoneed707b2009-07-24 23:12:02 +00001351 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001352 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001353 BasicBlock *HP = *HPI;
Hal Finkel19046ec2013-08-18 00:16:23 +00001354 if (!PredSeen.insert(HP))
1355 continue;
1356
Gabor Greif76560182010-07-09 15:40:10 +00001357 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001358 // Insert a unit add instruction right before the terminator
1359 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001360 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1361 "indvar.next",
1362 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001363 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001364 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001365 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001366 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001367 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001368 }
Gabor Greif76560182010-07-09 15:40:10 +00001369 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001370 }
1371
Dan Gohman6ebfd722010-07-26 18:28:14 +00001372 // {0,+,1} --> Insert a canonical induction variable into the loop!
1373 if (S->isAffine() && S->getOperand(1)->isOne()) {
1374 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1375 "IVs with types different from the canonical IV should "
1376 "already have been handled!");
1377 return CanonicalIV;
1378 }
1379
Dan Gohman4d8414f2009-06-13 16:25:49 +00001380 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001381
Chris Lattnerdf14a042005-10-30 06:24:33 +00001382 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001383 if (S->isAffine()) // {0,+,F} --> i*F
1384 return
1385 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001386 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001387 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001388 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001389 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001390
1391 // If this is a chain of recurrences, turn it into a closed form, using the
1392 // folders, then expandCodeFor the closed form. This allows the folders to
1393 // simplify the expression without having to build a bunch of special code
1394 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001395 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001396
Dan Gohman4d8414f2009-06-13 16:25:49 +00001397 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001398 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001399 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001400 if (isa<SCEVAddRecExpr>(Ext))
1401 NewS = Ext;
1402
Dan Gohman0bba49c2009-07-07 17:06:11 +00001403 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001404 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001405
Dan Gohman4d8414f2009-06-13 16:25:49 +00001406 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001407 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001408 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001409}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001410
Dan Gohman890f92b2009-04-18 17:56:28 +00001411Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001412 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001413 Value *V = expandCodeFor(S->getOperand(),
1414 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001415 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001416 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001417 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001418}
1419
Dan Gohman890f92b2009-04-18 17:56:28 +00001420Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001421 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001422 Value *V = expandCodeFor(S->getOperand(),
1423 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001424 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001425 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001426 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001427}
1428
Dan Gohman890f92b2009-04-18 17:56:28 +00001429Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001430 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001431 Value *V = expandCodeFor(S->getOperand(),
1432 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001433 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001434 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001435 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001436}
1437
Dan Gohman890f92b2009-04-18 17:56:28 +00001438Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001439 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001440 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001441 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1442 // In the case of mixed integer and pointer types, do the
1443 // rest of the comparisons as integer.
1444 if (S->getOperand(i)->getType() != Ty) {
1445 Ty = SE.getEffectiveSCEVType(Ty);
1446 LHS = InsertNoopCastOfTo(LHS, Ty);
1447 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001448 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001449 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001450 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001451 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001452 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001453 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001454 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001455 // In the case of mixed integer and pointer types, cast the
1456 // final result back to the pointer type.
1457 if (LHS->getType() != S->getType())
1458 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001459 return LHS;
1460}
1461
Dan Gohman890f92b2009-04-18 17:56:28 +00001462Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001463 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001464 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001465 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1466 // In the case of mixed integer and pointer types, do the
1467 // rest of the comparisons as integer.
1468 if (S->getOperand(i)->getType() != Ty) {
1469 Ty = SE.getEffectiveSCEVType(Ty);
1470 LHS = InsertNoopCastOfTo(LHS, Ty);
1471 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001472 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001473 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001474 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001475 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001476 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001477 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001478 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001479 // In the case of mixed integer and pointer types, cast the
1480 // final result back to the pointer type.
1481 if (LHS->getType() != S->getType())
1482 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001483 return LHS;
1484}
1485
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001486Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001487 Instruction *IP) {
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001488 Builder.SetInsertPoint(IP->getParent(), IP);
1489 return expandCodeFor(SH, Ty);
1490}
1491
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001492Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001493 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001494 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001495 if (Ty) {
1496 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1497 "non-trivial casts should be done with the SCEVs directly!");
1498 V = InsertNoopCastOfTo(V, Ty);
1499 }
1500 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001501}
1502
Dan Gohman890f92b2009-04-18 17:56:28 +00001503Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001504 // Compute an insertion point for this SCEV object. Hoist the instructions
1505 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001506 Instruction *InsertPt = Builder.GetInsertPoint();
1507 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001508 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001509 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001510 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001511 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001512 InsertPt = Preheader->getTerminator();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001513 else {
1514 // LSR sets the insertion point for AddRec start/step values to the
1515 // block start to simplify value reuse, even though it's an invalid
1516 // position. SCEVExpander must correct for this in all cases.
1517 InsertPt = L->getHeader()->getFirstInsertionPt();
1518 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001519 } else {
1520 // If the SCEV is computable at this level, insert it into the header
1521 // after the PHIs (and after any other instructions that we've inserted
1522 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001523 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1524 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001525 while (InsertPt != Builder.GetInsertPoint()
1526 && (isInsertedInstruction(InsertPt)
1527 || isa<DbgInfoIntrinsic>(InsertPt))) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001528 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001529 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001530 break;
1531 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001532
Dan Gohman667d7872009-06-26 22:53:46 +00001533 // Check to see if we already expanded this here.
Andrew Trick1ba57692013-01-14 21:00:37 +00001534 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1535 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001536 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001537 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001538
1539 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1540 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1541 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001542
1543 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001544 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001545
Dan Gohman667d7872009-06-26 22:53:46 +00001546 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001547 //
1548 // This is independent of PostIncLoops. The mapped value simply materializes
1549 // the expression at this insertion point. If the mapped value happened to be
1550 // a postinc expansion, it could be reused by a non postinc user, but only if
1551 // its insertion point was already at the head of the loop.
1552 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001553
Dan Gohman45598552010-02-15 00:21:43 +00001554 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001555 return V;
1556}
Dan Gohman1d09de32009-06-05 16:35:53 +00001557
Dan Gohman1d826a72010-02-14 03:12:47 +00001558void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001559 if (!PostIncLoops.empty())
1560 InsertedPostIncValues.insert(I);
1561 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001562 InsertedValues.insert(I);
Dan Gohman1d826a72010-02-14 03:12:47 +00001563}
1564
Dan Gohman45598552010-02-15 00:21:43 +00001565void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman45598552010-02-15 00:21:43 +00001566 Builder.SetInsertPoint(BB, I);
1567}
1568
Dan Gohman1d09de32009-06-05 16:35:53 +00001569/// getOrInsertCanonicalInductionVariable - This method returns the
1570/// canonical induction variable of the specified type for the specified
1571/// loop (inserting one if there is none). A canonical induction variable
1572/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001573PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001574SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001575 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001576 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001577
1578 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001579 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001580 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001581 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001582
1583 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001584 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1585 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001586 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001587 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001588 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001589
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001590 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001591}
Andrew Trick20449412011-10-11 02:28:51 +00001592
Andrew Trick139f3332012-01-07 01:29:21 +00001593/// Sort values by integer width for replaceCongruentIVs.
1594static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001595 // Put pointers at the back and make sure pointer < pointer = false.
1596 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1597 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1598 return rhs->getType()->getPrimitiveSizeInBits()
1599 < lhs->getType()->getPrimitiveSizeInBits();
1600}
1601
Andrew Trick20449412011-10-11 02:28:51 +00001602/// replaceCongruentIVs - Check for congruent phis in this loop header and
1603/// replace them with their most canonical representative. Return the number of
1604/// phis eliminated.
1605///
1606/// This does not depend on any SCEVExpander state but should be used in
1607/// the same context that SCEVExpander is used.
1608unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotema04a4a72012-10-19 21:28:43 +00001609 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001610 const TargetTransformInfo *TTI) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001611 // Find integer phis in order of increasing width.
1612 SmallVector<PHINode*, 8> Phis;
1613 for (BasicBlock::iterator I = L->getHeader()->begin();
1614 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1615 Phis.push_back(Phi);
1616 }
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001617 if (TTI)
Andrew Trickee98aa82012-01-07 01:12:09 +00001618 std::sort(Phis.begin(), Phis.end(), width_descending);
1619
Andrew Trick20449412011-10-11 02:28:51 +00001620 unsigned NumElim = 0;
1621 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trickee98aa82012-01-07 01:12:09 +00001622 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1623 // so narrow phis can reuse them.
1624 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1625 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1626 PHINode *Phi = *PIter;
1627
Benjamin Kramer239fd442012-10-19 16:37:30 +00001628 // Fold constant phis. They may be congruent to other constant phis and
1629 // would confuse the logic below that expects proper IVs.
1630 if (Value *V = Phi->hasConstantValue()) {
1631 Phi->replaceAllUsesWith(V);
1632 DeadInsts.push_back(Phi);
1633 ++NumElim;
1634 DEBUG_WITH_TYPE(DebugType, dbgs()
1635 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1636 continue;
1637 }
1638
Andrew Trick20449412011-10-11 02:28:51 +00001639 if (!SE.isSCEVable(Phi->getType()))
1640 continue;
1641
1642 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1643 if (!OrigPhiRef) {
1644 OrigPhiRef = Phi;
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001645 if (Phi->getType()->isIntegerTy() && TTI
1646 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001647 // This phi can be freely truncated to the narrowest phi type. Map the
1648 // truncated expression to it so it will be reused for narrow types.
1649 const SCEV *TruncExpr =
1650 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1651 ExprToIVMap[TruncExpr] = Phi;
1652 }
Andrew Trick20449412011-10-11 02:28:51 +00001653 continue;
1654 }
1655
Andrew Trickee98aa82012-01-07 01:12:09 +00001656 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1657 // sense.
1658 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001659 continue;
1660
1661 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1662 Instruction *OrigInc =
1663 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1664 Instruction *IsomorphicInc =
1665 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1666
Andrew Trickee98aa82012-01-07 01:12:09 +00001667 // If this phi has the same width but is more canonical, replace the
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001668 // original with it. As part of the "more canonical" determination,
1669 // respect a prior decision to use an IV chain.
Andrew Trickee98aa82012-01-07 01:12:09 +00001670 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001671 && !(ChainedPhis.count(Phi)
1672 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1673 && (ChainedPhis.count(Phi)
1674 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trick20449412011-10-11 02:28:51 +00001675 std::swap(OrigPhiRef, Phi);
1676 std::swap(OrigInc, IsomorphicInc);
1677 }
1678 // Replacing the congruent phi is sufficient because acyclic redundancy
1679 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1680 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trick139f3332012-01-07 01:29:21 +00001681 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1682 // common case of a single IV increment so that DeleteDeadPHIs can remove
1683 // cycles that had postinc uses.
Andrew Trickee98aa82012-01-07 01:12:09 +00001684 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1685 IsomorphicInc->getType());
1686 if (OrigInc != IsomorphicInc
Andrew Trick64925c52012-01-10 01:45:08 +00001687 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001688 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1689 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trick20449412011-10-11 02:28:51 +00001690 DEBUG_WITH_TYPE(DebugType, dbgs()
1691 << "INDVARS: Eliminated congruent iv.inc: "
1692 << *IsomorphicInc << '\n');
Andrew Trickee98aa82012-01-07 01:12:09 +00001693 Value *NewInc = OrigInc;
1694 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trickdd1f22f2012-01-14 03:17:23 +00001695 Instruction *IP = isa<PHINode>(OrigInc)
1696 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1697 : OrigInc->getNextNode();
1698 IRBuilder<> Builder(IP);
Andrew Trickee98aa82012-01-07 01:12:09 +00001699 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1700 NewInc = Builder.
1701 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1702 }
1703 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trick20449412011-10-11 02:28:51 +00001704 DeadInsts.push_back(IsomorphicInc);
1705 }
1706 }
1707 DEBUG_WITH_TYPE(DebugType, dbgs()
1708 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1709 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001710 Value *NewIV = OrigPhiRef;
1711 if (OrigPhiRef->getType() != Phi->getType()) {
1712 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1713 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1714 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1715 }
1716 Phi->replaceAllUsesWith(NewIV);
Andrew Trick20449412011-10-11 02:28:51 +00001717 DeadInsts.push_back(Phi);
1718 }
1719 return NumElim;
1720}
Andrew Tricke08c3222012-07-13 23:33:10 +00001721
1722namespace {
1723// Search for a SCEV subexpression that is not safe to expand. Any expression
1724// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1725// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1726// instruction, but the important thing is that we prove the denominator is
1727// nonzero before expansion.
1728//
1729// IVUsers already checks that IV-derived expressions are safe. So this check is
1730// only needed when the expression includes some subexpression that is not IV
1731// derived.
1732//
1733// Currently, we only allow division by a nonzero constant here. If this is
1734// inadequate, we could easily allow division by SCEVUnknown by using
1735// ValueTracking to check isKnownNonZero().
1736struct SCEVFindUnsafe {
1737 bool IsUnsafe;
1738
1739 SCEVFindUnsafe(): IsUnsafe(false) {}
1740
1741 bool follow(const SCEV *S) {
1742 const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S);
1743 if (!D)
1744 return true;
1745 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1746 if (SC && !SC->getValue()->isZero())
1747 return true;
1748 IsUnsafe = true;
1749 return false;
1750 }
1751 bool isDone() const { return IsUnsafe; }
1752};
1753}
1754
1755namespace llvm {
1756bool isSafeToExpand(const SCEV *S) {
1757 SCEVFindUnsafe Search;
1758 visitAll(S, Search);
1759 return !Search.IsUnsafe;
1760}
1761}