blob: c1ed76256e92d75a47c77032ace0d40435e66bf4 [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"
Benjamin Kramer8dd637a2014-06-21 11:47:18 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/LLVMContext.h"
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +000026#include "llvm/IR/Module.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000027#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "llvm/Support/raw_ostream.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000029
Nate Begeman2bca4d92005-07-30 00:12:19 +000030using namespace llvm;
31
Gabor Greif8e66a422010-07-09 16:42:04 +000032/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000033/// reusing an existing cast if a suitable one exists, moving an existing
34/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000035/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000036Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000037 Instruction::CastOps Op,
38 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000039 // This function must be called with the builder having a valid insertion
40 // point. It doesn't need to be the actual IP where the uses of the returned
41 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000042 // We use this precondition to produce a cast that will dominate all its
43 // uses. In particular, this is crucial for the case where the builder's
44 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000045 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000046 // where the uses will be added (only that it dominates it), we are
47 // not allowed to move it.
48 BasicBlock::iterator BIP = Builder.GetInsertPoint();
49
Craig Topper9f008862014-04-15 04:59:12 +000050 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000051
Dan Gohmand2772462010-06-19 13:25:23 +000052 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000053 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000054 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000055 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000056 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000057 // If the cast isn't where we want it, create a new cast at IP.
58 // Likewise, do not reuse a cast at BIP because it must dominate
59 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000060 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000061 // Create a new cast, and leave the old cast in place in case
62 // it is being used as an insert point. Clear its operand
63 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000064 Ret = CastInst::Create(Op, V, Ty, "", IP);
65 Ret->takeName(CI);
66 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000067 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000068 break;
Dan Gohmand2772462010-06-19 13:25:23 +000069 }
Rafael Espindola09a42012012-02-27 02:13:03 +000070 Ret = CI;
71 break;
Dan Gohmand2772462010-06-19 13:25:23 +000072 }
73
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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000209static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
210 const SCEV *Factor, ScalarEvolution &SE,
211 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000212 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000213 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000214 return true;
215
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000216 // x/x == 1.
217 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000218 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000219 return true;
220 }
221
Dan Gohman291c2e02009-05-24 18:06:31 +0000222 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000223 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000224 // 0/x == 0.
225 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000226 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000227 // Check for divisibility.
228 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
229 ConstantInt *CI =
230 ConstantInt::get(SE.getContext(),
231 C->getValue()->getValue().sdiv(
232 FC->getValue()->getValue()));
233 // If the quotient is zero and the remainder is non-zero, reject
234 // the value at this scale. It will be considered for subsequent
235 // smaller scales.
236 if (!CI->isZero()) {
237 const SCEV *Div = SE.getConstant(CI);
238 S = Div;
239 Remainder =
240 SE.getAddExpr(Remainder,
241 SE.getConstant(C->getValue()->getValue().srem(
242 FC->getValue()->getValue())));
243 return true;
244 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000245 }
Dan Gohman17893622009-05-27 02:00:53 +0000246 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000247
248 // In a Mul, check if there is a constant operand which is a multiple
249 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000250 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000251 // Size is known, check if there is a constant operand which is a multiple
252 // of the given factor. If so, we can factor it.
253 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
254 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
255 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
256 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
257 NewMulOps[0] = SE.getConstant(
258 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
259 S = SE.getMulExpr(NewMulOps);
260 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000261 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000262 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000263
264 // In an AddRec, check if both start and step are divisible.
265 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000266 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000267 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000268 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000269 return false;
270 if (!StepRem->isZero())
271 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000272 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000273 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000274 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000275 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
276 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000277 return true;
278 }
279
280 return false;
281}
282
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000283/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
284/// is the number of SCEVAddRecExprs present, which are kept at the end of
285/// the list.
286///
287static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000288 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000289 ScalarEvolution &SE) {
290 unsigned NumAddRecs = 0;
291 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
292 ++NumAddRecs;
293 // Group Ops into non-addrecs and addrecs.
294 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
295 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
296 // Let ScalarEvolution sort and simplify the non-addrecs list.
297 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000298 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000299 SE.getAddExpr(NoAddRecs);
300 // If it returned an add, use the operands. Otherwise it simplified
301 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000302 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000303 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000304 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000305 else if (!Sum->isZero())
306 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000307 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000308 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000309}
310
311/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
312/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
313/// This helps expose more opportunities for folding parts of the expressions
314/// into GEP indices.
315///
316static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000317 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000318 ScalarEvolution &SE) {
319 // Find the addrecs.
320 SmallVector<const SCEV *, 8> AddRecs;
321 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
322 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
323 const SCEV *Start = A->getStart();
324 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000325 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000326 AddRecs.push_back(SE.getAddRecExpr(Zero,
327 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000328 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000329 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000330 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
331 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000332 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000333 e += Add->getNumOperands();
334 } else {
335 Ops[i] = Start;
336 }
337 }
338 if (!AddRecs.empty()) {
339 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000340 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000341 // Resort the operand list, moving any constants to the front.
342 SimplifyAddOperands(Ops, Ty, SE);
343 }
344}
345
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000346/// expandAddToGEP - Expand an addition expression with a pointer type into
347/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
348/// BasicAliasAnalysis and other passes analyze the result. See the rules
349/// for getelementptr vs. inttoptr in
350/// http://llvm.org/docs/LangRef.html#pointeraliasing
351/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000352///
Dan Gohman510bffc2010-01-19 22:26:02 +0000353/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000354/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
355/// they may introduce pointer arithmetic which may not be safely converted
356/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000357///
358/// Design note: It might seem desirable for this function to be more
359/// loop-aware. If some of the indices are loop-invariant while others
360/// aren't, it might seem desirable to emit multiple GEPs, keeping the
361/// loop-invariant portions of the overall computation outside the loop.
362/// However, there are a few reasons this is not done here. Hoisting simple
363/// arithmetic is a low-level optimization that often isn't very
364/// important until late in the optimization process. In fact, passes
365/// like InstructionCombining will combine GEPs, even if it means
366/// pushing loop-invariant computation down into loops, so even if the
367/// GEPs were split here, the work would quickly be undone. The
368/// LoopStrengthReduction pass, which is usually run quite late (and
369/// after the last InstructionCombining pass), takes care of hoisting
370/// loop-invariant portions of expressions, after considering what
371/// can be folded using target addressing modes.
372///
Dan Gohmanaf752342009-07-07 17:06:11 +0000373Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
374 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000375 PointerType *PTy,
376 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000377 Value *V) {
David Blaikie156d46e2015-03-24 23:34:31 +0000378 Type *OriginalElTy = PTy->getElementType();
379 Type *ElTy = OriginalElTy;
Dan Gohman26494912009-05-19 02:15:55 +0000380 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000381 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000382 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000383
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000384 // Split AddRecs up into parts as either of the parts may be usable
385 // without the other.
386 SplitAddRecs(Ops, Ty, SE);
387
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000388 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000389
Bob Wilson2107eb72009-12-04 01:33:04 +0000390 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000391 // operands into GEP indices, at each level. The first index in a GEP
392 // indexes into the array implied by the pointer operand; the rest of
393 // the indices index into the element or field type selected by the
394 // preceding index.
395 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000396 // If the scale size is not 0, attempt to factor out a scale for
397 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000398 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000399 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000400 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000401 if (!ElSize->isZero()) {
402 SmallVector<const SCEV *, 8> NewOps;
403 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
404 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000405 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000406 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000407 // Op now has ElSize factored out.
408 ScaledOps.push_back(Op);
409 if (!Remainder->isZero())
410 NewOps.push_back(Remainder);
411 AnyNonZeroIndices = true;
412 } else {
413 // The operand was not divisible, so add it to the list of operands
414 // we'll scan next iteration.
415 NewOps.push_back(Ops[i]);
416 }
Dan Gohman26494912009-05-19 02:15:55 +0000417 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000418 // If we made any changes, update Ops.
419 if (!ScaledOps.empty()) {
420 Ops = NewOps;
421 SimplifyAddOperands(Ops, Ty, SE);
422 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000423 }
Dan Gohman26494912009-05-19 02:15:55 +0000424 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000425
426 // Record the scaled array index for this level of the type. If
427 // we didn't find any operands that could be factored, tentatively
428 // assume that element zero was selected (since the zero offset
429 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000430 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000431 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000432 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
433 GepIndices.push_back(Scaled);
434
435 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000436 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000437 bool FoundFieldNo = false;
438 // An empty struct has no fields.
439 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 // Field offsets are known. See if a constant offset falls within any of
441 // the struct fields.
442 if (Ops.empty())
443 break;
444 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
445 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
446 const StructLayout &SL = *DL.getStructLayout(STy);
447 uint64_t FullOffset = C->getValue()->getZExtValue();
448 if (FullOffset < SL.getSizeInBytes()) {
449 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
450 GepIndices.push_back(
451 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
452 ElTy = STy->getTypeAtIndex(ElIdx);
453 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000454 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 AnyNonZeroIndices = true;
456 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000457 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000458 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000459 // If no struct field offsets were found, tentatively assume that
460 // field zero was selected (since the zero offset would obviously
461 // be folded away).
462 if (!FoundFieldNo) {
463 ElTy = STy->getTypeAtIndex(0u);
464 GepIndices.push_back(
465 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
466 }
Dan Gohman26494912009-05-19 02:15:55 +0000467 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000468
Chris Lattner229907c2011-07-18 04:54:35 +0000469 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000470 ElTy = ATy->getElementType();
471 else
472 break;
Dan Gohman26494912009-05-19 02:15:55 +0000473 }
474
Dan Gohman8b0a4192010-03-01 17:49:51 +0000475 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000476 // the base to i8* and do an ugly getelementptr with that. It's still
477 // better than ptrtoint+arithmetic+inttoptr at least.
478 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000479 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000480 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000481 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000482
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000483 assert(!isa<Instruction>(V) ||
Rafael Espindola94df2672012-02-26 02:19:19 +0000484 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000485
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000486 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000487 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000488
489 // Fold a GEP with constant operands.
490 if (Constant *CLHS = dyn_cast<Constant>(V))
491 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie4a2e73b2015-04-02 18:55:32 +0000492 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
493 CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000494
495 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
496 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000497 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
498 // Scanning starts from the last instruction before the insertion point.
499 BasicBlock::iterator IP = Builder.GetInsertPoint();
500 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000501 --IP;
502 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000503 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
504 // generated code.
505 if (isa<DbgInfoIntrinsic>(IP))
506 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000507 if (IP->getOpcode() == Instruction::GetElementPtr &&
508 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
509 return IP;
510 if (IP == BlockBegin) break;
511 }
512 }
513
Dan Gohman29707de2010-03-03 05:29:13 +0000514 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000515 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000516
517 // Move the insertion point out of as many loops as we can.
518 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
519 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
520 BasicBlock *Preheader = L->getLoopPreheader();
521 if (!Preheader) break;
522
523 // Ok, move up a level.
524 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
525 }
526
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000527 // Emit a GEP.
David Blaikie93c54442015-04-03 19:41:44 +0000528 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000529 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000530
Dan Gohman26494912009-05-19 02:15:55 +0000531 return GEP;
532 }
533
Dan Gohman29707de2010-03-03 05:29:13 +0000534 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000535 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000536
537 // Move the insertion point out of as many loops as we can.
538 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
539 if (!L->isLoopInvariant(V)) break;
540
541 bool AnyIndexNotLoopInvariant = false;
542 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
543 E = GepIndices.end(); I != E; ++I)
544 if (!L->isLoopInvariant(*I)) {
545 AnyIndexNotLoopInvariant = true;
546 break;
547 }
548 if (AnyIndexNotLoopInvariant)
549 break;
550
551 BasicBlock *Preheader = L->getLoopPreheader();
552 if (!Preheader) break;
553
554 // Ok, move up a level.
555 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
556 }
557
Dan Gohman31a9b982009-07-28 01:40:03 +0000558 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
559 // because ScalarEvolution may have changed the address arithmetic to
560 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000561 Value *Casted = V;
562 if (V->getType() != PTy)
563 Casted = InsertNoopCastOfTo(Casted, PTy);
David Blaikie156d46e2015-03-24 23:34:31 +0000564 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000565 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000566 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000567 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000568 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000569
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000570 // Restore the original insert point.
571 Builder.restoreIP(SaveInsertPt);
572
Dan Gohman26494912009-05-19 02:15:55 +0000573 return expand(SE.getAddExpr(Ops));
574}
575
Dan Gohman29707de2010-03-03 05:29:13 +0000576/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
577/// SCEV expansion. If they are nested, this is the most nested. If they are
578/// neighboring, pick the later.
579static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
580 DominatorTree &DT) {
581 if (!A) return B;
582 if (!B) return A;
583 if (A->contains(B)) return B;
584 if (B->contains(A)) return A;
585 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
586 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
587 return A; // Arbitrarily break the tie.
588}
589
Dan Gohman8ea83d82010-11-18 00:34:22 +0000590/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000591/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000592const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
593 // Test whether we've already computed the most relevant loop for this SCEV.
594 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
Craig Topper9f008862014-04-15 04:59:12 +0000595 RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000596 if (!Pair.second)
597 return Pair.first->second;
598
Dan Gohman29707de2010-03-03 05:29:13 +0000599 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000600 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000601 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000602 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
603 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000604 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
605 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000606 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000607 }
608 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000609 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000610 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
611 L = AR->getLoop();
612 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
613 I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000614 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
615 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000616 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000617 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
618 const Loop *Result = getRelevantLoop(C->getOperand());
619 return RelevantLoops[C] = Result;
620 }
621 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
622 const Loop *Result =
623 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
624 getRelevantLoop(D->getRHS()),
625 *SE.DT);
626 return RelevantLoops[D] = Result;
627 }
Dan Gohman29707de2010-03-03 05:29:13 +0000628 llvm_unreachable("Unexpected SCEV type!");
629}
630
Dan Gohmanb29cda92010-04-15 17:08:50 +0000631namespace {
632
Dan Gohman29707de2010-03-03 05:29:13 +0000633/// LoopCompare - Compare loops by PickMostRelevantLoop.
634class LoopCompare {
635 DominatorTree &DT;
636public:
637 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
638
639 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
640 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000641 // Keep pointer operands sorted at the end.
642 if (LHS.second->getType()->isPointerTy() !=
643 RHS.second->getType()->isPointerTy())
644 return LHS.second->getType()->isPointerTy();
645
Dan Gohman29707de2010-03-03 05:29:13 +0000646 // Compare loops with PickMostRelevantLoop.
647 if (LHS.first != RHS.first)
648 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
649
650 // If one operand is a non-constant negative and the other is not,
651 // put the non-constant negative on the right so that a sub can
652 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000653 if (LHS.second->isNonConstantNegative()) {
654 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000655 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000656 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000657 return true;
658
659 // Otherwise they are equivalent according to this comparison.
660 return false;
661 }
662};
663
Dan Gohmanb29cda92010-04-15 17:08:50 +0000664}
665
Dan Gohman056857a2009-04-18 17:56:28 +0000666Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000667 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000668
Dan Gohman29707de2010-03-03 05:29:13 +0000669 // Collect all the add operands in a loop, along with their associated loops.
670 // Iterate in reverse so that constants are emitted last, all else equal, and
671 // so that pointer operands are inserted first, which the code below relies on
672 // to form more involved GEPs.
673 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
674 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
675 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000676 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000677
Dan Gohman29707de2010-03-03 05:29:13 +0000678 // Sort by loop. Use a stable sort so that constants follow non-constants and
679 // pointer operands precede non-pointer operands.
680 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000681
Dan Gohman29707de2010-03-03 05:29:13 +0000682 // Emit instructions to add all the operands. Hoist as much as possible
683 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000684 Value *Sum = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000685 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
686 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
687 const Loop *CurLoop = I->first;
688 const SCEV *Op = I->second;
689 if (!Sum) {
690 // This is the first operand. Just expand it.
691 Sum = expand(Op);
692 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000693 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000694 // The running sum expression is a pointer. Try to form a getelementptr
695 // at this level with that as the base.
696 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000697 for (; I != E && I->first == CurLoop; ++I) {
698 // If the operand is SCEVUnknown and not instructions, peek through
699 // it, to enable more of it to be folded into the GEP.
700 const SCEV *X = I->second;
701 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
702 if (!isa<Instruction>(U->getValue()))
703 X = SE.getSCEV(U->getValue());
704 NewOps.push_back(X);
705 }
Dan Gohman29707de2010-03-03 05:29:13 +0000706 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000707 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000708 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000709 // Try to form a getelementptr. If the running sum is instructions,
710 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000711 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000712 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
713 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000714 for (++I; I != E && I->first == CurLoop; ++I)
715 NewOps.push_back(I->second);
716 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000717 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000718 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000719 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000720 Sum = InsertNoopCastOfTo(Sum, Ty);
721 Sum = InsertBinop(Instruction::Sub, Sum, W);
722 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000723 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000724 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000725 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000726 Sum = InsertNoopCastOfTo(Sum, Ty);
727 // Canonicalize a constant to the RHS.
728 if (isa<Constant>(Sum)) std::swap(Sum, W);
729 Sum = InsertBinop(Instruction::Add, Sum, W);
730 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000731 }
732 }
Dan Gohman29707de2010-03-03 05:29:13 +0000733
734 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000735}
Dan Gohman26494912009-05-19 02:15:55 +0000736
Dan Gohman056857a2009-04-18 17:56:28 +0000737Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000738 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000739
Dan Gohman29707de2010-03-03 05:29:13 +0000740 // Collect all the mul operands in a loop, along with their associated loops.
741 // Iterate in reverse so that constants are emitted last, all else equal.
742 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
743 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
744 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000745 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000746
Dan Gohman29707de2010-03-03 05:29:13 +0000747 // Sort by loop. Use a stable sort so that constants follow non-constants.
748 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
749
750 // Emit instructions to mul all the operands. Hoist as much as possible
751 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000752 Value *Prod = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000753 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
754 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
755 const SCEV *Op = I->second;
756 if (!Prod) {
757 // This is the first operand. Just expand it.
758 Prod = expand(Op);
759 ++I;
760 } else if (Op->isAllOnesValue()) {
761 // Instead of doing a multiply by negative one, just do a negate.
762 Prod = InsertNoopCastOfTo(Prod, Ty);
763 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
764 ++I;
765 } else {
766 // A simple mul.
767 Value *W = expandCodeFor(Op, Ty);
768 Prod = InsertNoopCastOfTo(Prod, Ty);
769 // Canonicalize a constant to the RHS.
770 if (isa<Constant>(Prod)) std::swap(Prod, W);
771 Prod = InsertBinop(Instruction::Mul, Prod, W);
772 ++I;
773 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000774 }
775
Dan Gohman29707de2010-03-03 05:29:13 +0000776 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000777}
778
Dan Gohman056857a2009-04-18 17:56:28 +0000779Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000780 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000781
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000782 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000783 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000784 const APInt &RHS = SC->getValue()->getValue();
785 if (RHS.isPowerOf2())
786 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000787 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000788 }
789
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000790 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000791 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000792}
793
Dan Gohman291c2e02009-05-24 18:06:31 +0000794/// Move parts of Base into Rest to leave Base with the minimal
795/// expression that provides a pointer operand suitable for a
796/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000797static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000798 ScalarEvolution &SE) {
799 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
800 Base = A->getStart();
801 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000802 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000803 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000804 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000805 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000806 }
807 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
808 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000809 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000810 NewAddOps.back() = Rest;
811 Rest = SE.getAddExpr(NewAddOps);
812 ExposePointerBase(Base, Rest, SE);
813 }
814}
815
Andrew Trick7fb669a2011-10-07 23:46:21 +0000816/// Determine if this is a well-behaved chain of instructions leading back to
817/// the PHI. If so, it may be reused by expanded expressions.
818bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
819 const Loop *L) {
820 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
821 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
822 return false;
823 // If any of the operands don't dominate the insert position, bail.
824 // Addrec operands are always loop-invariant, so this can only happen
825 // if there are instructions which haven't been hoisted.
826 if (L == IVIncInsertLoop) {
827 for (User::op_iterator OI = IncV->op_begin()+1,
828 OE = IncV->op_end(); OI != OE; ++OI)
829 if (Instruction *OInst = dyn_cast<Instruction>(OI))
830 if (!SE.DT->dominates(OInst, IVIncInsertPos))
831 return false;
832 }
833 // Advance to the next instruction.
834 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
835 if (!IncV)
836 return false;
837
838 if (IncV->mayHaveSideEffects())
839 return false;
840
841 if (IncV != PN)
842 return true;
843
844 return isNormalAddRecExprPHI(PN, IncV, L);
845}
846
Andrew Trickc908b432012-01-20 07:41:13 +0000847/// getIVIncOperand returns an induction variable increment's induction
848/// variable operand.
849///
850/// If allowScale is set, any type of GEP is allowed as long as the nonIV
851/// operands dominate InsertPos.
852///
853/// If allowScale is not set, ensure that a GEP increment conforms to one of the
854/// simple patterns generated by getAddRecExprPHILiterally and
855/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
856Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
857 Instruction *InsertPos,
858 bool allowScale) {
859 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000860 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000861
862 switch (IncV->getOpcode()) {
863 default:
Craig Topper9f008862014-04-15 04:59:12 +0000864 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000865 // Check for a simple Add/Sub or GEP of a loop invariant step.
866 case Instruction::Add:
867 case Instruction::Sub: {
868 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindola94df2672012-02-26 02:19:19 +0000869 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000870 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000871 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000872 }
873 case Instruction::BitCast:
874 return dyn_cast<Instruction>(IncV->getOperand(0));
875 case Instruction::GetElementPtr:
876 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
877 I != E; ++I) {
878 if (isa<Constant>(*I))
879 continue;
880 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000881 if (!SE.DT->dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000882 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000883 }
884 if (allowScale) {
885 // allow any kind of GEP as long as it can be hoisted.
886 continue;
887 }
888 // This must be a pointer addition of constants (pretty), which is already
889 // handled, or some number of address-size elements (ugly). Ugly geps
890 // have 2 operands. i1* is used by the expander to represent an
891 // address-size element.
892 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000893 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000894 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
895 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
896 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000897 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000898 break;
899 }
900 return dyn_cast<Instruction>(IncV->getOperand(0));
901 }
902}
903
904/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
905/// it available to other uses in this loop. Recursively hoist any operands,
906/// until we reach a value that dominates InsertPos.
907bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000908 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000909 return true;
910
911 // InsertPos must itself dominate IncV so that IncV's new position satisfies
912 // its existing users.
Andrew Tricka7a3de12012-05-22 17:39:59 +0000913 if (isa<PHINode>(InsertPos)
914 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000915 return false;
916
917 // Check that the chain of IV operands leading back to Phi can be hoisted.
918 SmallVector<Instruction*, 4> IVIncs;
919 for(;;) {
920 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
921 if (!Oper)
922 return false;
923 // IncV is safe to hoist.
924 IVIncs.push_back(IncV);
925 IncV = Oper;
Rafael Espindola94df2672012-02-26 02:19:19 +0000926 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000927 break;
928 }
929 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
930 E = IVIncs.rend(); I != E; ++I) {
931 (*I)->moveBefore(InsertPos);
932 }
933 return true;
934}
935
Andrew Trick7fb669a2011-10-07 23:46:21 +0000936/// Determine if this cyclic phi is in a form that would have been generated by
937/// LSR. We don't care if the phi was actually expanded in this pass, as long
938/// as it is in a low-cost form, for example, no implied multiplication. This
939/// should match any patterns generated by getAddRecExprPHILiterally and
940/// expandAddtoGEP.
941bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000942 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000943 for(Instruction *IVOper = IncV;
944 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
945 /*allowScale=*/false));) {
946 if (IVOper == PN)
947 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000948 }
Andrew Trickc908b432012-01-20 07:41:13 +0000949 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000950}
951
Andrew Trickceafa2c2011-11-30 06:07:54 +0000952/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
953/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
954/// need to materialize IV increments elsewhere to handle difficult situations.
955Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
956 Type *ExpandTy, Type *IntTy,
957 bool useSubtract) {
958 Value *IncV;
959 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
960 if (ExpandTy->isPointerTy()) {
961 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
962 // If the step isn't constant, don't use an implicitly scaled GEP, because
963 // that would require a multiply inside the loop.
964 if (!isa<ConstantInt>(StepV))
965 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
966 GEPPtrTy->getAddressSpace());
967 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
968 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
969 if (IncV->getType() != PN->getType()) {
970 IncV = Builder.CreateBitCast(IncV, PN->getType());
971 rememberInstruction(IncV);
972 }
973 } else {
974 IncV = useSubtract ?
975 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
976 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
977 rememberInstruction(IncV);
978 }
979 return IncV;
980}
981
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +0000982/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
983/// position. This routine assumes that this is possible (has been checked).
984static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
985 Instruction *Pos, PHINode *LoopPhi) {
986 do {
987 if (DT->dominates(InstToHoist, Pos))
988 break;
989 // Make sure the increment is where we want it. But don't move it
990 // down past a potential existing post-inc user.
991 InstToHoist->moveBefore(Pos);
992 Pos = InstToHoist;
993 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
994 } while (InstToHoist != LoopPhi);
995}
996
997/// \brief Check whether we can cheaply express the requested SCEV in terms of
998/// the available PHI SCEV by truncation and/or invertion of the step.
999static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1000 const SCEVAddRecExpr *Phi,
1001 const SCEVAddRecExpr *Requested,
1002 bool &InvertStep) {
1003 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1004 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1005
1006 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1007 return false;
1008
1009 // Try truncate it if necessary.
1010 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1011 if (!Phi)
1012 return false;
1013
1014 // Check whether truncation will help.
1015 if (Phi == Requested) {
1016 InvertStep = false;
1017 return true;
1018 }
1019
1020 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1021 if (SE.getAddExpr(Requested->getStart(),
1022 SE.getNegativeSCEV(Requested)) == Phi) {
1023 InvertStep = true;
1024 return true;
1025 }
1026
1027 return false;
1028}
1029
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001030static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1031 if (!isa<IntegerType>(AR->getType()))
1032 return false;
1033
1034 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1035 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1036 const SCEV *Step = AR->getStepRecurrence(SE);
1037 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1038 SE.getSignExtendExpr(AR, WideTy));
1039 const SCEV *ExtendAfterOp =
1040 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1041 return ExtendAfterOp == OpAfterExtend;
1042}
1043
1044static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1045 if (!isa<IntegerType>(AR->getType()))
1046 return false;
1047
1048 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1049 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1050 const SCEV *Step = AR->getStepRecurrence(SE);
1051 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1052 SE.getZeroExtendExpr(AR, WideTy));
1053 const SCEV *ExtendAfterOp =
1054 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1055 return ExtendAfterOp == OpAfterExtend;
1056}
1057
Dan Gohman51ad99d2010-01-21 02:09:26 +00001058/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1059/// the base addrec, which is the addrec without any non-loop-dominating
1060/// values, and return the PHI.
1061PHINode *
1062SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1063 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001064 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001065 Type *IntTy,
1066 Type *&TruncTy,
1067 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001068 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001069
Dan Gohman51ad99d2010-01-21 02:09:26 +00001070 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001071 BasicBlock *LatchBlock = L->getLoopLatch();
1072 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001073 PHINode *AddRecPhiMatch = nullptr;
1074 Instruction *IncV = nullptr;
1075 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001076 InvertStep = false;
1077
1078 // Only try partially matching scevs that need truncation and/or
1079 // step-inversion if we know this loop is outside the current loop.
1080 bool TryNonMatchingSCEV = IVIncInsertLoop &&
1081 SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1082
Andrew Trick7fb669a2011-10-07 23:46:21 +00001083 for (BasicBlock::iterator I = L->getHeader()->begin();
1084 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001085 if (!SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001086 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001087
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001088 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1089 if (!PhiSCEV)
1090 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001091
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001092 bool IsMatchingSCEV = PhiSCEV == Normalized;
1093 // We only handle truncation and inversion of phi recurrences for the
1094 // expanded expression if the expanded expression's loop dominates the
1095 // loop we insert to. Check now, so we can bail out early.
1096 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1097 continue;
1098
1099 Instruction *TempIncV =
1100 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1101
1102 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001103 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001104 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001105 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001106 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1107 continue;
1108 } else {
1109 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001110 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001111 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001112
1113 // Stop if we have found an exact match SCEV.
1114 if (IsMatchingSCEV) {
1115 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001116 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001117 InvertStep = false;
1118 AddRecPhiMatch = PN;
1119 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001120 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001121
1122 // Try whether the phi can be translated into the requested form
1123 // (truncated and/or offset by a constant).
1124 if ((!TruncTy || InvertStep) &&
1125 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1126 // Record the phi node. But don't stop we might find an exact match
1127 // later.
1128 AddRecPhiMatch = PN;
1129 IncV = TempIncV;
1130 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1131 }
1132 }
1133
1134 if (AddRecPhiMatch) {
1135 // Potentially, move the increment. We have made sure in
1136 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1137 if (L == IVIncInsertLoop)
1138 hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1139
Andrew Trick7fb669a2011-10-07 23:46:21 +00001140 // Ok, the add recurrence looks usable.
1141 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001142 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001143 // Remember the increment.
1144 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001145 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001146 }
1147 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001148
1149 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001150 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001151
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001152 // Another AddRec may need to be recursively expanded below. For example, if
1153 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1154 // loop. Remove this loop from the PostIncLoops set before expanding such
1155 // AddRecs. Otherwise, we cannot find a valid position for the step
1156 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1157 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1158 // so it's not worth implementing SmallPtrSet::swap.
1159 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1160 PostIncLoops.clear();
1161
Dan Gohman51ad99d2010-01-21 02:09:26 +00001162 // Expand code for the start value.
1163 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1164 L->getHeader()->begin());
1165
Andrew Trick244e2c32011-07-16 00:59:39 +00001166 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001167 assert(!isa<Instruction>(StartV) ||
1168 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1169 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001170
Andrew Trickceafa2c2011-11-30 06:07:54 +00001171 // Expand code for the step value. Do this before creating the PHI so that PHI
1172 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001173 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001174 // If the stride is negative, insert a sub instead of an add for the increment
1175 // (unless it's a constant, because subtracts of constants are canonicalized
1176 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001177 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001178 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001179 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001180 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001181 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1182
Sanjoy Das54ef8952015-02-26 19:51:35 +00001183 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1184 // we actually do emit an addition. It does not apply if we emit a
1185 // subtraction.
1186 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1187 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1188
Dan Gohman51ad99d2010-01-21 02:09:26 +00001189 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001190 BasicBlock *Header = L->getHeader();
1191 Builder.SetInsertPoint(Header, Header->begin());
1192 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001193 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001194 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001195 rememberInstruction(PN);
1196
1197 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001198 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001199 BasicBlock *Pred = *HPI;
1200
1201 // Add a start value.
1202 if (!L->contains(Pred)) {
1203 PN->addIncoming(StartV, Pred);
1204 continue;
1205 }
1206
Andrew Trickceafa2c2011-11-30 06:07:54 +00001207 // Create a step value and add it to the PHI.
1208 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1209 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001210 Instruction *InsertPos = L == IVIncInsertLoop ?
1211 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001212 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001213 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001214
Andrew Trick8eaae282013-07-14 02:50:07 +00001215 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001216 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001217 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001218 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001219 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1220 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001221 PN->addIncoming(IncV, Pred);
1222 }
1223
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001224 // After expanding subexpressions, restore the PostIncLoops set so the caller
1225 // can ensure that IVIncrement dominates the current uses.
1226 PostIncLoops = SavedPostIncLoops;
1227
Dan Gohman51ad99d2010-01-21 02:09:26 +00001228 // Remember this PHI, even in post-inc mode.
1229 InsertedValues.insert(PN);
1230
1231 return PN;
1232}
1233
1234Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001235 Type *STy = S->getType();
1236 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001237 const Loop *L = S->getLoop();
1238
1239 // Determine a normalized form of this expression, which is the expression
1240 // before any post-inc adjustment is made.
1241 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001242 if (PostIncLoops.count(L)) {
1243 PostIncLoopSet Loops;
1244 Loops.insert(L);
1245 Normalized =
Craig Topper9f008862014-04-15 04:59:12 +00001246 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
1247 nullptr, Loops, SE, *SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001248 }
1249
1250 // Strip off any non-loop-dominating component from the addrec start.
1251 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001252 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001253 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001254 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001255 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001256 Normalized = cast<SCEVAddRecExpr>(
1257 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1258 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001259 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001260 }
1261
1262 // Strip off any non-loop-dominating component from the addrec step.
1263 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001264 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001265 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001266 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001267 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001268 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001269 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1270 Start, Step, Normalized->getLoop(),
1271 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001272 }
1273
1274 // Expand the core addrec. If we need post-loop scaling, force it to
1275 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001276 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001277 // In some cases, we decide to reuse an existing phi node but need to truncate
1278 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001279 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001280 bool InvertStep = false;
1281 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1282 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001283
Dan Gohman8b0a4192010-03-01 17:49:51 +00001284 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001285 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001286 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001287 Result = PN;
1288 else {
1289 // In PostInc mode, use the post-incremented value.
1290 BasicBlock *LatchBlock = L->getLoopLatch();
1291 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1292 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001293
1294 // For an expansion to use the postinc form, the client must call
1295 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1296 // or dominated by IVIncInsertPos.
Andrew Trickceafa2c2011-11-30 06:07:54 +00001297 if (isa<Instruction>(Result)
1298 && !SE.DT->dominates(cast<Instruction>(Result),
1299 Builder.GetInsertPoint())) {
1300 // The induction variable's postinc expansion does not dominate this use.
1301 // IVUsers tries to prevent this case, so it is rare. However, it can
1302 // happen when an IVUser outside the loop is not dominated by the latch
1303 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1304 // all cases. Consider a phi outide whose operand is replaced during
1305 // expansion with the value of the postinc user. Without fundamentally
1306 // changing the way postinc users are tracked, the only remedy is
1307 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1308 // but hopefully expandCodeFor handles that.
1309 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001310 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001311 if (useSubtract)
1312 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001313 Value *StepV;
1314 {
1315 // Expand the step somewhere that dominates the loop header.
1316 BuilderType::InsertPointGuard Guard(Builder);
1317 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1318 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001319 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1320 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001321 }
1322
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001323 // We have decided to reuse an induction variable of a dominating loop. Apply
1324 // truncation and/or invertion of the step.
1325 if (TruncTy) {
1326 Type *ResTy = Result->getType();
1327 // Normalize the result type.
1328 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1329 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1330 // Truncate the result.
1331 if (TruncTy != Result->getType()) {
1332 Result = Builder.CreateTrunc(Result, TruncTy);
1333 rememberInstruction(Result);
1334 }
1335 // Invert the result.
1336 if (InvertStep) {
1337 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1338 Result);
1339 rememberInstruction(Result);
1340 }
1341 }
1342
Dan Gohman51ad99d2010-01-21 02:09:26 +00001343 // Re-apply any non-loop-dominating scale.
1344 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001345 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001346 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001347 Result = Builder.CreateMul(Result,
1348 expandCodeFor(PostLoopScale, IntTy));
1349 rememberInstruction(Result);
1350 }
1351
1352 // Re-apply any non-loop-dominating offset.
1353 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001354 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001355 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1356 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1357 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001358 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001359 Result = Builder.CreateAdd(Result,
1360 expandCodeFor(PostLoopOffset, IntTy));
1361 rememberInstruction(Result);
1362 }
1363 }
1364
1365 return Result;
1366}
1367
Dan Gohman056857a2009-04-18 17:56:28 +00001368Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001369 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1370
Chris Lattner229907c2011-07-18 04:54:35 +00001371 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001372 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001373
Dan Gohman426901a2009-06-13 16:25:49 +00001374 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001375 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001376 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001377 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001378 CanonicalIV = PN;
1379
1380 // Rewrite an AddRec in terms of the canonical induction variable, if
1381 // its type is more narrow.
1382 if (CanonicalIV &&
1383 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1384 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001385 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1386 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1387 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001388 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001389 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001390 BasicBlock::iterator NewInsertPt =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001391 std::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001392 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001393 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1394 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001395 ++NewInsertPt;
Craig Topper9f008862014-04-15 04:59:12 +00001396 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Dan Gohman426901a2009-06-13 16:25:49 +00001397 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001398 return V;
1399 }
1400
Nate Begeman2bca4d92005-07-30 00:12:19 +00001401 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001402 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001403 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001404 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001405 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1406 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001407
1408 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1409 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001410 const SCEV *Base = S->getStart();
1411 const SCEV *RestArray[1] = { Rest };
1412 // Dig into the expression to find the pointer base for a GEP.
1413 ExposePointerBase(Base, RestArray[0], SE);
1414 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001415 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001416 // Make sure the Base isn't something exotic, such as a multiplied
1417 // or divided pointer value. In those cases, the result type isn't
1418 // actually a pointer type.
1419 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1420 Value *StartV = expand(Base);
1421 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1422 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001423 }
1424 }
1425
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001426 // Just do a normal add. Pre-expand the operands to suppress folding.
1427 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1428 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001429 }
1430
Dan Gohmancd838702010-07-26 18:28:14 +00001431 // If we don't yet have a canonical IV, create one.
1432 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001433 // Create and insert the PHI node for the induction variable in the
1434 // specified loop.
1435 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001436 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001437 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1438 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001439 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001440
Hal Finkel3f5279c2013-08-18 00:16:23 +00001441 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001442 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001443 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001444 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001445 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001446 // There must be an incoming value for each predecessor, even the
1447 // duplicates!
1448 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001449 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001450 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001451
Gabor Greife82532a2010-07-09 15:40:10 +00001452 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001453 // Insert a unit add instruction right before the terminator
1454 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001455 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1456 "indvar.next",
1457 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001458 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001459 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001460 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001461 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001462 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001463 }
Gabor Greife82532a2010-07-09 15:40:10 +00001464 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001465 }
1466
Dan Gohmancd838702010-07-26 18:28:14 +00001467 // {0,+,1} --> Insert a canonical induction variable into the loop!
1468 if (S->isAffine() && S->getOperand(1)->isOne()) {
1469 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1470 "IVs with types different from the canonical IV should "
1471 "already have been handled!");
1472 return CanonicalIV;
1473 }
1474
Dan Gohman426901a2009-06-13 16:25:49 +00001475 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001476
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001477 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001478 if (S->isAffine()) // {0,+,F} --> i*F
1479 return
1480 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001481 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001482 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001483 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001484 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001485
1486 // If this is a chain of recurrences, turn it into a closed form, using the
1487 // folders, then expandCodeFor the closed form. This allows the folders to
1488 // simplify the expression without having to build a bunch of special code
1489 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001490 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001491
Dan Gohman426901a2009-06-13 16:25:49 +00001492 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001493 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001494 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001495 if (isa<SCEVAddRecExpr>(Ext))
1496 NewS = Ext;
1497
Dan Gohmanaf752342009-07-07 17:06:11 +00001498 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001499 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001500
Dan Gohman426901a2009-06-13 16:25:49 +00001501 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001502 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001503 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001504}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001505
Dan Gohman056857a2009-04-18 17:56:28 +00001506Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001507 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001508 Value *V = expandCodeFor(S->getOperand(),
1509 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001510 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001511 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001512 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001513}
1514
Dan Gohman056857a2009-04-18 17:56:28 +00001515Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001516 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001517 Value *V = expandCodeFor(S->getOperand(),
1518 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001519 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001520 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001521 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001522}
1523
Dan Gohman056857a2009-04-18 17:56:28 +00001524Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001525 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001526 Value *V = expandCodeFor(S->getOperand(),
1527 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001528 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001529 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001530 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001531}
1532
Dan Gohman056857a2009-04-18 17:56:28 +00001533Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001534 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001535 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001536 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1537 // In the case of mixed integer and pointer types, do the
1538 // rest of the comparisons as integer.
1539 if (S->getOperand(i)->getType() != Ty) {
1540 Ty = SE.getEffectiveSCEVType(Ty);
1541 LHS = InsertNoopCastOfTo(LHS, Ty);
1542 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001543 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001544 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001545 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001546 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001547 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001548 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001549 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001550 // In the case of mixed integer and pointer types, cast the
1551 // final result back to the pointer type.
1552 if (LHS->getType() != S->getType())
1553 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001554 return LHS;
1555}
1556
Dan Gohman056857a2009-04-18 17:56:28 +00001557Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001558 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001559 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001560 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1561 // In the case of mixed integer and pointer types, do the
1562 // rest of the comparisons as integer.
1563 if (S->getOperand(i)->getType() != Ty) {
1564 Ty = SE.getEffectiveSCEVType(Ty);
1565 LHS = InsertNoopCastOfTo(LHS, Ty);
1566 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001567 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001568 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001569 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001570 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001571 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001572 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001573 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001574 // In the case of mixed integer and pointer types, cast the
1575 // final result back to the pointer type.
1576 if (LHS->getType() != S->getType())
1577 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001578 return LHS;
1579}
1580
Chris Lattner229907c2011-07-18 04:54:35 +00001581Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001582 Instruction *IP) {
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001583 Builder.SetInsertPoint(IP->getParent(), IP);
1584 return expandCodeFor(SH, Ty);
1585}
1586
Chris Lattner229907c2011-07-18 04:54:35 +00001587Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001588 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001589 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001590 if (Ty) {
1591 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1592 "non-trivial casts should be done with the SCEVs directly!");
1593 V = InsertNoopCastOfTo(V, Ty);
1594 }
1595 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001596}
1597
Dan Gohman056857a2009-04-18 17:56:28 +00001598Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001599 // Compute an insertion point for this SCEV object. Hoist the instructions
1600 // as far out in the loop nest as possible.
Dan Gohman830fd382009-06-27 21:18:18 +00001601 Instruction *InsertPt = Builder.GetInsertPoint();
1602 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001603 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001604 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001605 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001606 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001607 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001608 else {
1609 // LSR sets the insertion point for AddRec start/step values to the
1610 // block start to simplify value reuse, even though it's an invalid
1611 // position. SCEVExpander must correct for this in all cases.
1612 InsertPt = L->getHeader()->getFirstInsertionPt();
1613 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001614 } else {
1615 // If the SCEV is computable at this level, insert it into the header
1616 // after the PHIs (and after any other instructions that we've inserted
1617 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001618 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1619 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickc908b432012-01-20 07:41:13 +00001620 while (InsertPt != Builder.GetInsertPoint()
1621 && (isInsertedInstruction(InsertPt)
1622 || isa<DbgInfoIntrinsic>(InsertPt))) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001623 InsertPt = std::next(BasicBlock::iterator(InsertPt));
Andrew Trickc908b432012-01-20 07:41:13 +00001624 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001625 break;
1626 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001627
Dan Gohmandaafbe62009-06-26 22:53:46 +00001628 // Check to see if we already expanded this here.
Andrew Trickd4e1b5e2013-01-14 21:00:37 +00001629 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1630 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001631 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001632 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001633
Benjamin Kramer6e931522013-09-30 15:40:17 +00001634 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman830fd382009-06-27 21:18:18 +00001635 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001636
1637 // Expand the expression into instructions.
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001638 Value *V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001639
Dan Gohmandaafbe62009-06-26 22:53:46 +00001640 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001641 //
1642 // This is independent of PostIncLoops. The mapped value simply materializes
1643 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001644 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001645 // its insertion point was already at the head of the loop.
1646 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001647 return V;
1648}
Dan Gohman63964b52009-06-05 16:35:53 +00001649
Dan Gohman6b751732010-02-14 03:12:47 +00001650void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001651 if (!PostIncLoops.empty())
1652 InsertedPostIncValues.insert(I);
1653 else
Dan Gohman6b751732010-02-14 03:12:47 +00001654 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001655}
1656
Dan Gohman63964b52009-06-05 16:35:53 +00001657/// getOrInsertCanonicalInductionVariable - This method returns the
1658/// canonical induction variable of the specified type for the specified
1659/// loop (inserting one if there is none). A canonical induction variable
1660/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001661PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001662SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001663 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001664 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001665
1666 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001667 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001668 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001669 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001670
1671 // Emit code for it.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001672 BuilderType::InsertPointGuard Guard(Builder);
Craig Topper9f008862014-04-15 04:59:12 +00001673 PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
1674 L->getHeader()->begin()));
Dan Gohman31158752010-07-20 16:46:58 +00001675
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001676 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001677}
Andrew Trickf9201c52011-10-11 02:28:51 +00001678
Andrew Trickf9201c52011-10-11 02:28:51 +00001679/// replaceCongruentIVs - Check for congruent phis in this loop header and
1680/// replace them with their most canonical representative. Return the number of
1681/// phis eliminated.
1682///
1683/// This does not depend on any SCEVExpander state but should be used in
1684/// the same context that SCEVExpander is used.
1685unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001686 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001687 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001688 // Find integer phis in order of increasing width.
1689 SmallVector<PHINode*, 8> Phis;
1690 for (BasicBlock::iterator I = L->getHeader()->begin();
1691 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1692 Phis.push_back(Phi);
1693 }
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001694 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001695 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1696 // Put pointers at the back and make sure pointer < pointer = false.
1697 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1698 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1699 return RHS->getType()->getPrimitiveSizeInBits() <
1700 LHS->getType()->getPrimitiveSizeInBits();
1701 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001702
Andrew Trickf9201c52011-10-11 02:28:51 +00001703 unsigned NumElim = 0;
1704 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick5adedf52012-01-07 01:12:09 +00001705 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1706 // so narrow phis can reuse them.
1707 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1708 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1709 PHINode *Phi = *PIter;
1710
Benjamin Kramera225ed82012-10-19 16:37:30 +00001711 // Fold constant phis. They may be congruent to other constant phis and
1712 // would confuse the logic below that expects proper IVs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001713 if (Value *V = SimplifyInstruction(Phi, DL, SE.TLI, SE.DT, SE.AC)) {
Benjamin Kramera225ed82012-10-19 16:37:30 +00001714 Phi->replaceAllUsesWith(V);
1715 DeadInsts.push_back(Phi);
1716 ++NumElim;
1717 DEBUG_WITH_TYPE(DebugType, dbgs()
1718 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1719 continue;
1720 }
1721
Andrew Trickf9201c52011-10-11 02:28:51 +00001722 if (!SE.isSCEVable(Phi->getType()))
1723 continue;
1724
1725 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1726 if (!OrigPhiRef) {
1727 OrigPhiRef = Phi;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001728 if (Phi->getType()->isIntegerTy() && TTI
1729 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001730 // This phi can be freely truncated to the narrowest phi type. Map the
1731 // truncated expression to it so it will be reused for narrow types.
1732 const SCEV *TruncExpr =
1733 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1734 ExprToIVMap[TruncExpr] = Phi;
1735 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001736 continue;
1737 }
1738
Andrew Trick5adedf52012-01-07 01:12:09 +00001739 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1740 // sense.
1741 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001742 continue;
1743
1744 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1745 Instruction *OrigInc =
1746 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1747 Instruction *IsomorphicInc =
1748 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1749
Andrew Trick5adedf52012-01-07 01:12:09 +00001750 // If this phi has the same width but is more canonical, replace the
Andrew Trickc908b432012-01-20 07:41:13 +00001751 // original with it. As part of the "more canonical" determination,
1752 // respect a prior decision to use an IV chain.
Andrew Trick5adedf52012-01-07 01:12:09 +00001753 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickc908b432012-01-20 07:41:13 +00001754 && !(ChainedPhis.count(Phi)
1755 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1756 && (ChainedPhis.count(Phi)
1757 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001758 std::swap(OrigPhiRef, Phi);
1759 std::swap(OrigInc, IsomorphicInc);
1760 }
1761 // Replacing the congruent phi is sufficient because acyclic redundancy
1762 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1763 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trickf730f392012-01-07 01:29:21 +00001764 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1765 // common case of a single IV increment so that DeleteDeadPHIs can remove
1766 // cycles that had postinc uses.
Andrew Trick5adedf52012-01-07 01:12:09 +00001767 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1768 IsomorphicInc->getType());
1769 if (OrigInc != IsomorphicInc
Andrew Trickd5d2db92012-01-10 01:45:08 +00001770 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickc908b432012-01-20 07:41:13 +00001771 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1772 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001773 DEBUG_WITH_TYPE(DebugType, dbgs()
1774 << "INDVARS: Eliminated congruent iv.inc: "
1775 << *IsomorphicInc << '\n');
Andrew Trick5adedf52012-01-07 01:12:09 +00001776 Value *NewInc = OrigInc;
1777 if (OrigInc->getType() != IsomorphicInc->getType()) {
Sanjoy Dasf1e9e1d2015-03-13 18:31:19 +00001778 Instruction *IP = nullptr;
1779 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1780 IP = PN->getParent()->getFirstInsertionPt();
1781 else
1782 IP = OrigInc->getNextNode();
1783
Andrew Trick23ef0d62012-01-14 03:17:23 +00001784 IRBuilder<> Builder(IP);
Andrew Trick5adedf52012-01-07 01:12:09 +00001785 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1786 NewInc = Builder.
1787 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1788 }
1789 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trickf9201c52011-10-11 02:28:51 +00001790 DeadInsts.push_back(IsomorphicInc);
1791 }
1792 }
1793 DEBUG_WITH_TYPE(DebugType, dbgs()
1794 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1795 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001796 Value *NewIV = OrigPhiRef;
1797 if (OrigPhiRef->getType() != Phi->getType()) {
1798 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1799 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1800 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1801 }
1802 Phi->replaceAllUsesWith(NewIV);
Andrew Trickf9201c52011-10-11 02:28:51 +00001803 DeadInsts.push_back(Phi);
1804 }
1805 return NumElim;
1806}
Andrew Trick653513b2012-07-13 23:33:10 +00001807
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001808bool SCEVExpander::isHighCostExpansionHelper(
1809 const SCEV *S, Loop *L, SmallPtrSetImpl<const SCEV *> &Processed) {
Wei Mie2538b52015-05-28 21:49:07 +00001810
1811 // Zero/One operand expressions
1812 switch (S->getSCEVType()) {
1813 case scUnknown:
1814 case scConstant:
1815 return false;
1816 case scTruncate:
1817 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(), L,
1818 Processed);
1819 case scZeroExtend:
1820 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1821 L, Processed);
1822 case scSignExtend:
1823 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1824 L, Processed);
1825 }
1826
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001827 if (!Processed.insert(S).second)
1828 return false;
1829
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001830 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1831 // If the divisor is a power of two and the SCEV type fits in a native
1832 // integer, consider the divison cheap irrespective of whether it occurs in
1833 // the user code since it can be lowered into a right shift.
1834 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1835 if (SC->getValue()->getValue().isPowerOf2()) {
1836 const DataLayout &DL =
1837 L->getHeader()->getParent()->getParent()->getDataLayout();
1838 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1839 return DL.isIllegalInteger(Width);
1840 }
1841
1842 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1843 // HowManyLessThans produced to compute a precise expression, rather than a
1844 // UDiv from the user's code. If we can't find a UDiv in the code with some
1845 // simple searching, assume the former consider UDivExpr expensive to
1846 // compute.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001847 BasicBlock *ExitingBB = L->getExitingBlock();
1848 if (!ExitingBB)
1849 return true;
1850
1851 BranchInst *ExitingBI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1852 if (!ExitingBI || !ExitingBI->isConditional())
1853 return true;
1854
1855 ICmpInst *OrigCond = dyn_cast<ICmpInst>(ExitingBI->getCondition());
1856 if (!OrigCond)
1857 return true;
1858
1859 const SCEV *RHS = SE.getSCEV(OrigCond->getOperand(1));
1860 RHS = SE.getMinusSCEV(RHS, SE.getConstant(RHS->getType(), 1));
1861 if (RHS != S) {
1862 const SCEV *LHS = SE.getSCEV(OrigCond->getOperand(0));
1863 LHS = SE.getMinusSCEV(LHS, SE.getConstant(LHS->getType(), 1));
1864 if (LHS != S)
1865 return true;
1866 }
1867 }
1868
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001869 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1870 // the exit condition.
1871 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1872 return true;
1873
Wei Mie2538b52015-05-28 21:49:07 +00001874 // Recurse past nary expressions, which commonly occur in the
1875 // BackedgeTakenCount. They may already exist in program code, and if not,
1876 // they are not too expensive rematerialize.
1877 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1878 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
1879 I != E; ++I) {
1880 if (isHighCostExpansionHelper(*I, L, Processed))
1881 return true;
1882 }
1883 }
1884
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001885 // If we haven't recognized an expensive SCEV pattern, assume it's an
1886 // expression produced by program code.
1887 return false;
1888}
1889
Andrew Trick653513b2012-07-13 23:33:10 +00001890namespace {
1891// Search for a SCEV subexpression that is not safe to expand. Any expression
1892// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1893// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1894// instruction, but the important thing is that we prove the denominator is
1895// nonzero before expansion.
1896//
1897// IVUsers already checks that IV-derived expressions are safe. So this check is
1898// only needed when the expression includes some subexpression that is not IV
1899// derived.
1900//
1901// Currently, we only allow division by a nonzero constant here. If this is
1902// inadequate, we could easily allow division by SCEVUnknown by using
1903// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00001904//
1905// We cannot generally expand recurrences unless the step dominates the loop
1906// header. The expander handles the special case of affine recurrences by
1907// scaling the recurrence outside the loop, but this technique isn't generally
1908// applicable. Expanding a nested recurrence outside a loop requires computing
1909// binomial coefficients. This could be done, but the recurrence has to be in a
1910// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00001911struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00001912 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00001913 bool IsUnsafe;
1914
Andrew Trick57243da2013-10-25 21:35:56 +00001915 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00001916
1917 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00001918 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1919 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1920 if (!SC || SC->getValue()->isZero()) {
1921 IsUnsafe = true;
1922 return false;
1923 }
1924 }
1925 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1926 const SCEV *Step = AR->getStepRecurrence(SE);
1927 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1928 IsUnsafe = true;
1929 return false;
1930 }
1931 }
1932 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00001933 }
1934 bool isDone() const { return IsUnsafe; }
1935};
1936}
1937
1938namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00001939bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
1940 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00001941 visitAll(S, Search);
1942 return !Search.IsUnsafe;
1943}
1944}