blob: ea9de2f5a500f0963263975760a061bcda0753cd [file] [log] [blame]
Nate Begeman2bca4d92005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Begeman2bca4d92005-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 Begeman2bca4d92005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallSet.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000019#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000020#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/LLVMContext.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000025#include "llvm/Support/Debug.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000026
Nate Begeman2bca4d92005-07-30 00:12:19 +000027using namespace llvm;
28
Gabor Greif8e66a422010-07-09 16:42:04 +000029/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000030/// reusing an existing cast if a suitable one exists, moving an existing
31/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000032/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000033Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000034 Instruction::CastOps Op,
35 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000036 // This function must be called with the builder having a valid insertion
37 // point. It doesn't need to be the actual IP where the uses of the returned
38 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000039 // We use this precondition to produce a cast that will dominate all its
40 // uses. In particular, this is crucial for the case where the builder's
41 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000042 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000043 // where the uses will be added (only that it dominates it), we are
44 // not allowed to move it.
45 BasicBlock::iterator BIP = Builder.GetInsertPoint();
46
Rafael Espindola09a42012012-02-27 02:13:03 +000047 Instruction *Ret = NULL;
Rafael Espindola82d95752012-02-18 17:22:58 +000048
Dan Gohmand2772462010-06-19 13:25:23 +000049 // Check to see if there is already a cast!
50 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greif3b740e92010-07-09 16:39:02 +000051 UI != E; ++UI) {
52 User *U = *UI;
53 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000054 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000055 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000056 // If the cast isn't where we want it, create a new cast at IP.
57 // Likewise, do not reuse a cast at BIP because it must dominate
58 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000059 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000060 // Create a new cast, and leave the old cast in place in case
61 // it is being used as an insert point. Clear its operand
62 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000063 Ret = CastInst::Create(Op, V, Ty, "", IP);
64 Ret->takeName(CI);
65 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000066 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000067 break;
Dan Gohmand2772462010-06-19 13:25:23 +000068 }
Rafael Espindola09a42012012-02-27 02:13:03 +000069 Ret = CI;
70 break;
Dan Gohmand2772462010-06-19 13:25:23 +000071 }
Gabor Greif3b740e92010-07-09 16:39:02 +000072 }
Dan Gohmand2772462010-06-19 13:25:23 +000073
74 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000075 if (!Ret)
76 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
77
78 // We assert at the end of the function since IP might point to an
79 // instruction with different dominance properties than a cast
80 // (an invoke for example) and not dominate BIP (but the cast does).
81 assert(SE.DT->dominates(Ret, BIP));
82
83 rememberInstruction(Ret);
84 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000085}
86
Dan Gohman830fd382009-06-27 21:18:18 +000087/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
88/// which must be possible with a noop cast, doing what we can to share
89/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +000090Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +000091 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
92 assert((Op == Instruction::BitCast ||
93 Op == Instruction::PtrToInt ||
94 Op == Instruction::IntToPtr) &&
95 "InsertNoopCastOfTo cannot perform non-noop casts!");
96 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
97 "InsertNoopCastOfTo cannot change sizes!");
98
Dan Gohman0a40ad92009-04-16 03:18:22 +000099 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +0000100 if (Op == Instruction::BitCast) {
101 if (V->getType() == Ty)
102 return V;
103 if (CastInst *CI = dyn_cast<CastInst>(V)) {
104 if (CI->getOperand(0)->getType() == Ty)
105 return CI->getOperand(0);
106 }
107 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000108 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000109 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000110 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000111 if (CastInst *CI = dyn_cast<CastInst>(V))
112 if ((CI->getOpcode() == Instruction::PtrToInt ||
113 CI->getOpcode() == Instruction::IntToPtr) &&
114 SE.getTypeSizeInBits(CI->getType()) ==
115 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
116 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000117 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
118 if ((CE->getOpcode() == Instruction::PtrToInt ||
119 CE->getOpcode() == Instruction::IntToPtr) &&
120 SE.getTypeSizeInBits(CE->getType()) ==
121 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
122 return CE->getOperand(0);
123 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000124
Dan Gohmand2772462010-06-19 13:25:23 +0000125 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000126 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000127 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000128
Dan Gohmand2772462010-06-19 13:25:23 +0000129 // Cast the argument at the beginning of the entry block, after
130 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000131 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000132 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
133 while ((isa<BitCastInst>(IP) &&
134 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
135 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000136 isa<DbgInfoIntrinsic>(IP) ||
137 isa<LandingPadInst>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000138 ++IP;
139 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000140 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000141
Dan Gohmand2772462010-06-19 13:25:23 +0000142 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000143 Instruction *I = cast<Instruction>(V);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000144 BasicBlock::iterator IP = I; ++IP;
145 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
146 IP = II->getNormalDest()->begin();
Rafael Espindola82d95752012-02-18 17:22:58 +0000147 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000148 ++IP;
Dan Gohmand2772462010-06-19 13:25:23 +0000149 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000150}
151
Chris Lattnere71f1442007-04-13 05:04:18 +0000152/// InsertBinop - Insert the specified binary operator, doing a small amount
153/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000154Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
155 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000156 // Fold a binop with constant operands.
157 if (Constant *CLHS = dyn_cast<Constant>(LHS))
158 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000159 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000160
Chris Lattnere71f1442007-04-13 05:04:18 +0000161 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
162 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000163 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
164 // Scanning starts from the last instruction before the insertion point.
165 BasicBlock::iterator IP = Builder.GetInsertPoint();
166 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000167 --IP;
168 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000169 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
170 // generated code.
171 if (isa<DbgInfoIntrinsic>(IP))
172 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000173 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
174 IP->getOperand(1) == RHS)
175 return IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000176 if (IP == BlockBegin) break;
177 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000178 }
Dan Gohman830fd382009-06-27 21:18:18 +0000179
Dan Gohman29707de2010-03-03 05:29:13 +0000180 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000181 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
182 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000183
184 // Move the insertion point out of as many loops as we can.
185 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
186 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
187 BasicBlock *Preheader = L->getLoopPreheader();
188 if (!Preheader) break;
189
190 // Ok, move up a level.
191 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
192 }
193
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000194 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000195 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000196 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000197 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000198
Dan Gohmand195a222009-05-01 17:13:31 +0000199 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000200}
201
Dan Gohman17893622009-05-27 02:00:53 +0000202/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000203/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000204/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000205/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000206/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
207/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
208/// check to see if the divide was folded.
Dan Gohmanaf752342009-07-07 17:06:11 +0000209static bool FactorOutConstant(const SCEV *&S,
210 const SCEV *&Remainder,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000211 const SCEV *Factor,
212 ScalarEvolution &SE,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000213 const DataLayout *TD) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000214 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000215 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000216 return true;
217
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000218 // x/x == 1.
219 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000220 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000221 return true;
222 }
223
Dan Gohman291c2e02009-05-24 18:06:31 +0000224 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000225 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000226 // 0/x == 0.
227 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000228 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000229 // Check for divisibility.
230 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
231 ConstantInt *CI =
232 ConstantInt::get(SE.getContext(),
233 C->getValue()->getValue().sdiv(
234 FC->getValue()->getValue()));
235 // If the quotient is zero and the remainder is non-zero, reject
236 // the value at this scale. It will be considered for subsequent
237 // smaller scales.
238 if (!CI->isZero()) {
239 const SCEV *Div = SE.getConstant(CI);
240 S = Div;
241 Remainder =
242 SE.getAddExpr(Remainder,
243 SE.getConstant(C->getValue()->getValue().srem(
244 FC->getValue()->getValue())));
245 return true;
246 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000247 }
Dan Gohman17893622009-05-27 02:00:53 +0000248 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000249
250 // In a Mul, check if there is a constant operand which is a multiple
251 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000252 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
253 if (TD) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000254 // With DataLayout, the size is known. Check if there is a constant
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000255 // operand which is a multiple of the given factor. If so, we can
256 // factor it.
257 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
258 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
259 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohman00524492010-03-18 01:17:13 +0000260 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000261 NewMulOps[0] =
262 SE.getConstant(C->getValue()->getValue().sdiv(
263 FC->getValue()->getValue()));
264 S = SE.getMulExpr(NewMulOps);
265 return true;
266 }
267 } else {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000268 // Without DataLayout, check if Factor can be factored out of any of the
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000269 // Mul's operands. If so, we can just remove it.
270 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
271 const SCEV *SOp = M->getOperand(i);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000272 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000273 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
274 Remainder->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +0000275 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000276 NewMulOps[i] = SOp;
277 S = SE.getMulExpr(NewMulOps);
278 return true;
279 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000280 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000281 }
282 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000283
284 // In an AddRec, check if both start and step are divisible.
285 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000286 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000287 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000288 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman17893622009-05-27 02:00:53 +0000289 return false;
290 if (!StepRem->isZero())
291 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000292 const SCEV *Start = A->getStart();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000293 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman291c2e02009-05-24 18:06:31 +0000294 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000295 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
296 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000297 return true;
298 }
299
300 return false;
301}
302
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000303/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
304/// is the number of SCEVAddRecExprs present, which are kept at the end of
305/// the list.
306///
307static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000308 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000309 ScalarEvolution &SE) {
310 unsigned NumAddRecs = 0;
311 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
312 ++NumAddRecs;
313 // Group Ops into non-addrecs and addrecs.
314 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
315 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
316 // Let ScalarEvolution sort and simplify the non-addrecs list.
317 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000318 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000319 SE.getAddExpr(NoAddRecs);
320 // If it returned an add, use the operands. Otherwise it simplified
321 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000322 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000323 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000324 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000325 else if (!Sum->isZero())
326 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000327 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000328 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000329}
330
331/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
332/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
333/// This helps expose more opportunities for folding parts of the expressions
334/// into GEP indices.
335///
336static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000337 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000338 ScalarEvolution &SE) {
339 // Find the addrecs.
340 SmallVector<const SCEV *, 8> AddRecs;
341 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
342 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
343 const SCEV *Start = A->getStart();
344 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000345 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000346 AddRecs.push_back(SE.getAddRecExpr(Zero,
347 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000348 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000349 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000350 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
351 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000352 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000353 e += Add->getNumOperands();
354 } else {
355 Ops[i] = Start;
356 }
357 }
358 if (!AddRecs.empty()) {
359 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000360 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000361 // Resort the operand list, moving any constants to the front.
362 SimplifyAddOperands(Ops, Ty, SE);
363 }
364}
365
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000366/// expandAddToGEP - Expand an addition expression with a pointer type into
367/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
368/// BasicAliasAnalysis and other passes analyze the result. See the rules
369/// for getelementptr vs. inttoptr in
370/// http://llvm.org/docs/LangRef.html#pointeraliasing
371/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000372///
Dan Gohman510bffc2010-01-19 22:26:02 +0000373/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000374/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
375/// they may introduce pointer arithmetic which may not be safely converted
376/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000377///
378/// Design note: It might seem desirable for this function to be more
379/// loop-aware. If some of the indices are loop-invariant while others
380/// aren't, it might seem desirable to emit multiple GEPs, keeping the
381/// loop-invariant portions of the overall computation outside the loop.
382/// However, there are a few reasons this is not done here. Hoisting simple
383/// arithmetic is a low-level optimization that often isn't very
384/// important until late in the optimization process. In fact, passes
385/// like InstructionCombining will combine GEPs, even if it means
386/// pushing loop-invariant computation down into loops, so even if the
387/// GEPs were split here, the work would quickly be undone. The
388/// LoopStrengthReduction pass, which is usually run quite late (and
389/// after the last InstructionCombining pass), takes care of hoisting
390/// loop-invariant portions of expressions, after considering what
391/// can be folded using target addressing modes.
392///
Dan Gohmanaf752342009-07-07 17:06:11 +0000393Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
394 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000395 PointerType *PTy,
396 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000397 Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000398 Type *ElTy = PTy->getElementType();
Dan Gohman26494912009-05-19 02:15:55 +0000399 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000400 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000401 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000402
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000403 // Split AddRecs up into parts as either of the parts may be usable
404 // without the other.
405 SplitAddRecs(Ops, Ty, SE);
406
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000407 Type *IntPtrTy = SE.TD
408 ? SE.TD->getIntPtrType(PTy)
409 : Type::getInt64Ty(PTy->getContext());
410
Bob Wilson2107eb72009-12-04 01:33:04 +0000411 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000412 // operands into GEP indices, at each level. The first index in a GEP
413 // indexes into the array implied by the pointer operand; the rest of
414 // the indices index into the element or field type selected by the
415 // preceding index.
416 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000417 // If the scale size is not 0, attempt to factor out a scale for
418 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000419 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000420 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000421 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000422 if (!ElSize->isZero()) {
423 SmallVector<const SCEV *, 8> NewOps;
424 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
425 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000426 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000427 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
428 // Op now has ElSize factored out.
429 ScaledOps.push_back(Op);
430 if (!Remainder->isZero())
431 NewOps.push_back(Remainder);
432 AnyNonZeroIndices = true;
433 } else {
434 // The operand was not divisible, so add it to the list of operands
435 // we'll scan next iteration.
436 NewOps.push_back(Ops[i]);
437 }
Dan Gohman26494912009-05-19 02:15:55 +0000438 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000439 // If we made any changes, update Ops.
440 if (!ScaledOps.empty()) {
441 Ops = NewOps;
442 SimplifyAddOperands(Ops, Ty, SE);
443 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000444 }
Dan Gohman26494912009-05-19 02:15:55 +0000445 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000446
447 // Record the scaled array index for this level of the type. If
448 // we didn't find any operands that could be factored, tentatively
449 // assume that element zero was selected (since the zero offset
450 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000451 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000452 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000453 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
454 GepIndices.push_back(Scaled);
455
456 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000457 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000458 bool FoundFieldNo = false;
459 // An empty struct has no fields.
460 if (STy->getNumElements() == 0) break;
461 if (SE.TD) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000462 // With DataLayout, field offsets are known. See if a constant offset
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000463 // falls within any of the struct fields.
464 if (Ops.empty()) break;
Dan Gohman26494912009-05-19 02:15:55 +0000465 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
466 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
467 const StructLayout &SL = *SE.TD->getStructLayout(STy);
468 uint64_t FullOffset = C->getValue()->getZExtValue();
469 if (FullOffset < SL.getSizeInBytes()) {
470 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson55f1c092009-08-13 21:58:54 +0000471 GepIndices.push_back(
472 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman26494912009-05-19 02:15:55 +0000473 ElTy = STy->getTypeAtIndex(ElIdx);
474 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000475 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman26494912009-05-19 02:15:55 +0000476 AnyNonZeroIndices = true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000477 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000478 }
479 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000480 } else {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000481 // Without DataLayout, just check for an offsetof expression of the
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000482 // appropriate struct type.
483 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmancf913832010-01-28 02:15:55 +0000484 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattner229907c2011-07-18 04:54:35 +0000485 Type *CTy;
Dan Gohmancf913832010-01-28 02:15:55 +0000486 Constant *FieldNo;
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000487 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohmancf913832010-01-28 02:15:55 +0000488 GepIndices.push_back(FieldNo);
489 ElTy =
490 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000491 Ops[i] = SE.getConstant(Ty, 0);
492 AnyNonZeroIndices = true;
493 FoundFieldNo = true;
494 break;
495 }
Dan Gohmancf913832010-01-28 02:15:55 +0000496 }
Dan Gohman26494912009-05-19 02:15:55 +0000497 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000498 // If no struct field offsets were found, tentatively assume that
499 // field zero was selected (since the zero offset would obviously
500 // be folded away).
501 if (!FoundFieldNo) {
502 ElTy = STy->getTypeAtIndex(0u);
503 GepIndices.push_back(
504 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
505 }
Dan Gohman26494912009-05-19 02:15:55 +0000506 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000507
Chris Lattner229907c2011-07-18 04:54:35 +0000508 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000509 ElTy = ATy->getElementType();
510 else
511 break;
Dan Gohman26494912009-05-19 02:15:55 +0000512 }
513
Dan Gohman8b0a4192010-03-01 17:49:51 +0000514 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000515 // the base to i8* and do an ugly getelementptr with that. It's still
516 // better than ptrtoint+arithmetic+inttoptr at least.
517 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000518 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000519 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000520 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000521
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000522 assert(!isa<Instruction>(V) ||
Rafael Espindola94df2672012-02-26 02:19:19 +0000523 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000524
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000525 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000526 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000527
528 // Fold a GEP with constant operands.
529 if (Constant *CLHS = dyn_cast<Constant>(V))
530 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaded8db7d2011-07-21 14:31:17 +0000531 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000532
533 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
534 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000535 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
536 // Scanning starts from the last instruction before the insertion point.
537 BasicBlock::iterator IP = Builder.GetInsertPoint();
538 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000539 --IP;
540 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000541 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
542 // generated code.
543 if (isa<DbgInfoIntrinsic>(IP))
544 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000545 if (IP->getOpcode() == Instruction::GetElementPtr &&
546 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
547 return IP;
548 if (IP == BlockBegin) break;
549 }
550 }
551
Dan Gohman29707de2010-03-03 05:29:13 +0000552 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000553 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000554
555 // Move the insertion point out of as many loops as we can.
556 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
557 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
558 BasicBlock *Preheader = L->getLoopPreheader();
559 if (!Preheader) break;
560
561 // Ok, move up a level.
562 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
563 }
564
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000565 // Emit a GEP.
566 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000567 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000568
Dan Gohman26494912009-05-19 02:15:55 +0000569 return GEP;
570 }
571
Dan Gohman29707de2010-03-03 05:29:13 +0000572 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000573 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000574
575 // Move the insertion point out of as many loops as we can.
576 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
577 if (!L->isLoopInvariant(V)) break;
578
579 bool AnyIndexNotLoopInvariant = false;
580 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
581 E = GepIndices.end(); I != E; ++I)
582 if (!L->isLoopInvariant(*I)) {
583 AnyIndexNotLoopInvariant = true;
584 break;
585 }
586 if (AnyIndexNotLoopInvariant)
587 break;
588
589 BasicBlock *Preheader = L->getLoopPreheader();
590 if (!Preheader) break;
591
592 // Ok, move up a level.
593 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
594 }
595
Dan Gohman31a9b982009-07-28 01:40:03 +0000596 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
597 // because ScalarEvolution may have changed the address arithmetic to
598 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000599 Value *Casted = V;
600 if (V->getType() != PTy)
601 Casted = InsertNoopCastOfTo(Casted, PTy);
602 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000603 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000604 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000605 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000606 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000607
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000608 // Restore the original insert point.
609 Builder.restoreIP(SaveInsertPt);
610
Dan Gohman26494912009-05-19 02:15:55 +0000611 return expand(SE.getAddExpr(Ops));
612}
613
Dan Gohman29707de2010-03-03 05:29:13 +0000614/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
615/// SCEV expansion. If they are nested, this is the most nested. If they are
616/// neighboring, pick the later.
617static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
618 DominatorTree &DT) {
619 if (!A) return B;
620 if (!B) return A;
621 if (A->contains(B)) return B;
622 if (B->contains(A)) return A;
623 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
624 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
625 return A; // Arbitrarily break the tie.
626}
627
Dan Gohman8ea83d82010-11-18 00:34:22 +0000628/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000629/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000630const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
631 // Test whether we've already computed the most relevant loop for this SCEV.
632 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
633 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
634 if (!Pair.second)
635 return Pair.first->second;
636
Dan Gohman29707de2010-03-03 05:29:13 +0000637 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000638 // A constant has no relevant loops.
Dan Gohman29707de2010-03-03 05:29:13 +0000639 return 0;
640 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
641 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000642 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
643 // A non-instruction has no relevant loops.
Dan Gohman29707de2010-03-03 05:29:13 +0000644 return 0;
645 }
646 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
647 const Loop *L = 0;
648 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
649 L = AR->getLoop();
650 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
651 I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000652 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
653 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000654 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000655 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
656 const Loop *Result = getRelevantLoop(C->getOperand());
657 return RelevantLoops[C] = Result;
658 }
659 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
660 const Loop *Result =
661 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
662 getRelevantLoop(D->getRHS()),
663 *SE.DT);
664 return RelevantLoops[D] = Result;
665 }
Dan Gohman29707de2010-03-03 05:29:13 +0000666 llvm_unreachable("Unexpected SCEV type!");
667}
668
Dan Gohmanb29cda92010-04-15 17:08:50 +0000669namespace {
670
Dan Gohman29707de2010-03-03 05:29:13 +0000671/// LoopCompare - Compare loops by PickMostRelevantLoop.
672class LoopCompare {
673 DominatorTree &DT;
674public:
675 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
676
677 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
678 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000679 // Keep pointer operands sorted at the end.
680 if (LHS.second->getType()->isPointerTy() !=
681 RHS.second->getType()->isPointerTy())
682 return LHS.second->getType()->isPointerTy();
683
Dan Gohman29707de2010-03-03 05:29:13 +0000684 // Compare loops with PickMostRelevantLoop.
685 if (LHS.first != RHS.first)
686 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
687
688 // If one operand is a non-constant negative and the other is not,
689 // put the non-constant negative on the right so that a sub can
690 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000691 if (LHS.second->isNonConstantNegative()) {
692 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000693 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000694 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000695 return true;
696
697 // Otherwise they are equivalent according to this comparison.
698 return false;
699 }
700};
701
Dan Gohmanb29cda92010-04-15 17:08:50 +0000702}
703
Dan Gohman056857a2009-04-18 17:56:28 +0000704Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000705 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000706
Dan Gohman29707de2010-03-03 05:29:13 +0000707 // Collect all the add operands in a loop, along with their associated loops.
708 // Iterate in reverse so that constants are emitted last, all else equal, and
709 // so that pointer operands are inserted first, which the code below relies on
710 // to form more involved GEPs.
711 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
712 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
713 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000714 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000715
Dan Gohman29707de2010-03-03 05:29:13 +0000716 // Sort by loop. Use a stable sort so that constants follow non-constants and
717 // pointer operands precede non-pointer operands.
718 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000719
Dan Gohman29707de2010-03-03 05:29:13 +0000720 // Emit instructions to add all the operands. Hoist as much as possible
721 // out of loops, and form meaningful getelementptrs where possible.
722 Value *Sum = 0;
723 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
724 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
725 const Loop *CurLoop = I->first;
726 const SCEV *Op = I->second;
727 if (!Sum) {
728 // This is the first operand. Just expand it.
729 Sum = expand(Op);
730 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000731 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000732 // The running sum expression is a pointer. Try to form a getelementptr
733 // at this level with that as the base.
734 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000735 for (; I != E && I->first == CurLoop; ++I) {
736 // If the operand is SCEVUnknown and not instructions, peek through
737 // it, to enable more of it to be folded into the GEP.
738 const SCEV *X = I->second;
739 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
740 if (!isa<Instruction>(U->getValue()))
741 X = SE.getSCEV(U->getValue());
742 NewOps.push_back(X);
743 }
Dan Gohman29707de2010-03-03 05:29:13 +0000744 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000745 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000746 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000747 // Try to form a getelementptr. If the running sum is instructions,
748 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000749 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000750 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
751 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000752 for (++I; I != E && I->first == CurLoop; ++I)
753 NewOps.push_back(I->second);
754 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000755 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000756 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000757 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000758 Sum = InsertNoopCastOfTo(Sum, Ty);
759 Sum = InsertBinop(Instruction::Sub, Sum, W);
760 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000761 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000762 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000763 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000764 Sum = InsertNoopCastOfTo(Sum, Ty);
765 // Canonicalize a constant to the RHS.
766 if (isa<Constant>(Sum)) std::swap(Sum, W);
767 Sum = InsertBinop(Instruction::Add, Sum, W);
768 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000769 }
770 }
Dan Gohman29707de2010-03-03 05:29:13 +0000771
772 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000773}
Dan Gohman26494912009-05-19 02:15:55 +0000774
Dan Gohman056857a2009-04-18 17:56:28 +0000775Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000776 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000777
Dan Gohman29707de2010-03-03 05:29:13 +0000778 // Collect all the mul operands in a loop, along with their associated loops.
779 // Iterate in reverse so that constants are emitted last, all else equal.
780 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
781 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
782 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000783 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000784
Dan Gohman29707de2010-03-03 05:29:13 +0000785 // Sort by loop. Use a stable sort so that constants follow non-constants.
786 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
787
788 // Emit instructions to mul all the operands. Hoist as much as possible
789 // out of loops.
790 Value *Prod = 0;
791 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
792 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
793 const SCEV *Op = I->second;
794 if (!Prod) {
795 // This is the first operand. Just expand it.
796 Prod = expand(Op);
797 ++I;
798 } else if (Op->isAllOnesValue()) {
799 // Instead of doing a multiply by negative one, just do a negate.
800 Prod = InsertNoopCastOfTo(Prod, Ty);
801 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
802 ++I;
803 } else {
804 // A simple mul.
805 Value *W = expandCodeFor(Op, Ty);
806 Prod = InsertNoopCastOfTo(Prod, Ty);
807 // Canonicalize a constant to the RHS.
808 if (isa<Constant>(Prod)) std::swap(Prod, W);
809 Prod = InsertBinop(Instruction::Mul, Prod, W);
810 ++I;
811 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000812 }
813
Dan Gohman29707de2010-03-03 05:29:13 +0000814 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000815}
816
Dan Gohman056857a2009-04-18 17:56:28 +0000817Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000818 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000819
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000820 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000821 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000822 const APInt &RHS = SC->getValue()->getValue();
823 if (RHS.isPowerOf2())
824 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000825 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000826 }
827
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000828 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000829 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000830}
831
Dan Gohman291c2e02009-05-24 18:06:31 +0000832/// Move parts of Base into Rest to leave Base with the minimal
833/// expression that provides a pointer operand suitable for a
834/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000835static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000836 ScalarEvolution &SE) {
837 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
838 Base = A->getStart();
839 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000840 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000841 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000842 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000843 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000844 }
845 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
846 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000847 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000848 NewAddOps.back() = Rest;
849 Rest = SE.getAddExpr(NewAddOps);
850 ExposePointerBase(Base, Rest, SE);
851 }
852}
853
Andrew Trick7fb669a2011-10-07 23:46:21 +0000854/// Determine if this is a well-behaved chain of instructions leading back to
855/// the PHI. If so, it may be reused by expanded expressions.
856bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
857 const Loop *L) {
858 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
859 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
860 return false;
861 // If any of the operands don't dominate the insert position, bail.
862 // Addrec operands are always loop-invariant, so this can only happen
863 // if there are instructions which haven't been hoisted.
864 if (L == IVIncInsertLoop) {
865 for (User::op_iterator OI = IncV->op_begin()+1,
866 OE = IncV->op_end(); OI != OE; ++OI)
867 if (Instruction *OInst = dyn_cast<Instruction>(OI))
868 if (!SE.DT->dominates(OInst, IVIncInsertPos))
869 return false;
870 }
871 // Advance to the next instruction.
872 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
873 if (!IncV)
874 return false;
875
876 if (IncV->mayHaveSideEffects())
877 return false;
878
879 if (IncV != PN)
880 return true;
881
882 return isNormalAddRecExprPHI(PN, IncV, L);
883}
884
Andrew Trickc908b432012-01-20 07:41:13 +0000885/// getIVIncOperand returns an induction variable increment's induction
886/// variable operand.
887///
888/// If allowScale is set, any type of GEP is allowed as long as the nonIV
889/// operands dominate InsertPos.
890///
891/// If allowScale is not set, ensure that a GEP increment conforms to one of the
892/// simple patterns generated by getAddRecExprPHILiterally and
893/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
894Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
895 Instruction *InsertPos,
896 bool allowScale) {
897 if (IncV == InsertPos)
898 return NULL;
899
900 switch (IncV->getOpcode()) {
901 default:
902 return NULL;
903 // Check for a simple Add/Sub or GEP of a loop invariant step.
904 case Instruction::Add:
905 case Instruction::Sub: {
906 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindola94df2672012-02-26 02:19:19 +0000907 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000908 return dyn_cast<Instruction>(IncV->getOperand(0));
909 return NULL;
910 }
911 case Instruction::BitCast:
912 return dyn_cast<Instruction>(IncV->getOperand(0));
913 case Instruction::GetElementPtr:
914 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
915 I != E; ++I) {
916 if (isa<Constant>(*I))
917 continue;
918 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000919 if (!SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000920 return NULL;
921 }
922 if (allowScale) {
923 // allow any kind of GEP as long as it can be hoisted.
924 continue;
925 }
926 // This must be a pointer addition of constants (pretty), which is already
927 // handled, or some number of address-size elements (ugly). Ugly geps
928 // have 2 operands. i1* is used by the expander to represent an
929 // address-size element.
930 if (IncV->getNumOperands() != 2)
931 return NULL;
932 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
933 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
934 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
935 return NULL;
936 break;
937 }
938 return dyn_cast<Instruction>(IncV->getOperand(0));
939 }
940}
941
942/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
943/// it available to other uses in this loop. Recursively hoist any operands,
944/// until we reach a value that dominates InsertPos.
945bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000946 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000947 return true;
948
949 // InsertPos must itself dominate IncV so that IncV's new position satisfies
950 // its existing users.
Andrew Tricka7a3de12012-05-22 17:39:59 +0000951 if (isa<PHINode>(InsertPos)
952 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000953 return false;
954
955 // Check that the chain of IV operands leading back to Phi can be hoisted.
956 SmallVector<Instruction*, 4> IVIncs;
957 for(;;) {
958 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
959 if (!Oper)
960 return false;
961 // IncV is safe to hoist.
962 IVIncs.push_back(IncV);
963 IncV = Oper;
Rafael Espindola94df2672012-02-26 02:19:19 +0000964 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000965 break;
966 }
967 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
968 E = IVIncs.rend(); I != E; ++I) {
969 (*I)->moveBefore(InsertPos);
970 }
971 return true;
972}
973
Andrew Trick7fb669a2011-10-07 23:46:21 +0000974/// Determine if this cyclic phi is in a form that would have been generated by
975/// LSR. We don't care if the phi was actually expanded in this pass, as long
976/// as it is in a low-cost form, for example, no implied multiplication. This
977/// should match any patterns generated by getAddRecExprPHILiterally and
978/// expandAddtoGEP.
979bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000980 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000981 for(Instruction *IVOper = IncV;
982 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
983 /*allowScale=*/false));) {
984 if (IVOper == PN)
985 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000986 }
Andrew Trickc908b432012-01-20 07:41:13 +0000987 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000988}
989
Andrew Trickceafa2c2011-11-30 06:07:54 +0000990/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
991/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
992/// need to materialize IV increments elsewhere to handle difficult situations.
993Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
994 Type *ExpandTy, Type *IntTy,
995 bool useSubtract) {
996 Value *IncV;
997 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
998 if (ExpandTy->isPointerTy()) {
999 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1000 // If the step isn't constant, don't use an implicitly scaled GEP, because
1001 // that would require a multiply inside the loop.
1002 if (!isa<ConstantInt>(StepV))
1003 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1004 GEPPtrTy->getAddressSpace());
1005 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1006 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1007 if (IncV->getType() != PN->getType()) {
1008 IncV = Builder.CreateBitCast(IncV, PN->getType());
1009 rememberInstruction(IncV);
1010 }
1011 } else {
1012 IncV = useSubtract ?
1013 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1014 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1015 rememberInstruction(IncV);
1016 }
1017 return IncV;
1018}
1019
Dan Gohman51ad99d2010-01-21 02:09:26 +00001020/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1021/// the base addrec, which is the addrec without any non-loop-dominating
1022/// values, and return the PHI.
1023PHINode *
1024SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1025 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001026 Type *ExpandTy,
1027 Type *IntTy) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001028 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001029
Dan Gohman51ad99d2010-01-21 02:09:26 +00001030 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001031 BasicBlock *LatchBlock = L->getLoopLatch();
1032 if (LatchBlock) {
1033 for (BasicBlock::iterator I = L->getHeader()->begin();
1034 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1035 if (!SE.isSCEVable(PN->getType()) ||
1036 (SE.getEffectiveSCEVType(PN->getType()) !=
1037 SE.getEffectiveSCEVType(Normalized->getType())) ||
1038 SE.getSCEV(PN) != Normalized)
1039 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001040
Andrew Trick7fb669a2011-10-07 23:46:21 +00001041 Instruction *IncV =
1042 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman148a9722010-02-16 00:20:08 +00001043
Andrew Trick7fb669a2011-10-07 23:46:21 +00001044 if (LSRMode) {
Andrew Trickfd4ca0f2011-10-15 06:19:55 +00001045 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001046 continue;
Andrew Trickc908b432012-01-20 07:41:13 +00001047 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1048 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001049 }
Andrew Trick7fb669a2011-10-07 23:46:21 +00001050 else {
1051 if (!isNormalAddRecExprPHI(PN, IncV, L))
1052 continue;
Andrew Trickc908b432012-01-20 07:41:13 +00001053 if (L == IVIncInsertLoop)
1054 do {
1055 if (SE.DT->dominates(IncV, IVIncInsertPos))
1056 break;
1057 // Make sure the increment is where we want it. But don't move it
1058 // down past a potential existing post-inc user.
1059 IncV->moveBefore(IVIncInsertPos);
1060 IVIncInsertPos = IncV;
1061 IncV = cast<Instruction>(IncV->getOperand(0));
1062 } while (IncV != PN);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001063 }
1064 // Ok, the add recurrence looks usable.
1065 // Remember this PHI, even in post-inc mode.
1066 InsertedValues.insert(PN);
1067 // Remember the increment.
1068 rememberInstruction(IncV);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001069 return PN;
1070 }
1071 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001072
1073 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001074 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001075
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001076 // Another AddRec may need to be recursively expanded below. For example, if
1077 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1078 // loop. Remove this loop from the PostIncLoops set before expanding such
1079 // AddRecs. Otherwise, we cannot find a valid position for the step
1080 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1081 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1082 // so it's not worth implementing SmallPtrSet::swap.
1083 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1084 PostIncLoops.clear();
1085
Dan Gohman51ad99d2010-01-21 02:09:26 +00001086 // Expand code for the start value.
1087 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1088 L->getHeader()->begin());
1089
Andrew Trick244e2c32011-07-16 00:59:39 +00001090 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001091 assert(!isa<Instruction>(StartV) ||
1092 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1093 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001094
Andrew Trickceafa2c2011-11-30 06:07:54 +00001095 // Expand code for the step value. Do this before creating the PHI so that PHI
1096 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001097 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001098 // If the stride is negative, insert a sub instead of an add for the increment
1099 // (unless it's a constant, because subtracts of constants are canonicalized
1100 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001101 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001102 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001103 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001104 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001105 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1106
1107 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001108 BasicBlock *Header = L->getHeader();
1109 Builder.SetInsertPoint(Header, Header->begin());
1110 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001111 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001112 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001113 rememberInstruction(PN);
1114
1115 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001116 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001117 BasicBlock *Pred = *HPI;
1118
1119 // Add a start value.
1120 if (!L->contains(Pred)) {
1121 PN->addIncoming(StartV, Pred);
1122 continue;
1123 }
1124
Andrew Trickceafa2c2011-11-30 06:07:54 +00001125 // Create a step value and add it to the PHI.
1126 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1127 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001128 Instruction *InsertPos = L == IVIncInsertLoop ?
1129 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001130 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001131 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Andrew Trick8eaae282013-07-14 02:50:07 +00001132 if (isa<OverflowingBinaryOperator>(IncV)) {
1133 if (Normalized->getNoWrapFlags(SCEV::FlagNUW))
1134 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1135 if (Normalized->getNoWrapFlags(SCEV::FlagNSW))
1136 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1137 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001138 PN->addIncoming(IncV, Pred);
1139 }
1140
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001141 // After expanding subexpressions, restore the PostIncLoops set so the caller
1142 // can ensure that IVIncrement dominates the current uses.
1143 PostIncLoops = SavedPostIncLoops;
1144
Dan Gohman51ad99d2010-01-21 02:09:26 +00001145 // Remember this PHI, even in post-inc mode.
1146 InsertedValues.insert(PN);
1147
1148 return PN;
1149}
1150
1151Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001152 Type *STy = S->getType();
1153 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001154 const Loop *L = S->getLoop();
1155
1156 // Determine a normalized form of this expression, which is the expression
1157 // before any post-inc adjustment is made.
1158 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001159 if (PostIncLoops.count(L)) {
1160 PostIncLoopSet Loops;
1161 Loops.insert(L);
1162 Normalized =
1163 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1164 Loops, SE, *SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001165 }
1166
1167 // Strip off any non-loop-dominating component from the addrec start.
1168 const SCEV *Start = Normalized->getStart();
1169 const SCEV *PostLoopOffset = 0;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001170 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001171 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001172 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001173 Normalized = cast<SCEVAddRecExpr>(
1174 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1175 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001176 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001177 }
1178
1179 // Strip off any non-loop-dominating component from the addrec step.
1180 const SCEV *Step = Normalized->getStepRecurrence(SE);
1181 const SCEV *PostLoopScale = 0;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001182 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001183 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001184 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001185 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001186 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1187 Start, Step, Normalized->getLoop(),
1188 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001189 }
1190
1191 // Expand the core addrec. If we need post-loop scaling, force it to
1192 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001193 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohman51ad99d2010-01-21 02:09:26 +00001194 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1195
Dan Gohman8b0a4192010-03-01 17:49:51 +00001196 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001197 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001198 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001199 Result = PN;
1200 else {
1201 // In PostInc mode, use the post-incremented value.
1202 BasicBlock *LatchBlock = L->getLoopLatch();
1203 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1204 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001205
1206 // For an expansion to use the postinc form, the client must call
1207 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1208 // or dominated by IVIncInsertPos.
Andrew Trickceafa2c2011-11-30 06:07:54 +00001209 if (isa<Instruction>(Result)
1210 && !SE.DT->dominates(cast<Instruction>(Result),
1211 Builder.GetInsertPoint())) {
1212 // The induction variable's postinc expansion does not dominate this use.
1213 // IVUsers tries to prevent this case, so it is rare. However, it can
1214 // happen when an IVUser outside the loop is not dominated by the latch
1215 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1216 // all cases. Consider a phi outide whose operand is replaced during
1217 // expansion with the value of the postinc user. Without fundamentally
1218 // changing the way postinc users are tracked, the only remedy is
1219 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1220 // but hopefully expandCodeFor handles that.
1221 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001222 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001223 if (useSubtract)
1224 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001225 Value *StepV;
1226 {
1227 // Expand the step somewhere that dominates the loop header.
1228 BuilderType::InsertPointGuard Guard(Builder);
1229 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1230 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001231 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1232 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001233 }
1234
1235 // Re-apply any non-loop-dominating scale.
1236 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001237 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001238 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001239 Result = Builder.CreateMul(Result,
1240 expandCodeFor(PostLoopScale, IntTy));
1241 rememberInstruction(Result);
1242 }
1243
1244 // Re-apply any non-loop-dominating offset.
1245 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001246 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001247 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1248 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1249 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001250 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001251 Result = Builder.CreateAdd(Result,
1252 expandCodeFor(PostLoopOffset, IntTy));
1253 rememberInstruction(Result);
1254 }
1255 }
1256
1257 return Result;
1258}
1259
Dan Gohman056857a2009-04-18 17:56:28 +00001260Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001261 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1262
Chris Lattner229907c2011-07-18 04:54:35 +00001263 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001264 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001265
Dan Gohman426901a2009-06-13 16:25:49 +00001266 // First check for an existing canonical IV in a suitable type.
1267 PHINode *CanonicalIV = 0;
1268 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001269 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001270 CanonicalIV = PN;
1271
1272 // Rewrite an AddRec in terms of the canonical induction variable, if
1273 // its type is more narrow.
1274 if (CanonicalIV &&
1275 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1276 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001277 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1278 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1279 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001280 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001281 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001282 BasicBlock::iterator NewInsertPt =
Chris Lattnera48f44d2009-12-03 00:50:42 +00001283 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001284 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001285 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1286 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001287 ++NewInsertPt;
Dan Gohman426901a2009-06-13 16:25:49 +00001288 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1289 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001290 return V;
1291 }
1292
Nate Begeman2bca4d92005-07-30 00:12:19 +00001293 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001294 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001295 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001296 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001297 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1298 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001299
1300 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1301 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001302 const SCEV *Base = S->getStart();
1303 const SCEV *RestArray[1] = { Rest };
1304 // Dig into the expression to find the pointer base for a GEP.
1305 ExposePointerBase(Base, RestArray[0], SE);
1306 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001307 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001308 // Make sure the Base isn't something exotic, such as a multiplied
1309 // or divided pointer value. In those cases, the result type isn't
1310 // actually a pointer type.
1311 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1312 Value *StartV = expand(Base);
1313 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1314 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001315 }
1316 }
1317
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001318 // Just do a normal add. Pre-expand the operands to suppress folding.
1319 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1320 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001321 }
1322
Dan Gohmancd838702010-07-26 18:28:14 +00001323 // If we don't yet have a canonical IV, create one.
1324 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001325 // Create and insert the PHI node for the induction variable in the
1326 // specified loop.
1327 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001328 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001329 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1330 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001331 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001332
Hal Finkel3f5279c2013-08-18 00:16:23 +00001333 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001334 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001335 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001336 BasicBlock *HP = *HPI;
Hal Finkel3f5279c2013-08-18 00:16:23 +00001337 if (!PredSeen.insert(HP))
1338 continue;
1339
Gabor Greife82532a2010-07-09 15:40:10 +00001340 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001341 // Insert a unit add instruction right before the terminator
1342 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001343 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1344 "indvar.next",
1345 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001346 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001347 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001348 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001349 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001350 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001351 }
Gabor Greife82532a2010-07-09 15:40:10 +00001352 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001353 }
1354
Dan Gohmancd838702010-07-26 18:28:14 +00001355 // {0,+,1} --> Insert a canonical induction variable into the loop!
1356 if (S->isAffine() && S->getOperand(1)->isOne()) {
1357 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1358 "IVs with types different from the canonical IV should "
1359 "already have been handled!");
1360 return CanonicalIV;
1361 }
1362
Dan Gohman426901a2009-06-13 16:25:49 +00001363 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001364
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001365 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001366 if (S->isAffine()) // {0,+,F} --> i*F
1367 return
1368 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001369 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001370 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001371 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001372 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001373
1374 // If this is a chain of recurrences, turn it into a closed form, using the
1375 // folders, then expandCodeFor the closed form. This allows the folders to
1376 // simplify the expression without having to build a bunch of special code
1377 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001378 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001379
Dan Gohman426901a2009-06-13 16:25:49 +00001380 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001381 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001382 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001383 if (isa<SCEVAddRecExpr>(Ext))
1384 NewS = Ext;
1385
Dan Gohmanaf752342009-07-07 17:06:11 +00001386 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001387 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001388
Dan Gohman426901a2009-06-13 16:25:49 +00001389 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001390 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001391 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001392}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001393
Dan Gohman056857a2009-04-18 17:56:28 +00001394Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001395 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001396 Value *V = expandCodeFor(S->getOperand(),
1397 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001398 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001399 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001400 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001401}
1402
Dan Gohman056857a2009-04-18 17:56:28 +00001403Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001404 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001405 Value *V = expandCodeFor(S->getOperand(),
1406 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001407 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001408 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001409 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001410}
1411
Dan Gohman056857a2009-04-18 17:56:28 +00001412Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001413 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001414 Value *V = expandCodeFor(S->getOperand(),
1415 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001416 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001417 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001418 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001419}
1420
Dan Gohman056857a2009-04-18 17:56:28 +00001421Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001422 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001423 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001424 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1425 // In the case of mixed integer and pointer types, do the
1426 // rest of the comparisons as integer.
1427 if (S->getOperand(i)->getType() != Ty) {
1428 Ty = SE.getEffectiveSCEVType(Ty);
1429 LHS = InsertNoopCastOfTo(LHS, Ty);
1430 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001431 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001432 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001433 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001434 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001435 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001436 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001437 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001438 // In the case of mixed integer and pointer types, cast the
1439 // final result back to the pointer type.
1440 if (LHS->getType() != S->getType())
1441 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001442 return LHS;
1443}
1444
Dan Gohman056857a2009-04-18 17:56:28 +00001445Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001446 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001447 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001448 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1449 // In the case of mixed integer and pointer types, do the
1450 // rest of the comparisons as integer.
1451 if (S->getOperand(i)->getType() != Ty) {
1452 Ty = SE.getEffectiveSCEVType(Ty);
1453 LHS = InsertNoopCastOfTo(LHS, Ty);
1454 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001455 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001456 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001457 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001458 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001459 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001460 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001461 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001462 // In the case of mixed integer and pointer types, cast the
1463 // final result back to the pointer type.
1464 if (LHS->getType() != S->getType())
1465 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001466 return LHS;
1467}
1468
Chris Lattner229907c2011-07-18 04:54:35 +00001469Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001470 Instruction *IP) {
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001471 Builder.SetInsertPoint(IP->getParent(), IP);
1472 return expandCodeFor(SH, Ty);
1473}
1474
Chris Lattner229907c2011-07-18 04:54:35 +00001475Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001476 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001477 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001478 if (Ty) {
1479 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1480 "non-trivial casts should be done with the SCEVs directly!");
1481 V = InsertNoopCastOfTo(V, Ty);
1482 }
1483 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001484}
1485
Dan Gohman056857a2009-04-18 17:56:28 +00001486Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001487 // Compute an insertion point for this SCEV object. Hoist the instructions
1488 // as far out in the loop nest as possible.
Dan Gohman830fd382009-06-27 21:18:18 +00001489 Instruction *InsertPt = Builder.GetInsertPoint();
1490 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001491 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001492 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001493 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001494 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001495 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001496 else {
1497 // LSR sets the insertion point for AddRec start/step values to the
1498 // block start to simplify value reuse, even though it's an invalid
1499 // position. SCEVExpander must correct for this in all cases.
1500 InsertPt = L->getHeader()->getFirstInsertionPt();
1501 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001502 } else {
1503 // If the SCEV is computable at this level, insert it into the header
1504 // after the PHIs (and after any other instructions that we've inserted
1505 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001506 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1507 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickc908b432012-01-20 07:41:13 +00001508 while (InsertPt != Builder.GetInsertPoint()
1509 && (isInsertedInstruction(InsertPt)
1510 || isa<DbgInfoIntrinsic>(InsertPt))) {
Chris Lattnera48f44d2009-12-03 00:50:42 +00001511 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Andrew Trickc908b432012-01-20 07:41:13 +00001512 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001513 break;
1514 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001515
Dan Gohmandaafbe62009-06-26 22:53:46 +00001516 // Check to see if we already expanded this here.
Andrew Trickd4e1b5e2013-01-14 21:00:37 +00001517 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1518 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001519 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001520 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001521
Benjamin Kramer6e931522013-09-30 15:40:17 +00001522 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman830fd382009-06-27 21:18:18 +00001523 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001524
1525 // Expand the expression into instructions.
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001526 Value *V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001527
Dan Gohmandaafbe62009-06-26 22:53:46 +00001528 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001529 //
1530 // This is independent of PostIncLoops. The mapped value simply materializes
1531 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001532 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001533 // its insertion point was already at the head of the loop.
1534 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001535 return V;
1536}
Dan Gohman63964b52009-06-05 16:35:53 +00001537
Dan Gohman6b751732010-02-14 03:12:47 +00001538void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001539 if (!PostIncLoops.empty())
1540 InsertedPostIncValues.insert(I);
1541 else
Dan Gohman6b751732010-02-14 03:12:47 +00001542 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001543}
1544
Dan Gohman63964b52009-06-05 16:35:53 +00001545/// getOrInsertCanonicalInductionVariable - This method returns the
1546/// canonical induction variable of the specified type for the specified
1547/// loop (inserting one if there is none). A canonical induction variable
1548/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001549PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001550SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001551 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001552 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001553
1554 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001555 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001556 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001557 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001558
1559 // Emit code for it.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001560 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman4fd92432010-07-20 16:44:52 +00001561 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman31158752010-07-20 16:46:58 +00001562
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001563 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001564}
Andrew Trickf9201c52011-10-11 02:28:51 +00001565
Andrew Trickf730f392012-01-07 01:29:21 +00001566/// Sort values by integer width for replaceCongruentIVs.
1567static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001568 // Put pointers at the back and make sure pointer < pointer = false.
1569 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1570 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1571 return rhs->getType()->getPrimitiveSizeInBits()
1572 < lhs->getType()->getPrimitiveSizeInBits();
1573}
1574
Andrew Trickf9201c52011-10-11 02:28:51 +00001575/// replaceCongruentIVs - Check for congruent phis in this loop header and
1576/// replace them with their most canonical representative. Return the number of
1577/// phis eliminated.
1578///
1579/// This does not depend on any SCEVExpander state but should be used in
1580/// the same context that SCEVExpander is used.
1581unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001582 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001583 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001584 // Find integer phis in order of increasing width.
1585 SmallVector<PHINode*, 8> Phis;
1586 for (BasicBlock::iterator I = L->getHeader()->begin();
1587 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1588 Phis.push_back(Phi);
1589 }
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001590 if (TTI)
Andrew Trick5adedf52012-01-07 01:12:09 +00001591 std::sort(Phis.begin(), Phis.end(), width_descending);
1592
Andrew Trickf9201c52011-10-11 02:28:51 +00001593 unsigned NumElim = 0;
1594 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick5adedf52012-01-07 01:12:09 +00001595 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1596 // so narrow phis can reuse them.
1597 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1598 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1599 PHINode *Phi = *PIter;
1600
Benjamin Kramera225ed82012-10-19 16:37:30 +00001601 // Fold constant phis. They may be congruent to other constant phis and
1602 // would confuse the logic below that expects proper IVs.
1603 if (Value *V = Phi->hasConstantValue()) {
1604 Phi->replaceAllUsesWith(V);
1605 DeadInsts.push_back(Phi);
1606 ++NumElim;
1607 DEBUG_WITH_TYPE(DebugType, dbgs()
1608 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1609 continue;
1610 }
1611
Andrew Trickf9201c52011-10-11 02:28:51 +00001612 if (!SE.isSCEVable(Phi->getType()))
1613 continue;
1614
1615 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1616 if (!OrigPhiRef) {
1617 OrigPhiRef = Phi;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001618 if (Phi->getType()->isIntegerTy() && TTI
1619 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001620 // This phi can be freely truncated to the narrowest phi type. Map the
1621 // truncated expression to it so it will be reused for narrow types.
1622 const SCEV *TruncExpr =
1623 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1624 ExprToIVMap[TruncExpr] = Phi;
1625 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001626 continue;
1627 }
1628
Andrew Trick5adedf52012-01-07 01:12:09 +00001629 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1630 // sense.
1631 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001632 continue;
1633
1634 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1635 Instruction *OrigInc =
1636 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1637 Instruction *IsomorphicInc =
1638 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1639
Andrew Trick5adedf52012-01-07 01:12:09 +00001640 // If this phi has the same width but is more canonical, replace the
Andrew Trickc908b432012-01-20 07:41:13 +00001641 // original with it. As part of the "more canonical" determination,
1642 // respect a prior decision to use an IV chain.
Andrew Trick5adedf52012-01-07 01:12:09 +00001643 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickc908b432012-01-20 07:41:13 +00001644 && !(ChainedPhis.count(Phi)
1645 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1646 && (ChainedPhis.count(Phi)
1647 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001648 std::swap(OrigPhiRef, Phi);
1649 std::swap(OrigInc, IsomorphicInc);
1650 }
1651 // Replacing the congruent phi is sufficient because acyclic redundancy
1652 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1653 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trickf730f392012-01-07 01:29:21 +00001654 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1655 // common case of a single IV increment so that DeleteDeadPHIs can remove
1656 // cycles that had postinc uses.
Andrew Trick5adedf52012-01-07 01:12:09 +00001657 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1658 IsomorphicInc->getType());
1659 if (OrigInc != IsomorphicInc
Andrew Trickd5d2db92012-01-10 01:45:08 +00001660 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickc908b432012-01-20 07:41:13 +00001661 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1662 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001663 DEBUG_WITH_TYPE(DebugType, dbgs()
1664 << "INDVARS: Eliminated congruent iv.inc: "
1665 << *IsomorphicInc << '\n');
Andrew Trick5adedf52012-01-07 01:12:09 +00001666 Value *NewInc = OrigInc;
1667 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trick23ef0d62012-01-14 03:17:23 +00001668 Instruction *IP = isa<PHINode>(OrigInc)
1669 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1670 : OrigInc->getNextNode();
1671 IRBuilder<> Builder(IP);
Andrew Trick5adedf52012-01-07 01:12:09 +00001672 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1673 NewInc = Builder.
1674 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1675 }
1676 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trickf9201c52011-10-11 02:28:51 +00001677 DeadInsts.push_back(IsomorphicInc);
1678 }
1679 }
1680 DEBUG_WITH_TYPE(DebugType, dbgs()
1681 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1682 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001683 Value *NewIV = OrigPhiRef;
1684 if (OrigPhiRef->getType() != Phi->getType()) {
1685 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1686 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1687 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1688 }
1689 Phi->replaceAllUsesWith(NewIV);
Andrew Trickf9201c52011-10-11 02:28:51 +00001690 DeadInsts.push_back(Phi);
1691 }
1692 return NumElim;
1693}
Andrew Trick653513b2012-07-13 23:33:10 +00001694
1695namespace {
1696// Search for a SCEV subexpression that is not safe to expand. Any expression
1697// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1698// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1699// instruction, but the important thing is that we prove the denominator is
1700// nonzero before expansion.
1701//
1702// IVUsers already checks that IV-derived expressions are safe. So this check is
1703// only needed when the expression includes some subexpression that is not IV
1704// derived.
1705//
1706// Currently, we only allow division by a nonzero constant here. If this is
1707// inadequate, we could easily allow division by SCEVUnknown by using
1708// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00001709//
1710// We cannot generally expand recurrences unless the step dominates the loop
1711// header. The expander handles the special case of affine recurrences by
1712// scaling the recurrence outside the loop, but this technique isn't generally
1713// applicable. Expanding a nested recurrence outside a loop requires computing
1714// binomial coefficients. This could be done, but the recurrence has to be in a
1715// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00001716struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00001717 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00001718 bool IsUnsafe;
1719
Andrew Trick57243da2013-10-25 21:35:56 +00001720 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00001721
1722 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00001723 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1724 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1725 if (!SC || SC->getValue()->isZero()) {
1726 IsUnsafe = true;
1727 return false;
1728 }
1729 }
1730 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1731 const SCEV *Step = AR->getStepRecurrence(SE);
1732 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1733 IsUnsafe = true;
1734 return false;
1735 }
1736 }
1737 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00001738 }
1739 bool isDone() const { return IsUnsafe; }
1740};
1741}
1742
1743namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00001744bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
1745 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00001746 visitAll(S, Search);
1747 return !Search.IsUnsafe;
1748}
1749}