blob: c434b40c7ca322a865e6c4031958a26f85ca3ebd [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000018#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthe4ba75f2013-01-07 14:41:08 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/LLVMContext.h"
Andrew Trickc5701912011-10-07 23:46:21 +000023#include "llvm/Support/Debug.h"
Andrew Trickd152d032011-07-16 00:59:39 +000024
Nate Begeman36f891b2005-07-30 00:12:19 +000025using namespace llvm;
26
Gabor Greif19e5ada2010-07-09 16:42:04 +000027/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000028/// reusing an existing cast if a suitable one exists, moving an existing
29/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000030/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000031Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000032 Instruction::CastOps Op,
33 BasicBlock::iterator IP) {
Rafael Espindola919a5032012-02-22 03:21:39 +000034 // This function must be called with the builder having a valid insertion
35 // point. It doesn't need to be the actual IP where the uses of the returned
36 // cast will be added, but it must dominate such IP.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000037 // We use this precondition to produce a cast that will dominate all its
38 // uses. In particular, this is crucial for the case where the builder's
39 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +000040 // Since we don't know the builder's insertion point is actually
Rafael Espindola919a5032012-02-22 03:21:39 +000041 // where the uses will be added (only that it dominates it), we are
42 // not allowed to move it.
43 BasicBlock::iterator BIP = Builder.GetInsertPoint();
44
Rafael Espindola23b6ec92012-02-27 02:13:03 +000045 Instruction *Ret = NULL;
Rafael Espindolaef4c80e2012-02-18 17:22:58 +000046
Dan Gohman485c43f2010-06-19 13:25:23 +000047 // Check to see if there is already a cast!
48 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000049 UI != E; ++UI) {
50 User *U = *UI;
51 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000052 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000053 if (CI->getOpcode() == Op) {
Rafael Espindolab84d5402012-02-22 03:44:46 +000054 // If the cast isn't where we want it, create a new cast at IP.
55 // Likewise, do not reuse a cast at BIP because it must dominate
56 // instructions that might be inserted before BIP.
Rafael Espindola919a5032012-02-22 03:21:39 +000057 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohman485c43f2010-06-19 13:25:23 +000058 // Create a new cast, and leave the old cast in place in case
59 // it is being used as an insert point. Clear its operand
60 // so that it doesn't hold anything live.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000061 Ret = CastInst::Create(Op, V, Ty, "", IP);
62 Ret->takeName(CI);
63 CI->replaceAllUsesWith(Ret);
Dan Gohman485c43f2010-06-19 13:25:23 +000064 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola23b6ec92012-02-27 02:13:03 +000065 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000066 }
Rafael Espindola23b6ec92012-02-27 02:13:03 +000067 Ret = CI;
68 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000069 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000070 }
Dan Gohman485c43f2010-06-19 13:25:23 +000071
72 // Create a new cast.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000073 if (!Ret)
74 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
75
76 // We assert at the end of the function since IP might point to an
77 // instruction with different dominance properties than a cast
78 // (an invoke for example) and not dominate BIP (but the cast does).
79 assert(SE.DT->dominates(Ret, BIP));
80
81 rememberInstruction(Ret);
82 return Ret;
Dan Gohman485c43f2010-06-19 13:25:23 +000083}
84
Dan Gohman267a3852009-06-27 21:18:18 +000085/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
86/// which must be possible with a noop cast, doing what we can to share
87/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000088Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000089 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
90 assert((Op == Instruction::BitCast ||
91 Op == Instruction::PtrToInt ||
92 Op == Instruction::IntToPtr) &&
93 "InsertNoopCastOfTo cannot perform non-noop casts!");
94 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
95 "InsertNoopCastOfTo cannot change sizes!");
96
Dan Gohman2d1be872009-04-16 03:18:22 +000097 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-12-14 22:07:19 +000098 if (Op == Instruction::BitCast) {
99 if (V->getType() == Ty)
100 return V;
101 if (CastInst *CI = dyn_cast<CastInst>(V)) {
102 if (CI->getOperand(0)->getType() == Ty)
103 return CI->getOperand(0);
104 }
105 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000106 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +0000107 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +0000108 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000109 if (CastInst *CI = dyn_cast<CastInst>(V))
110 if ((CI->getOpcode() == Instruction::PtrToInt ||
111 CI->getOpcode() == Instruction::IntToPtr) &&
112 SE.getTypeSizeInBits(CI->getType()) ==
113 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
114 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +0000115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
116 if ((CE->getOpcode() == Instruction::PtrToInt ||
117 CE->getOpcode() == Instruction::IntToPtr) &&
118 SE.getTypeSizeInBits(CE->getType()) ==
119 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
120 return CE->getOperand(0);
121 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000122
Dan Gohman485c43f2010-06-19 13:25:23 +0000123 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000124 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000125 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000126
Dan Gohman485c43f2010-06-19 13:25:23 +0000127 // Cast the argument at the beginning of the entry block, after
128 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000129 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000130 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
131 while ((isa<BitCastInst>(IP) &&
132 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
133 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000134 isa<DbgInfoIntrinsic>(IP) ||
135 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000136 ++IP;
137 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000138 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000139
Dan Gohman485c43f2010-06-19 13:25:23 +0000140 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000141 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000142 BasicBlock::iterator IP = I; ++IP;
143 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
144 IP = II->getNormalDest()->begin();
Rafael Espindolaef4c80e2012-02-18 17:22:58 +0000145 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000146 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000147 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000148}
149
Chris Lattner7fec90e2007-04-13 05:04:18 +0000150/// InsertBinop - Insert the specified binary operator, doing a small amount
151/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000152Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
153 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000154 // Fold a binop with constant operands.
155 if (Constant *CLHS = dyn_cast<Constant>(LHS))
156 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000157 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000158
Chris Lattner7fec90e2007-04-13 05:04:18 +0000159 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
160 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000161 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
162 // Scanning starts from the last instruction before the insertion point.
163 BasicBlock::iterator IP = Builder.GetInsertPoint();
164 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000165 --IP;
166 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000167 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
168 // generated code.
169 if (isa<DbgInfoIntrinsic>(IP))
170 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000171 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
172 IP->getOperand(1) == RHS)
173 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000174 if (IP == BlockBegin) break;
175 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000176 }
Dan Gohman267a3852009-06-27 21:18:18 +0000177
Dan Gohman087bd1e2010-03-03 05:29:13 +0000178 // Save the original insertion point so we can restore it when we're done.
179 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
180 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
181
182 // Move the insertion point out of as many loops as we can.
183 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
184 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
185 BasicBlock *Preheader = L->getLoopPreheader();
186 if (!Preheader) break;
187
188 // Ok, move up a level.
189 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
190 }
191
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000192 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000193 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000194 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000195 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000196
197 // Restore the original insert point.
198 if (SaveInsertBB)
199 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
200
Dan Gohmancf5ab822009-05-01 17:13:31 +0000201 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000202}
203
Dan Gohman4a4f7672009-05-27 02:00:53 +0000204/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000205/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000206/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000207/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000208/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
209/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
210/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000211static bool FactorOutConstant(const SCEV *&S,
212 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000213 const SCEV *Factor,
214 ScalarEvolution &SE,
Micah Villmow3574eca2012-10-08 16:38:25 +0000215 const DataLayout *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000216 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000217 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000218 return true;
219
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000220 // x/x == 1.
221 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000222 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000223 return true;
224 }
225
Dan Gohman453aa4f2009-05-24 18:06:31 +0000226 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000227 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000228 // 0/x == 0.
229 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000230 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000231 // Check for divisibility.
232 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
233 ConstantInt *CI =
234 ConstantInt::get(SE.getContext(),
235 C->getValue()->getValue().sdiv(
236 FC->getValue()->getValue()));
237 // If the quotient is zero and the remainder is non-zero, reject
238 // the value at this scale. It will be considered for subsequent
239 // smaller scales.
240 if (!CI->isZero()) {
241 const SCEV *Div = SE.getConstant(CI);
242 S = Div;
243 Remainder =
244 SE.getAddExpr(Remainder,
245 SE.getConstant(C->getValue()->getValue().srem(
246 FC->getValue()->getValue())));
247 return true;
248 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000249 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000250 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000251
252 // In a Mul, check if there is a constant operand which is a multiple
253 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000254 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
255 if (TD) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000256 // With DataLayout, the size is known. Check if there is a constant
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000257 // operand which is a multiple of the given factor. If so, we can
258 // factor it.
259 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
260 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
261 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000262 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 NewMulOps[0] =
264 SE.getConstant(C->getValue()->getValue().sdiv(
265 FC->getValue()->getValue()));
266 S = SE.getMulExpr(NewMulOps);
267 return true;
268 }
269 } else {
Micah Villmow3574eca2012-10-08 16:38:25 +0000270 // Without DataLayout, check if Factor can be factored out of any of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000271 // Mul's operands. If so, we can just remove it.
272 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
273 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000274 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000275 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
276 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000277 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000278 NewMulOps[i] = SOp;
279 S = SE.getMulExpr(NewMulOps);
280 return true;
281 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000282 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000283 }
284 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000285
286 // In an AddRec, check if both start and step are divisible.
287 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000288 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000289 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000290 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000291 return false;
292 if (!StepRem->isZero())
293 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000294 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000295 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000296 return false;
Andrew Trick6f71dd72013-07-14 03:10:08 +0000297 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
298 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000299 return true;
300 }
301
302 return false;
303}
304
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000305/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
306/// is the number of SCEVAddRecExprs present, which are kept at the end of
307/// the list.
308///
309static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000310 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000311 ScalarEvolution &SE) {
312 unsigned NumAddRecs = 0;
313 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
314 ++NumAddRecs;
315 // Group Ops into non-addrecs and addrecs.
316 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
317 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
318 // Let ScalarEvolution sort and simplify the non-addrecs list.
319 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000320 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000321 SE.getAddExpr(NoAddRecs);
322 // If it returned an add, use the operands. Otherwise it simplified
323 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000324 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000325 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000326 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000327 else if (!Sum->isZero())
328 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000329 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000330 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000331}
332
333/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
334/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
335/// This helps expose more opportunities for folding parts of the expressions
336/// into GEP indices.
337///
338static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000339 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000340 ScalarEvolution &SE) {
341 // Find the addrecs.
342 SmallVector<const SCEV *, 8> AddRecs;
343 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
344 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
345 const SCEV *Start = A->getStart();
346 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000347 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000348 AddRecs.push_back(SE.getAddRecExpr(Zero,
349 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000350 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000351 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000352 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
353 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000354 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000355 e += Add->getNumOperands();
356 } else {
357 Ops[i] = Start;
358 }
359 }
360 if (!AddRecs.empty()) {
361 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000362 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000363 // Resort the operand list, moving any constants to the front.
364 SimplifyAddOperands(Ops, Ty, SE);
365 }
366}
367
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000368/// expandAddToGEP - Expand an addition expression with a pointer type into
369/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
370/// BasicAliasAnalysis and other passes analyze the result. See the rules
371/// for getelementptr vs. inttoptr in
372/// http://llvm.org/docs/LangRef.html#pointeraliasing
373/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000374///
Dan Gohman3abf9052010-01-19 22:26:02 +0000375/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000376/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
377/// they may introduce pointer arithmetic which may not be safely converted
378/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000379///
380/// Design note: It might seem desirable for this function to be more
381/// loop-aware. If some of the indices are loop-invariant while others
382/// aren't, it might seem desirable to emit multiple GEPs, keeping the
383/// loop-invariant portions of the overall computation outside the loop.
384/// However, there are a few reasons this is not done here. Hoisting simple
385/// arithmetic is a low-level optimization that often isn't very
386/// important until late in the optimization process. In fact, passes
387/// like InstructionCombining will combine GEPs, even if it means
388/// pushing loop-invariant computation down into loops, so even if the
389/// GEPs were split here, the work would quickly be undone. The
390/// LoopStrengthReduction pass, which is usually run quite late (and
391/// after the last InstructionCombining pass), takes care of hoisting
392/// loop-invariant portions of expressions, after considering what
393/// can be folded using target addressing modes.
394///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000395Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
396 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000397 PointerType *PTy,
398 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000399 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000400 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000401 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000402 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000403 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000404
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000405 // Split AddRecs up into parts as either of the parts may be usable
406 // without the other.
407 SplitAddRecs(Ops, Ty, SE);
408
Bob Wilsoneb356992009-12-04 01:33:04 +0000409 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000410 // operands into GEP indices, at each level. The first index in a GEP
411 // indexes into the array implied by the pointer operand; the rest of
412 // the indices index into the element or field type selected by the
413 // preceding index.
414 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000415 // If the scale size is not 0, attempt to factor out a scale for
416 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000417 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000418 if (ElTy->isSized()) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000419 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000420 if (!ElSize->isZero()) {
421 SmallVector<const SCEV *, 8> NewOps;
422 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
423 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000424 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000425 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
426 // Op now has ElSize factored out.
427 ScaledOps.push_back(Op);
428 if (!Remainder->isZero())
429 NewOps.push_back(Remainder);
430 AnyNonZeroIndices = true;
431 } else {
432 // The operand was not divisible, so add it to the list of operands
433 // we'll scan next iteration.
434 NewOps.push_back(Ops[i]);
435 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000436 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000437 // If we made any changes, update Ops.
438 if (!ScaledOps.empty()) {
439 Ops = NewOps;
440 SimplifyAddOperands(Ops, Ty, SE);
441 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000442 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000443 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000444
445 // Record the scaled array index for this level of the type. If
446 // we didn't find any operands that could be factored, tentatively
447 // assume that element zero was selected (since the zero offset
448 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000449 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000450 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000451 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
452 GepIndices.push_back(Scaled);
453
454 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000455 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000456 bool FoundFieldNo = false;
457 // An empty struct has no fields.
458 if (STy->getNumElements() == 0) break;
459 if (SE.TD) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000460 // With DataLayout, field offsets are known. See if a constant offset
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 // falls within any of the struct fields.
462 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000463 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
464 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
465 const StructLayout &SL = *SE.TD->getStructLayout(STy);
466 uint64_t FullOffset = C->getValue()->getZExtValue();
467 if (FullOffset < SL.getSizeInBytes()) {
468 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000469 GepIndices.push_back(
470 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000471 ElTy = STy->getTypeAtIndex(ElIdx);
472 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000473 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000474 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000475 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 }
477 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000478 } else {
Micah Villmow3574eca2012-10-08 16:38:25 +0000479 // Without DataLayout, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000480 // appropriate struct type.
481 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000482 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000483 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000484 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000485 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000486 GepIndices.push_back(FieldNo);
487 ElTy =
488 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000489 Ops[i] = SE.getConstant(Ty, 0);
490 AnyNonZeroIndices = true;
491 FoundFieldNo = true;
492 break;
493 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000494 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000495 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000496 // If no struct field offsets were found, tentatively assume that
497 // field zero was selected (since the zero offset would obviously
498 // be folded away).
499 if (!FoundFieldNo) {
500 ElTy = STy->getTypeAtIndex(0u);
501 GepIndices.push_back(
502 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
503 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000504 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000505
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000506 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000507 ElTy = ATy->getElementType();
508 else
509 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000510 }
511
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000512 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000513 // the base to i8* and do an ugly getelementptr with that. It's still
514 // better than ptrtoint+arithmetic+inttoptr at least.
515 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000516 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000517 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000518 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000519
Rafael Espindola705b48d2012-02-21 03:51:14 +0000520 assert(!isa<Instruction>(V) ||
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000521 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola4b045782012-02-21 01:19:51 +0000522
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000523 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000524 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000525
526 // Fold a GEP with constant operands.
527 if (Constant *CLHS = dyn_cast<Constant>(V))
528 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000529 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000530
531 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
532 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000533 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
534 // Scanning starts from the last instruction before the insertion point.
535 BasicBlock::iterator IP = Builder.GetInsertPoint();
536 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000537 --IP;
538 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000539 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
540 // generated code.
541 if (isa<DbgInfoIntrinsic>(IP))
542 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000543 if (IP->getOpcode() == Instruction::GetElementPtr &&
544 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
545 return IP;
546 if (IP == BlockBegin) break;
547 }
548 }
549
Dan Gohman087bd1e2010-03-03 05:29:13 +0000550 // Save the original insertion point so we can restore it when we're done.
551 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
552 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
553
554 // Move the insertion point out of as many loops as we can.
555 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
556 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
557 BasicBlock *Preheader = L->getLoopPreheader();
558 if (!Preheader) break;
559
560 // Ok, move up a level.
561 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
562 }
563
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000564 // Emit a GEP.
565 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000566 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000567
568 // Restore the original insert point.
569 if (SaveInsertBB)
570 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
571
Dan Gohman5be18e82009-05-19 02:15:55 +0000572 return GEP;
573 }
574
Dan Gohman087bd1e2010-03-03 05:29:13 +0000575 // Save the original insertion point so we can restore it when we're done.
576 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
577 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
578
579 // Move the insertion point out of as many loops as we can.
580 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
581 if (!L->isLoopInvariant(V)) break;
582
583 bool AnyIndexNotLoopInvariant = false;
584 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
585 E = GepIndices.end(); I != E; ++I)
586 if (!L->isLoopInvariant(*I)) {
587 AnyIndexNotLoopInvariant = true;
588 break;
589 }
590 if (AnyIndexNotLoopInvariant)
591 break;
592
593 BasicBlock *Preheader = L->getLoopPreheader();
594 if (!Preheader) break;
595
596 // Ok, move up a level.
597 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
598 }
599
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000600 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
601 // because ScalarEvolution may have changed the address arithmetic to
602 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000603 Value *Casted = V;
604 if (V->getType() != PTy)
605 Casted = InsertNoopCastOfTo(Casted, PTy);
606 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000607 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000608 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000609 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000610 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000611
612 // Restore the original insert point.
613 if (SaveInsertBB)
614 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
615
Dan Gohman5be18e82009-05-19 02:15:55 +0000616 return expand(SE.getAddExpr(Ops));
617}
618
Dan Gohman087bd1e2010-03-03 05:29:13 +0000619/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
620/// SCEV expansion. If they are nested, this is the most nested. If they are
621/// neighboring, pick the later.
622static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
623 DominatorTree &DT) {
624 if (!A) return B;
625 if (!B) return A;
626 if (A->contains(B)) return B;
627 if (B->contains(A)) return A;
628 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
629 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
630 return A; // Arbitrarily break the tie.
631}
632
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000633/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000634/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000635const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
636 // Test whether we've already computed the most relevant loop for this SCEV.
637 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
638 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
639 if (!Pair.second)
640 return Pair.first->second;
641
Dan Gohman087bd1e2010-03-03 05:29:13 +0000642 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000643 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000644 return 0;
645 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
646 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000647 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
648 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000649 return 0;
650 }
651 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
652 const Loop *L = 0;
653 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
654 L = AR->getLoop();
655 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
656 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000657 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
658 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000659 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000660 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
661 const Loop *Result = getRelevantLoop(C->getOperand());
662 return RelevantLoops[C] = Result;
663 }
664 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
665 const Loop *Result =
666 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
667 getRelevantLoop(D->getRHS()),
668 *SE.DT);
669 return RelevantLoops[D] = Result;
670 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000671 llvm_unreachable("Unexpected SCEV type!");
672}
673
Dan Gohmanb3579832010-04-15 17:08:50 +0000674namespace {
675
Dan Gohman087bd1e2010-03-03 05:29:13 +0000676/// LoopCompare - Compare loops by PickMostRelevantLoop.
677class LoopCompare {
678 DominatorTree &DT;
679public:
680 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
681
682 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
683 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000684 // Keep pointer operands sorted at the end.
685 if (LHS.second->getType()->isPointerTy() !=
686 RHS.second->getType()->isPointerTy())
687 return LHS.second->getType()->isPointerTy();
688
Dan Gohman087bd1e2010-03-03 05:29:13 +0000689 // Compare loops with PickMostRelevantLoop.
690 if (LHS.first != RHS.first)
691 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
692
693 // If one operand is a non-constant negative and the other is not,
694 // put the non-constant negative on the right so that a sub can
695 // be used instead of a negate and add.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000696 if (LHS.second->isNonConstantNegative()) {
697 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000698 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000699 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000700 return true;
701
702 // Otherwise they are equivalent according to this comparison.
703 return false;
704 }
705};
706
Dan Gohmanb3579832010-04-15 17:08:50 +0000707}
708
Dan Gohman890f92b2009-04-18 17:56:28 +0000709Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000710 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000711
Dan Gohman087bd1e2010-03-03 05:29:13 +0000712 // Collect all the add operands in a loop, along with their associated loops.
713 // Iterate in reverse so that constants are emitted last, all else equal, and
714 // so that pointer operands are inserted first, which the code below relies on
715 // to form more involved GEPs.
716 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
717 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
718 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000719 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000720
Dan Gohman087bd1e2010-03-03 05:29:13 +0000721 // Sort by loop. Use a stable sort so that constants follow non-constants and
722 // pointer operands precede non-pointer operands.
723 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000724
Dan Gohman087bd1e2010-03-03 05:29:13 +0000725 // Emit instructions to add all the operands. Hoist as much as possible
726 // out of loops, and form meaningful getelementptrs where possible.
727 Value *Sum = 0;
728 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
729 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
730 const Loop *CurLoop = I->first;
731 const SCEV *Op = I->second;
732 if (!Sum) {
733 // This is the first operand. Just expand it.
734 Sum = expand(Op);
735 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000736 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000737 // The running sum expression is a pointer. Try to form a getelementptr
738 // at this level with that as the base.
739 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000740 for (; I != E && I->first == CurLoop; ++I) {
741 // If the operand is SCEVUnknown and not instructions, peek through
742 // it, to enable more of it to be folded into the GEP.
743 const SCEV *X = I->second;
744 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
745 if (!isa<Instruction>(U->getValue()))
746 X = SE.getSCEV(U->getValue());
747 NewOps.push_back(X);
748 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000749 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000750 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000751 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000752 // Try to form a getelementptr. If the running sum is instructions,
753 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000754 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000755 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
756 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000757 for (++I; I != E && I->first == CurLoop; ++I)
758 NewOps.push_back(I->second);
759 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000760 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000761 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000762 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000763 Sum = InsertNoopCastOfTo(Sum, Ty);
764 Sum = InsertBinop(Instruction::Sub, Sum, W);
765 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000766 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000767 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000768 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000769 Sum = InsertNoopCastOfTo(Sum, Ty);
770 // Canonicalize a constant to the RHS.
771 if (isa<Constant>(Sum)) std::swap(Sum, W);
772 Sum = InsertBinop(Instruction::Add, Sum, W);
773 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000774 }
775 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000776
777 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000778}
Dan Gohman5be18e82009-05-19 02:15:55 +0000779
Dan Gohman890f92b2009-04-18 17:56:28 +0000780Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000781 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000782
Dan Gohman087bd1e2010-03-03 05:29:13 +0000783 // Collect all the mul operands in a loop, along with their associated loops.
784 // Iterate in reverse so that constants are emitted last, all else equal.
785 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
786 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
787 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000788 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000789
Dan Gohman087bd1e2010-03-03 05:29:13 +0000790 // Sort by loop. Use a stable sort so that constants follow non-constants.
791 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
792
793 // Emit instructions to mul all the operands. Hoist as much as possible
794 // out of loops.
795 Value *Prod = 0;
796 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
797 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
798 const SCEV *Op = I->second;
799 if (!Prod) {
800 // This is the first operand. Just expand it.
801 Prod = expand(Op);
802 ++I;
803 } else if (Op->isAllOnesValue()) {
804 // Instead of doing a multiply by negative one, just do a negate.
805 Prod = InsertNoopCastOfTo(Prod, Ty);
806 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
807 ++I;
808 } else {
809 // A simple mul.
810 Value *W = expandCodeFor(Op, Ty);
811 Prod = InsertNoopCastOfTo(Prod, Ty);
812 // Canonicalize a constant to the RHS.
813 if (isa<Constant>(Prod)) std::swap(Prod, W);
814 Prod = InsertBinop(Instruction::Mul, Prod, W);
815 ++I;
816 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000817 }
818
Dan Gohman087bd1e2010-03-03 05:29:13 +0000819 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000820}
821
Dan Gohman890f92b2009-04-18 17:56:28 +0000822Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000823 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000824
Dan Gohman92fcdca2009-06-09 17:18:38 +0000825 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000826 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000827 const APInt &RHS = SC->getValue()->getValue();
828 if (RHS.isPowerOf2())
829 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000830 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000831 }
832
Dan Gohman92fcdca2009-06-09 17:18:38 +0000833 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000834 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000835}
836
Dan Gohman453aa4f2009-05-24 18:06:31 +0000837/// Move parts of Base into Rest to leave Base with the minimal
838/// expression that provides a pointer operand suitable for a
839/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000841 ScalarEvolution &SE) {
842 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
843 Base = A->getStart();
844 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000845 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000846 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000847 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000848 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000849 }
850 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
851 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000852 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000853 NewAddOps.back() = Rest;
854 Rest = SE.getAddExpr(NewAddOps);
855 ExposePointerBase(Base, Rest, SE);
856 }
857}
858
Andrew Trickc5701912011-10-07 23:46:21 +0000859/// Determine if this is a well-behaved chain of instructions leading back to
860/// the PHI. If so, it may be reused by expanded expressions.
861bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
862 const Loop *L) {
863 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
864 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
865 return false;
866 // If any of the operands don't dominate the insert position, bail.
867 // Addrec operands are always loop-invariant, so this can only happen
868 // if there are instructions which haven't been hoisted.
869 if (L == IVIncInsertLoop) {
870 for (User::op_iterator OI = IncV->op_begin()+1,
871 OE = IncV->op_end(); OI != OE; ++OI)
872 if (Instruction *OInst = dyn_cast<Instruction>(OI))
873 if (!SE.DT->dominates(OInst, IVIncInsertPos))
874 return false;
875 }
876 // Advance to the next instruction.
877 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
878 if (!IncV)
879 return false;
880
881 if (IncV->mayHaveSideEffects())
882 return false;
883
884 if (IncV != PN)
885 return true;
886
887 return isNormalAddRecExprPHI(PN, IncV, L);
888}
889
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000890/// getIVIncOperand returns an induction variable increment's induction
891/// variable operand.
892///
893/// If allowScale is set, any type of GEP is allowed as long as the nonIV
894/// operands dominate InsertPos.
895///
896/// If allowScale is not set, ensure that a GEP increment conforms to one of the
897/// simple patterns generated by getAddRecExprPHILiterally and
898/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
899Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
900 Instruction *InsertPos,
901 bool allowScale) {
902 if (IncV == InsertPos)
903 return NULL;
904
905 switch (IncV->getOpcode()) {
906 default:
907 return NULL;
908 // Check for a simple Add/Sub or GEP of a loop invariant step.
909 case Instruction::Add:
910 case Instruction::Sub: {
911 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000912 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000913 return dyn_cast<Instruction>(IncV->getOperand(0));
914 return NULL;
915 }
916 case Instruction::BitCast:
917 return dyn_cast<Instruction>(IncV->getOperand(0));
918 case Instruction::GetElementPtr:
919 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
920 I != E; ++I) {
921 if (isa<Constant>(*I))
922 continue;
923 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000924 if (!SE.DT->dominates(OInst, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000925 return NULL;
926 }
927 if (allowScale) {
928 // allow any kind of GEP as long as it can be hoisted.
929 continue;
930 }
931 // This must be a pointer addition of constants (pretty), which is already
932 // handled, or some number of address-size elements (ugly). Ugly geps
933 // have 2 operands. i1* is used by the expander to represent an
934 // address-size element.
935 if (IncV->getNumOperands() != 2)
936 return NULL;
937 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
938 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
939 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
940 return NULL;
941 break;
942 }
943 return dyn_cast<Instruction>(IncV->getOperand(0));
944 }
945}
946
947/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
948/// it available to other uses in this loop. Recursively hoist any operands,
949/// until we reach a value that dominates InsertPos.
950bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000951 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000952 return true;
953
954 // InsertPos must itself dominate IncV so that IncV's new position satisfies
955 // its existing users.
Andrew Trick3de8ad82012-05-22 17:39:59 +0000956 if (isa<PHINode>(InsertPos)
957 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000958 return false;
959
960 // Check that the chain of IV operands leading back to Phi can be hoisted.
961 SmallVector<Instruction*, 4> IVIncs;
962 for(;;) {
963 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
964 if (!Oper)
965 return false;
966 // IncV is safe to hoist.
967 IVIncs.push_back(IncV);
968 IncV = Oper;
Rafael Espindolac9ae8cc2012-02-26 02:19:19 +0000969 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000970 break;
971 }
972 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
973 E = IVIncs.rend(); I != E; ++I) {
974 (*I)->moveBefore(InsertPos);
975 }
976 return true;
977}
978
Andrew Trickc5701912011-10-07 23:46:21 +0000979/// Determine if this cyclic phi is in a form that would have been generated by
980/// LSR. We don't care if the phi was actually expanded in this pass, as long
981/// as it is in a low-cost form, for example, no implied multiplication. This
982/// should match any patterns generated by getAddRecExprPHILiterally and
983/// expandAddtoGEP.
984bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000985 const Loop *L) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000986 for(Instruction *IVOper = IncV;
987 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
988 /*allowScale=*/false));) {
989 if (IVOper == PN)
990 return true;
Andrew Trickc5701912011-10-07 23:46:21 +0000991 }
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000992 return false;
Andrew Trickc5701912011-10-07 23:46:21 +0000993}
994
Andrew Trick553fe052011-11-30 06:07:54 +0000995/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
996/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
997/// need to materialize IV increments elsewhere to handle difficult situations.
998Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
999 Type *ExpandTy, Type *IntTy,
1000 bool useSubtract) {
1001 Value *IncV;
1002 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1003 if (ExpandTy->isPointerTy()) {
1004 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1005 // If the step isn't constant, don't use an implicitly scaled GEP, because
1006 // that would require a multiply inside the loop.
1007 if (!isa<ConstantInt>(StepV))
1008 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1009 GEPPtrTy->getAddressSpace());
1010 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1011 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1012 if (IncV->getType() != PN->getType()) {
1013 IncV = Builder.CreateBitCast(IncV, PN->getType());
1014 rememberInstruction(IncV);
1015 }
1016 } else {
1017 IncV = useSubtract ?
1018 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1019 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1020 rememberInstruction(IncV);
1021 }
1022 return IncV;
1023}
1024
Dan Gohmana10756e2010-01-21 02:09:26 +00001025/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1026/// the base addrec, which is the addrec without any non-loop-dominating
1027/// values, and return the PHI.
1028PHINode *
1029SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1030 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 Type *ExpandTy,
1032 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001033 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +00001034
Dan Gohmana10756e2010-01-21 02:09:26 +00001035 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +00001036 BasicBlock *LatchBlock = L->getLoopLatch();
1037 if (LatchBlock) {
1038 for (BasicBlock::iterator I = L->getHeader()->begin();
1039 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1040 if (!SE.isSCEVable(PN->getType()) ||
1041 (SE.getEffectiveSCEVType(PN->getType()) !=
1042 SE.getEffectiveSCEVType(Normalized->getType())) ||
1043 SE.getSCEV(PN) != Normalized)
1044 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001045
Andrew Trickc5701912011-10-07 23:46:21 +00001046 Instruction *IncV =
1047 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +00001048
Andrew Trickc5701912011-10-07 23:46:21 +00001049 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +00001050 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +00001051 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001052 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1053 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001054 }
Andrew Trickc5701912011-10-07 23:46:21 +00001055 else {
1056 if (!isNormalAddRecExprPHI(PN, IncV, L))
1057 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001058 if (L == IVIncInsertLoop)
1059 do {
1060 if (SE.DT->dominates(IncV, IVIncInsertPos))
1061 break;
1062 // Make sure the increment is where we want it. But don't move it
1063 // down past a potential existing post-inc user.
1064 IncV->moveBefore(IVIncInsertPos);
1065 IVIncInsertPos = IncV;
1066 IncV = cast<Instruction>(IncV->getOperand(0));
1067 } while (IncV != PN);
Andrew Trickc5701912011-10-07 23:46:21 +00001068 }
1069 // Ok, the add recurrence looks usable.
1070 // Remember this PHI, even in post-inc mode.
1071 InsertedValues.insert(PN);
1072 // Remember the increment.
1073 rememberInstruction(IncV);
Andrew Trickc5701912011-10-07 23:46:21 +00001074 return PN;
1075 }
1076 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001077
1078 // Save the original insertion point so we can restore it when we're done.
1079 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1080 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1081
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001082 // Another AddRec may need to be recursively expanded below. For example, if
1083 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1084 // loop. Remove this loop from the PostIncLoops set before expanding such
1085 // AddRecs. Otherwise, we cannot find a valid position for the step
1086 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1087 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1088 // so it's not worth implementing SmallPtrSet::swap.
1089 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1090 PostIncLoops.clear();
1091
Dan Gohmana10756e2010-01-21 02:09:26 +00001092 // Expand code for the start value.
1093 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1094 L->getHeader()->begin());
1095
Andrew Trickd152d032011-07-16 00:59:39 +00001096 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001097 assert(!isa<Instruction>(StartV) ||
1098 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1099 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001100
Andrew Trick553fe052011-11-30 06:07:54 +00001101 // Expand code for the step value. Do this before creating the PHI so that PHI
1102 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001103 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001104 // If the stride is negative, insert a sub instead of an add for the increment
1105 // (unless it's a constant, because subtracts of constants are canonicalized
1106 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001107 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001108 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001109 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001110 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001111 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1112
1113 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001114 BasicBlock *Header = L->getHeader();
1115 Builder.SetInsertPoint(Header, Header->begin());
1116 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001117 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001118 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001119 rememberInstruction(PN);
1120
1121 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001122 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001123 BasicBlock *Pred = *HPI;
1124
1125 // Add a start value.
1126 if (!L->contains(Pred)) {
1127 PN->addIncoming(StartV, Pred);
1128 continue;
1129 }
1130
Andrew Trick553fe052011-11-30 06:07:54 +00001131 // Create a step value and add it to the PHI.
1132 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1133 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001134 Instruction *InsertPos = L == IVIncInsertLoop ?
1135 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001136 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001137 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Andrew Trick409443b2013-07-14 02:50:07 +00001138 if (isa<OverflowingBinaryOperator>(IncV)) {
1139 if (Normalized->getNoWrapFlags(SCEV::FlagNUW))
1140 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1141 if (Normalized->getNoWrapFlags(SCEV::FlagNSW))
1142 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1143 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001144 PN->addIncoming(IncV, Pred);
1145 }
1146
1147 // Restore the original insert point.
1148 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001149 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001150
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001151 // After expanding subexpressions, restore the PostIncLoops set so the caller
1152 // can ensure that IVIncrement dominates the current uses.
1153 PostIncLoops = SavedPostIncLoops;
1154
Dan Gohmana10756e2010-01-21 02:09:26 +00001155 // Remember this PHI, even in post-inc mode.
1156 InsertedValues.insert(PN);
1157
1158 return PN;
1159}
1160
1161Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001162 Type *STy = S->getType();
1163 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001164 const Loop *L = S->getLoop();
1165
1166 // Determine a normalized form of this expression, which is the expression
1167 // before any post-inc adjustment is made.
1168 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001169 if (PostIncLoops.count(L)) {
1170 PostIncLoopSet Loops;
1171 Loops.insert(L);
1172 Normalized =
1173 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1174 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001175 }
1176
1177 // Strip off any non-loop-dominating component from the addrec start.
1178 const SCEV *Start = Normalized->getStart();
1179 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001180 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001181 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001182 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001183 Normalized = cast<SCEVAddRecExpr>(
1184 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1185 Normalized->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001186 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001187 }
1188
1189 // Strip off any non-loop-dominating component from the addrec step.
1190 const SCEV *Step = Normalized->getStepRecurrence(SE);
1191 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001192 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001193 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001194 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001195 Normalized =
Andrew Trick6f71dd72013-07-14 03:10:08 +00001196 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1197 Start, Step, Normalized->getLoop(),
1198 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001199 }
1200
1201 // Expand the core addrec. If we need post-loop scaling, force it to
1202 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001203 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001204 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1205
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001206 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001207 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001208 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001209 Result = PN;
1210 else {
1211 // In PostInc mode, use the post-incremented value.
1212 BasicBlock *LatchBlock = L->getLoopLatch();
1213 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1214 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001215
1216 // For an expansion to use the postinc form, the client must call
1217 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1218 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001219 if (isa<Instruction>(Result)
1220 && !SE.DT->dominates(cast<Instruction>(Result),
1221 Builder.GetInsertPoint())) {
1222 // The induction variable's postinc expansion does not dominate this use.
1223 // IVUsers tries to prevent this case, so it is rare. However, it can
1224 // happen when an IVUser outside the loop is not dominated by the latch
1225 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1226 // all cases. Consider a phi outide whose operand is replaced during
1227 // expansion with the value of the postinc user. Without fundamentally
1228 // changing the way postinc users are tracked, the only remedy is
1229 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1230 // but hopefully expandCodeFor handles that.
1231 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001232 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001233 if (useSubtract)
1234 Step = SE.getNegativeSCEV(Step);
1235 // Expand the step somewhere that dominates the loop header.
1236 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1237 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1238 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1239 // Restore the insertion point to the place where the caller has
1240 // determined dominates all uses.
1241 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1242 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1243 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001244 }
1245
1246 // Re-apply any non-loop-dominating scale.
1247 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001248 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001249 Result = Builder.CreateMul(Result,
1250 expandCodeFor(PostLoopScale, IntTy));
1251 rememberInstruction(Result);
1252 }
1253
1254 // Re-apply any non-loop-dominating offset.
1255 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001256 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001257 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1258 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1259 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001260 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001261 Result = Builder.CreateAdd(Result,
1262 expandCodeFor(PostLoopOffset, IntTy));
1263 rememberInstruction(Result);
1264 }
1265 }
1266
1267 return Result;
1268}
1269
Dan Gohman890f92b2009-04-18 17:56:28 +00001270Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001271 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1272
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001273 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001274 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001275
Dan Gohman4d8414f2009-06-13 16:25:49 +00001276 // First check for an existing canonical IV in a suitable type.
1277 PHINode *CanonicalIV = 0;
1278 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001279 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001280 CanonicalIV = PN;
1281
1282 // Rewrite an AddRec in terms of the canonical induction variable, if
1283 // its type is more narrow.
1284 if (CanonicalIV &&
1285 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1286 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001287 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1288 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1289 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001290 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001291 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman267a3852009-06-27 21:18:18 +00001292 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1293 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001294 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001295 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001296 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1297 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001298 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001299 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1300 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001301 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001302 return V;
1303 }
1304
Nate Begeman36f891b2005-07-30 00:12:19 +00001305 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001306 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001307 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001308 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick6f71dd72013-07-14 03:10:08 +00001309 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1310 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +00001311
1312 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1313 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001314 const SCEV *Base = S->getStart();
1315 const SCEV *RestArray[1] = { Rest };
1316 // Dig into the expression to find the pointer base for a GEP.
1317 ExposePointerBase(Base, RestArray[0], SE);
1318 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001319 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001320 // Make sure the Base isn't something exotic, such as a multiplied
1321 // or divided pointer value. In those cases, the result type isn't
1322 // actually a pointer type.
1323 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1324 Value *StartV = expand(Base);
1325 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1326 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001327 }
1328 }
1329
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001330 // Just do a normal add. Pre-expand the operands to suppress folding.
1331 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1332 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001333 }
1334
Dan Gohman6ebfd722010-07-26 18:28:14 +00001335 // If we don't yet have a canonical IV, create one.
1336 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001337 // Create and insert the PHI node for the induction variable in the
1338 // specified loop.
1339 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001340 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001341 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1342 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001343 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001344
Owen Andersoneed707b2009-07-24 23:12:02 +00001345 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001346 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001347 BasicBlock *HP = *HPI;
1348 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001349 // Insert a unit add instruction right before the terminator
1350 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001351 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1352 "indvar.next",
1353 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001354 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001355 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001356 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001357 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001358 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001359 }
Gabor Greif76560182010-07-09 15:40:10 +00001360 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001361 }
1362
Dan Gohman6ebfd722010-07-26 18:28:14 +00001363 // {0,+,1} --> Insert a canonical induction variable into the loop!
1364 if (S->isAffine() && S->getOperand(1)->isOne()) {
1365 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1366 "IVs with types different from the canonical IV should "
1367 "already have been handled!");
1368 return CanonicalIV;
1369 }
1370
Dan Gohman4d8414f2009-06-13 16:25:49 +00001371 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001372
Chris Lattnerdf14a042005-10-30 06:24:33 +00001373 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001374 if (S->isAffine()) // {0,+,F} --> i*F
1375 return
1376 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001377 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001378 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001379 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001380 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001381
1382 // If this is a chain of recurrences, turn it into a closed form, using the
1383 // folders, then expandCodeFor the closed form. This allows the folders to
1384 // simplify the expression without having to build a bunch of special code
1385 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001386 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001387
Dan Gohman4d8414f2009-06-13 16:25:49 +00001388 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001389 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001390 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001391 if (isa<SCEVAddRecExpr>(Ext))
1392 NewS = Ext;
1393
Dan Gohman0bba49c2009-07-07 17:06:11 +00001394 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001395 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001396
Dan Gohman4d8414f2009-06-13 16:25:49 +00001397 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001398 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001399 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001400}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001401
Dan Gohman890f92b2009-04-18 17:56:28 +00001402Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001403 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001404 Value *V = expandCodeFor(S->getOperand(),
1405 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001406 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001407 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001408 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001409}
1410
Dan Gohman890f92b2009-04-18 17:56:28 +00001411Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *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.CreateZExt(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::visitSignExtendExpr(const SCEVSignExtendExpr *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.CreateSExt(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::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001430 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001431 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001432 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1433 // In the case of mixed integer and pointer types, do the
1434 // rest of the comparisons as integer.
1435 if (S->getOperand(i)->getType() != Ty) {
1436 Ty = SE.getEffectiveSCEVType(Ty);
1437 LHS = InsertNoopCastOfTo(LHS, Ty);
1438 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001439 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001440 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001441 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001442 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001443 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001444 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001445 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001446 // In the case of mixed integer and pointer types, cast the
1447 // final result back to the pointer type.
1448 if (LHS->getType() != S->getType())
1449 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001450 return LHS;
1451}
1452
Dan Gohman890f92b2009-04-18 17:56:28 +00001453Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001454 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001455 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001456 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1457 // In the case of mixed integer and pointer types, do the
1458 // rest of the comparisons as integer.
1459 if (S->getOperand(i)->getType() != Ty) {
1460 Ty = SE.getEffectiveSCEVType(Ty);
1461 LHS = InsertNoopCastOfTo(LHS, Ty);
1462 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001463 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001464 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001465 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001466 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001467 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001468 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001469 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001470 // In the case of mixed integer and pointer types, cast the
1471 // final result back to the pointer type.
1472 if (LHS->getType() != S->getType())
1473 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001474 return LHS;
1475}
1476
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001477Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001478 Instruction *IP) {
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001479 Builder.SetInsertPoint(IP->getParent(), IP);
1480 return expandCodeFor(SH, Ty);
1481}
1482
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001483Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001484 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001485 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001486 if (Ty) {
1487 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1488 "non-trivial casts should be done with the SCEVs directly!");
1489 V = InsertNoopCastOfTo(V, Ty);
1490 }
1491 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001492}
1493
Dan Gohman890f92b2009-04-18 17:56:28 +00001494Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001495 // Compute an insertion point for this SCEV object. Hoist the instructions
1496 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001497 Instruction *InsertPt = Builder.GetInsertPoint();
1498 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001499 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001500 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001501 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001502 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001503 InsertPt = Preheader->getTerminator();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001504 else {
1505 // LSR sets the insertion point for AddRec start/step values to the
1506 // block start to simplify value reuse, even though it's an invalid
1507 // position. SCEVExpander must correct for this in all cases.
1508 InsertPt = L->getHeader()->getFirstInsertionPt();
1509 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001510 } else {
1511 // If the SCEV is computable at this level, insert it into the header
1512 // after the PHIs (and after any other instructions that we've inserted
1513 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001514 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1515 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001516 while (InsertPt != Builder.GetInsertPoint()
1517 && (isInsertedInstruction(InsertPt)
1518 || isa<DbgInfoIntrinsic>(InsertPt))) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001519 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001520 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001521 break;
1522 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001523
Dan Gohman667d7872009-06-26 22:53:46 +00001524 // Check to see if we already expanded this here.
Andrew Trick1ba57692013-01-14 21:00:37 +00001525 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1526 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001527 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001528 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001529
1530 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1531 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1532 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001533
1534 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001535 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001536
Dan Gohman667d7872009-06-26 22:53:46 +00001537 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001538 //
1539 // This is independent of PostIncLoops. The mapped value simply materializes
1540 // the expression at this insertion point. If the mapped value happened to be
1541 // a postinc expansion, it could be reused by a non postinc user, but only if
1542 // its insertion point was already at the head of the loop.
1543 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001544
Dan Gohman45598552010-02-15 00:21:43 +00001545 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001546 return V;
1547}
Dan Gohman1d09de32009-06-05 16:35:53 +00001548
Dan Gohman1d826a72010-02-14 03:12:47 +00001549void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001550 if (!PostIncLoops.empty())
1551 InsertedPostIncValues.insert(I);
1552 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001553 InsertedValues.insert(I);
Dan Gohman1d826a72010-02-14 03:12:47 +00001554}
1555
Dan Gohman45598552010-02-15 00:21:43 +00001556void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman45598552010-02-15 00:21:43 +00001557 Builder.SetInsertPoint(BB, I);
1558}
1559
Dan Gohman1d09de32009-06-05 16:35:53 +00001560/// getOrInsertCanonicalInductionVariable - This method returns the
1561/// canonical induction variable of the specified type for the specified
1562/// loop (inserting one if there is none). A canonical induction variable
1563/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001564PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001565SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001566 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001567 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001568
1569 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001570 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001571 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001572 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001573
1574 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001575 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1576 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001577 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001578 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001579 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001580
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001581 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001582}
Andrew Trick20449412011-10-11 02:28:51 +00001583
Andrew Trick139f3332012-01-07 01:29:21 +00001584/// Sort values by integer width for replaceCongruentIVs.
1585static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001586 // Put pointers at the back and make sure pointer < pointer = false.
1587 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1588 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1589 return rhs->getType()->getPrimitiveSizeInBits()
1590 < lhs->getType()->getPrimitiveSizeInBits();
1591}
1592
Andrew Trick20449412011-10-11 02:28:51 +00001593/// replaceCongruentIVs - Check for congruent phis in this loop header and
1594/// replace them with their most canonical representative. Return the number of
1595/// phis eliminated.
1596///
1597/// This does not depend on any SCEVExpander state but should be used in
1598/// the same context that SCEVExpander is used.
1599unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotema04a4a72012-10-19 21:28:43 +00001600 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001601 const TargetTransformInfo *TTI) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001602 // Find integer phis in order of increasing width.
1603 SmallVector<PHINode*, 8> Phis;
1604 for (BasicBlock::iterator I = L->getHeader()->begin();
1605 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1606 Phis.push_back(Phi);
1607 }
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001608 if (TTI)
Andrew Trickee98aa82012-01-07 01:12:09 +00001609 std::sort(Phis.begin(), Phis.end(), width_descending);
1610
Andrew Trick20449412011-10-11 02:28:51 +00001611 unsigned NumElim = 0;
1612 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trickee98aa82012-01-07 01:12:09 +00001613 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1614 // so narrow phis can reuse them.
1615 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1616 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1617 PHINode *Phi = *PIter;
1618
Benjamin Kramer239fd442012-10-19 16:37:30 +00001619 // Fold constant phis. They may be congruent to other constant phis and
1620 // would confuse the logic below that expects proper IVs.
1621 if (Value *V = Phi->hasConstantValue()) {
1622 Phi->replaceAllUsesWith(V);
1623 DeadInsts.push_back(Phi);
1624 ++NumElim;
1625 DEBUG_WITH_TYPE(DebugType, dbgs()
1626 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1627 continue;
1628 }
1629
Andrew Trick20449412011-10-11 02:28:51 +00001630 if (!SE.isSCEVable(Phi->getType()))
1631 continue;
1632
1633 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1634 if (!OrigPhiRef) {
1635 OrigPhiRef = Phi;
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001636 if (Phi->getType()->isIntegerTy() && TTI
1637 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001638 // This phi can be freely truncated to the narrowest phi type. Map the
1639 // truncated expression to it so it will be reused for narrow types.
1640 const SCEV *TruncExpr =
1641 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1642 ExprToIVMap[TruncExpr] = Phi;
1643 }
Andrew Trick20449412011-10-11 02:28:51 +00001644 continue;
1645 }
1646
Andrew Trickee98aa82012-01-07 01:12:09 +00001647 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1648 // sense.
1649 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001650 continue;
1651
1652 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1653 Instruction *OrigInc =
1654 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1655 Instruction *IsomorphicInc =
1656 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1657
Andrew Trickee98aa82012-01-07 01:12:09 +00001658 // If this phi has the same width but is more canonical, replace the
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001659 // original with it. As part of the "more canonical" determination,
1660 // respect a prior decision to use an IV chain.
Andrew Trickee98aa82012-01-07 01:12:09 +00001661 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001662 && !(ChainedPhis.count(Phi)
1663 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1664 && (ChainedPhis.count(Phi)
1665 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trick20449412011-10-11 02:28:51 +00001666 std::swap(OrigPhiRef, Phi);
1667 std::swap(OrigInc, IsomorphicInc);
1668 }
1669 // Replacing the congruent phi is sufficient because acyclic redundancy
1670 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1671 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trick139f3332012-01-07 01:29:21 +00001672 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1673 // common case of a single IV increment so that DeleteDeadPHIs can remove
1674 // cycles that had postinc uses.
Andrew Trickee98aa82012-01-07 01:12:09 +00001675 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1676 IsomorphicInc->getType());
1677 if (OrigInc != IsomorphicInc
Andrew Trick64925c52012-01-10 01:45:08 +00001678 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001679 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1680 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trick20449412011-10-11 02:28:51 +00001681 DEBUG_WITH_TYPE(DebugType, dbgs()
1682 << "INDVARS: Eliminated congruent iv.inc: "
1683 << *IsomorphicInc << '\n');
Andrew Trickee98aa82012-01-07 01:12:09 +00001684 Value *NewInc = OrigInc;
1685 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trickdd1f22f2012-01-14 03:17:23 +00001686 Instruction *IP = isa<PHINode>(OrigInc)
1687 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1688 : OrigInc->getNextNode();
1689 IRBuilder<> Builder(IP);
Andrew Trickee98aa82012-01-07 01:12:09 +00001690 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1691 NewInc = Builder.
1692 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1693 }
1694 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trick20449412011-10-11 02:28:51 +00001695 DeadInsts.push_back(IsomorphicInc);
1696 }
1697 }
1698 DEBUG_WITH_TYPE(DebugType, dbgs()
1699 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1700 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001701 Value *NewIV = OrigPhiRef;
1702 if (OrigPhiRef->getType() != Phi->getType()) {
1703 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1704 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1705 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1706 }
1707 Phi->replaceAllUsesWith(NewIV);
Andrew Trick20449412011-10-11 02:28:51 +00001708 DeadInsts.push_back(Phi);
1709 }
1710 return NumElim;
1711}
Andrew Tricke08c3222012-07-13 23:33:10 +00001712
1713namespace {
1714// Search for a SCEV subexpression that is not safe to expand. Any expression
1715// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1716// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1717// instruction, but the important thing is that we prove the denominator is
1718// nonzero before expansion.
1719//
1720// IVUsers already checks that IV-derived expressions are safe. So this check is
1721// only needed when the expression includes some subexpression that is not IV
1722// derived.
1723//
1724// Currently, we only allow division by a nonzero constant here. If this is
1725// inadequate, we could easily allow division by SCEVUnknown by using
1726// ValueTracking to check isKnownNonZero().
1727struct SCEVFindUnsafe {
1728 bool IsUnsafe;
1729
1730 SCEVFindUnsafe(): IsUnsafe(false) {}
1731
1732 bool follow(const SCEV *S) {
1733 const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S);
1734 if (!D)
1735 return true;
1736 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1737 if (SC && !SC->getValue()->isZero())
1738 return true;
1739 IsUnsafe = true;
1740 return false;
1741 }
1742 bool isDone() const { return IsUnsafe; }
1743};
1744}
1745
1746namespace llvm {
1747bool isSafeToExpand(const SCEV *S) {
1748 SCEVFindUnsafe Search;
1749 visitAll(S, Search);
1750 return !Search.IsUnsafe;
1751}
1752}