blob: 1bdddebf9c96e7a7fb09d81b040add6641a1fc38 [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"
Andrew Trick7fb669a2011-10-07 23:46:21 +000026#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/Support/raw_ostream.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000028
Nate Begeman2bca4d92005-07-30 00:12:19 +000029using namespace llvm;
30
Gabor Greif8e66a422010-07-09 16:42:04 +000031/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000032/// reusing an existing cast if a suitable one exists, moving an existing
33/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000034/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000035Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000036 Instruction::CastOps Op,
37 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000038 // This function must be called with the builder having a valid insertion
39 // point. It doesn't need to be the actual IP where the uses of the returned
40 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000041 // We use this precondition to produce a cast that will dominate all its
42 // uses. In particular, this is crucial for the case where the builder's
43 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000044 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000045 // where the uses will be added (only that it dominates it), we are
46 // not allowed to move it.
47 BasicBlock::iterator BIP = Builder.GetInsertPoint();
48
Craig Topper9f008862014-04-15 04:59:12 +000049 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000050
Dan Gohmand2772462010-06-19 13:25:23 +000051 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000052 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000053 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000054 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000055 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000056 // If the cast isn't where we want it, create a new cast at IP.
57 // Likewise, do not reuse a cast at BIP because it must dominate
58 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000059 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000060 // Create a new cast, and leave the old cast in place in case
61 // it is being used as an insert point. Clear its operand
62 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000063 Ret = CastInst::Create(Op, V, Ty, "", IP);
64 Ret->takeName(CI);
65 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000066 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000067 break;
Dan Gohmand2772462010-06-19 13:25:23 +000068 }
Rafael Espindola09a42012012-02-27 02:13:03 +000069 Ret = CI;
70 break;
Dan Gohmand2772462010-06-19 13:25:23 +000071 }
72
73 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000074 if (!Ret)
75 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
76
77 // We assert at the end of the function since IP might point to an
78 // instruction with different dominance properties than a cast
79 // (an invoke for example) and not dominate BIP (but the cast does).
80 assert(SE.DT->dominates(Ret, BIP));
81
82 rememberInstruction(Ret);
83 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000084}
85
Dan Gohman830fd382009-06-27 21:18:18 +000086/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
87/// which must be possible with a noop cast, doing what we can to share
88/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +000089Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +000090 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
91 assert((Op == Instruction::BitCast ||
92 Op == Instruction::PtrToInt ||
93 Op == Instruction::IntToPtr) &&
94 "InsertNoopCastOfTo cannot perform non-noop casts!");
95 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
96 "InsertNoopCastOfTo cannot change sizes!");
97
Dan Gohman0a40ad92009-04-16 03:18:22 +000098 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +000099 if (Op == Instruction::BitCast) {
100 if (V->getType() == Ty)
101 return V;
102 if (CastInst *CI = dyn_cast<CastInst>(V)) {
103 if (CI->getOperand(0)->getType() == Ty)
104 return CI->getOperand(0);
105 }
106 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000107 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000108 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000109 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000110 if (CastInst *CI = dyn_cast<CastInst>(V))
111 if ((CI->getOpcode() == Instruction::PtrToInt ||
112 CI->getOpcode() == Instruction::IntToPtr) &&
113 SE.getTypeSizeInBits(CI->getType()) ==
114 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
115 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
117 if ((CE->getOpcode() == Instruction::PtrToInt ||
118 CE->getOpcode() == Instruction::IntToPtr) &&
119 SE.getTypeSizeInBits(CE->getType()) ==
120 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
121 return CE->getOperand(0);
122 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000123
Dan Gohmand2772462010-06-19 13:25:23 +0000124 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000125 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000126 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000127
Dan Gohmand2772462010-06-19 13:25:23 +0000128 // Cast the argument at the beginning of the entry block, after
129 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000130 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000131 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
132 while ((isa<BitCastInst>(IP) &&
133 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
134 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000135 isa<DbgInfoIntrinsic>(IP) ||
136 isa<LandingPadInst>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000137 ++IP;
138 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000139 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000140
Dan Gohmand2772462010-06-19 13:25:23 +0000141 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000142 Instruction *I = cast<Instruction>(V);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000143 BasicBlock::iterator IP = I; ++IP;
144 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
145 IP = II->getNormalDest()->begin();
Rafael Espindola82d95752012-02-18 17:22:58 +0000146 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000147 ++IP;
Dan Gohmand2772462010-06-19 13:25:23 +0000148 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000149}
150
Chris Lattnere71f1442007-04-13 05:04:18 +0000151/// InsertBinop - Insert the specified binary operator, doing a small amount
152/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000153Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
154 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000155 // Fold a binop with constant operands.
156 if (Constant *CLHS = dyn_cast<Constant>(LHS))
157 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000158 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000159
Chris Lattnere71f1442007-04-13 05:04:18 +0000160 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
161 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000162 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
163 // Scanning starts from the last instruction before the insertion point.
164 BasicBlock::iterator IP = Builder.GetInsertPoint();
165 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000166 --IP;
167 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000168 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
169 // generated code.
170 if (isa<DbgInfoIntrinsic>(IP))
171 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000172 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
173 IP->getOperand(1) == RHS)
174 return IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000175 if (IP == BlockBegin) break;
176 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000177 }
Dan Gohman830fd382009-06-27 21:18:18 +0000178
Dan Gohman29707de2010-03-03 05:29:13 +0000179 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000180 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
181 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000182
183 // Move the insertion point out of as many loops as we can.
184 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
185 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
186 BasicBlock *Preheader = L->getLoopPreheader();
187 if (!Preheader) break;
188
189 // Ok, move up a level.
190 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
191 }
192
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000193 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000194 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000195 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000196 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000197
Dan Gohmand195a222009-05-01 17:13:31 +0000198 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000199}
200
Dan Gohman17893622009-05-27 02:00:53 +0000201/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000202/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000203/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000204/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000205/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
206/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
207/// check to see if the divide was folded.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000208static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
209 const SCEV *Factor, ScalarEvolution &SE,
210 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000211 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000212 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000213 return true;
214
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000215 // x/x == 1.
216 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000217 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000218 return true;
219 }
220
Dan Gohman291c2e02009-05-24 18:06:31 +0000221 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000222 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000223 // 0/x == 0.
224 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000225 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000226 // Check for divisibility.
227 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
228 ConstantInt *CI =
229 ConstantInt::get(SE.getContext(),
230 C->getValue()->getValue().sdiv(
231 FC->getValue()->getValue()));
232 // If the quotient is zero and the remainder is non-zero, reject
233 // the value at this scale. It will be considered for subsequent
234 // smaller scales.
235 if (!CI->isZero()) {
236 const SCEV *Div = SE.getConstant(CI);
237 S = Div;
238 Remainder =
239 SE.getAddExpr(Remainder,
240 SE.getConstant(C->getValue()->getValue().srem(
241 FC->getValue()->getValue())));
242 return true;
243 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000244 }
Dan Gohman17893622009-05-27 02:00:53 +0000245 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000246
247 // In a Mul, check if there is a constant operand which is a multiple
248 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000249 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 // Size is known, check if there is a constant operand which is a multiple
251 // of the given factor. If so, we can factor it.
252 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
253 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
254 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
255 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
256 NewMulOps[0] = SE.getConstant(
257 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
258 S = SE.getMulExpr(NewMulOps);
259 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000260 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000261 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000262
263 // In an AddRec, check if both start and step are divisible.
264 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000265 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000266 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000267 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000268 return false;
269 if (!StepRem->isZero())
270 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000271 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000272 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000273 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000274 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
275 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000276 return true;
277 }
278
279 return false;
280}
281
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000282/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
283/// is the number of SCEVAddRecExprs present, which are kept at the end of
284/// the list.
285///
286static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000287 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000288 ScalarEvolution &SE) {
289 unsigned NumAddRecs = 0;
290 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
291 ++NumAddRecs;
292 // Group Ops into non-addrecs and addrecs.
293 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
294 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
295 // Let ScalarEvolution sort and simplify the non-addrecs list.
296 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000297 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000298 SE.getAddExpr(NoAddRecs);
299 // If it returned an add, use the operands. Otherwise it simplified
300 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000301 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000302 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000303 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000304 else if (!Sum->isZero())
305 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000306 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000307 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000308}
309
310/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
311/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
312/// This helps expose more opportunities for folding parts of the expressions
313/// into GEP indices.
314///
315static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000316 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000317 ScalarEvolution &SE) {
318 // Find the addrecs.
319 SmallVector<const SCEV *, 8> AddRecs;
320 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
321 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
322 const SCEV *Start = A->getStart();
323 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000324 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000325 AddRecs.push_back(SE.getAddRecExpr(Zero,
326 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000327 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000328 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000329 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
330 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000331 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000332 e += Add->getNumOperands();
333 } else {
334 Ops[i] = Start;
335 }
336 }
337 if (!AddRecs.empty()) {
338 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000339 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000340 // Resort the operand list, moving any constants to the front.
341 SimplifyAddOperands(Ops, Ty, SE);
342 }
343}
344
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000345/// expandAddToGEP - Expand an addition expression with a pointer type into
346/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
347/// BasicAliasAnalysis and other passes analyze the result. See the rules
348/// for getelementptr vs. inttoptr in
349/// http://llvm.org/docs/LangRef.html#pointeraliasing
350/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000351///
Dan Gohman510bffc2010-01-19 22:26:02 +0000352/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000353/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
354/// they may introduce pointer arithmetic which may not be safely converted
355/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000356///
357/// Design note: It might seem desirable for this function to be more
358/// loop-aware. If some of the indices are loop-invariant while others
359/// aren't, it might seem desirable to emit multiple GEPs, keeping the
360/// loop-invariant portions of the overall computation outside the loop.
361/// However, there are a few reasons this is not done here. Hoisting simple
362/// arithmetic is a low-level optimization that often isn't very
363/// important until late in the optimization process. In fact, passes
364/// like InstructionCombining will combine GEPs, even if it means
365/// pushing loop-invariant computation down into loops, so even if the
366/// GEPs were split here, the work would quickly be undone. The
367/// LoopStrengthReduction pass, which is usually run quite late (and
368/// after the last InstructionCombining pass), takes care of hoisting
369/// loop-invariant portions of expressions, after considering what
370/// can be folded using target addressing modes.
371///
Dan Gohmanaf752342009-07-07 17:06:11 +0000372Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
373 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000374 PointerType *PTy,
375 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000376 Value *V) {
David Blaikie156d46e2015-03-24 23:34:31 +0000377 Type *OriginalElTy = PTy->getElementType();
378 Type *ElTy = OriginalElTy;
Dan Gohman26494912009-05-19 02:15:55 +0000379 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000380 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000381 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000382
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000383 // Split AddRecs up into parts as either of the parts may be usable
384 // without the other.
385 SplitAddRecs(Ops, Ty, SE);
386
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000387 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000388
Bob Wilson2107eb72009-12-04 01:33:04 +0000389 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000390 // operands into GEP indices, at each level. The first index in a GEP
391 // indexes into the array implied by the pointer operand; the rest of
392 // the indices index into the element or field type selected by the
393 // preceding index.
394 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000395 // If the scale size is not 0, attempt to factor out a scale for
396 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000397 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000398 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000399 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000400 if (!ElSize->isZero()) {
401 SmallVector<const SCEV *, 8> NewOps;
402 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
403 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000404 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000406 // Op now has ElSize factored out.
407 ScaledOps.push_back(Op);
408 if (!Remainder->isZero())
409 NewOps.push_back(Remainder);
410 AnyNonZeroIndices = true;
411 } else {
412 // The operand was not divisible, so add it to the list of operands
413 // we'll scan next iteration.
414 NewOps.push_back(Ops[i]);
415 }
Dan Gohman26494912009-05-19 02:15:55 +0000416 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000417 // If we made any changes, update Ops.
418 if (!ScaledOps.empty()) {
419 Ops = NewOps;
420 SimplifyAddOperands(Ops, Ty, SE);
421 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000422 }
Dan Gohman26494912009-05-19 02:15:55 +0000423 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000424
425 // Record the scaled array index for this level of the type. If
426 // we didn't find any operands that could be factored, tentatively
427 // assume that element zero was selected (since the zero offset
428 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000429 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000430 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000431 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
432 GepIndices.push_back(Scaled);
433
434 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000435 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000436 bool FoundFieldNo = false;
437 // An empty struct has no fields.
438 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000439 // Field offsets are known. See if a constant offset falls within any of
440 // the struct fields.
441 if (Ops.empty())
442 break;
443 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
444 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
445 const StructLayout &SL = *DL.getStructLayout(STy);
446 uint64_t FullOffset = C->getValue()->getZExtValue();
447 if (FullOffset < SL.getSizeInBytes()) {
448 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
449 GepIndices.push_back(
450 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
451 ElTy = STy->getTypeAtIndex(ElIdx);
452 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000453 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000454 AnyNonZeroIndices = true;
455 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000456 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000458 // If no struct field offsets were found, tentatively assume that
459 // field zero was selected (since the zero offset would obviously
460 // be folded away).
461 if (!FoundFieldNo) {
462 ElTy = STy->getTypeAtIndex(0u);
463 GepIndices.push_back(
464 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
465 }
Dan Gohman26494912009-05-19 02:15:55 +0000466 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000467
Chris Lattner229907c2011-07-18 04:54:35 +0000468 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000469 ElTy = ATy->getElementType();
470 else
471 break;
Dan Gohman26494912009-05-19 02:15:55 +0000472 }
473
Dan Gohman8b0a4192010-03-01 17:49:51 +0000474 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000475 // the base to i8* and do an ugly getelementptr with that. It's still
476 // better than ptrtoint+arithmetic+inttoptr at least.
477 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000478 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000479 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000480 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000481
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000482 assert(!isa<Instruction>(V) ||
Rafael Espindola94df2672012-02-26 02:19:19 +0000483 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000484
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000485 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000486 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000487
488 // Fold a GEP with constant operands.
489 if (Constant *CLHS = dyn_cast<Constant>(V))
490 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie4a2e73b2015-04-02 18:55:32 +0000491 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
492 CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000493
494 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
495 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000496 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
497 // Scanning starts from the last instruction before the insertion point.
498 BasicBlock::iterator IP = Builder.GetInsertPoint();
499 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000500 --IP;
501 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000502 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
503 // generated code.
504 if (isa<DbgInfoIntrinsic>(IP))
505 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000506 if (IP->getOpcode() == Instruction::GetElementPtr &&
507 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
508 return IP;
509 if (IP == BlockBegin) break;
510 }
511 }
512
Dan Gohman29707de2010-03-03 05:29:13 +0000513 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000514 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000515
516 // Move the insertion point out of as many loops as we can.
517 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
518 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
519 BasicBlock *Preheader = L->getLoopPreheader();
520 if (!Preheader) break;
521
522 // Ok, move up a level.
523 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
524 }
525
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000526 // Emit a GEP.
527 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000528 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000529
Dan Gohman26494912009-05-19 02:15:55 +0000530 return GEP;
531 }
532
Dan Gohman29707de2010-03-03 05:29:13 +0000533 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000534 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000535
536 // Move the insertion point out of as many loops as we can.
537 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
538 if (!L->isLoopInvariant(V)) break;
539
540 bool AnyIndexNotLoopInvariant = false;
541 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
542 E = GepIndices.end(); I != E; ++I)
543 if (!L->isLoopInvariant(*I)) {
544 AnyIndexNotLoopInvariant = true;
545 break;
546 }
547 if (AnyIndexNotLoopInvariant)
548 break;
549
550 BasicBlock *Preheader = L->getLoopPreheader();
551 if (!Preheader) break;
552
553 // Ok, move up a level.
554 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
555 }
556
Dan Gohman31a9b982009-07-28 01:40:03 +0000557 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
558 // because ScalarEvolution may have changed the address arithmetic to
559 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000560 Value *Casted = V;
561 if (V->getType() != PTy)
562 Casted = InsertNoopCastOfTo(Casted, PTy);
David Blaikie156d46e2015-03-24 23:34:31 +0000563 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000564 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000565 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000566 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000567 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000568
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000569 // Restore the original insert point.
570 Builder.restoreIP(SaveInsertPt);
571
Dan Gohman26494912009-05-19 02:15:55 +0000572 return expand(SE.getAddExpr(Ops));
573}
574
Dan Gohman29707de2010-03-03 05:29:13 +0000575/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
576/// SCEV expansion. If they are nested, this is the most nested. If they are
577/// neighboring, pick the later.
578static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
579 DominatorTree &DT) {
580 if (!A) return B;
581 if (!B) return A;
582 if (A->contains(B)) return B;
583 if (B->contains(A)) return A;
584 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
585 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
586 return A; // Arbitrarily break the tie.
587}
588
Dan Gohman8ea83d82010-11-18 00:34:22 +0000589/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000590/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000591const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
592 // Test whether we've already computed the most relevant loop for this SCEV.
593 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
Craig Topper9f008862014-04-15 04:59:12 +0000594 RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000595 if (!Pair.second)
596 return Pair.first->second;
597
Dan Gohman29707de2010-03-03 05:29:13 +0000598 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000599 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000600 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000601 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
602 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000603 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
604 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000605 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000606 }
607 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000608 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000609 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
610 L = AR->getLoop();
611 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
612 I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000613 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
614 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000615 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000616 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
617 const Loop *Result = getRelevantLoop(C->getOperand());
618 return RelevantLoops[C] = Result;
619 }
620 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
621 const Loop *Result =
622 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
623 getRelevantLoop(D->getRHS()),
624 *SE.DT);
625 return RelevantLoops[D] = Result;
626 }
Dan Gohman29707de2010-03-03 05:29:13 +0000627 llvm_unreachable("Unexpected SCEV type!");
628}
629
Dan Gohmanb29cda92010-04-15 17:08:50 +0000630namespace {
631
Dan Gohman29707de2010-03-03 05:29:13 +0000632/// LoopCompare - Compare loops by PickMostRelevantLoop.
633class LoopCompare {
634 DominatorTree &DT;
635public:
636 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
637
638 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
639 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000640 // Keep pointer operands sorted at the end.
641 if (LHS.second->getType()->isPointerTy() !=
642 RHS.second->getType()->isPointerTy())
643 return LHS.second->getType()->isPointerTy();
644
Dan Gohman29707de2010-03-03 05:29:13 +0000645 // Compare loops with PickMostRelevantLoop.
646 if (LHS.first != RHS.first)
647 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
648
649 // If one operand is a non-constant negative and the other is not,
650 // put the non-constant negative on the right so that a sub can
651 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000652 if (LHS.second->isNonConstantNegative()) {
653 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000654 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000655 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000656 return true;
657
658 // Otherwise they are equivalent according to this comparison.
659 return false;
660 }
661};
662
Dan Gohmanb29cda92010-04-15 17:08:50 +0000663}
664
Dan Gohman056857a2009-04-18 17:56:28 +0000665Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000666 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000667
Dan Gohman29707de2010-03-03 05:29:13 +0000668 // Collect all the add operands in a loop, along with their associated loops.
669 // Iterate in reverse so that constants are emitted last, all else equal, and
670 // so that pointer operands are inserted first, which the code below relies on
671 // to form more involved GEPs.
672 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
673 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
674 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000675 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000676
Dan Gohman29707de2010-03-03 05:29:13 +0000677 // Sort by loop. Use a stable sort so that constants follow non-constants and
678 // pointer operands precede non-pointer operands.
679 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000680
Dan Gohman29707de2010-03-03 05:29:13 +0000681 // Emit instructions to add all the operands. Hoist as much as possible
682 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000683 Value *Sum = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000684 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
685 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
686 const Loop *CurLoop = I->first;
687 const SCEV *Op = I->second;
688 if (!Sum) {
689 // This is the first operand. Just expand it.
690 Sum = expand(Op);
691 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000692 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000693 // The running sum expression is a pointer. Try to form a getelementptr
694 // at this level with that as the base.
695 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000696 for (; I != E && I->first == CurLoop; ++I) {
697 // If the operand is SCEVUnknown and not instructions, peek through
698 // it, to enable more of it to be folded into the GEP.
699 const SCEV *X = I->second;
700 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
701 if (!isa<Instruction>(U->getValue()))
702 X = SE.getSCEV(U->getValue());
703 NewOps.push_back(X);
704 }
Dan Gohman29707de2010-03-03 05:29:13 +0000705 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000706 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000707 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000708 // Try to form a getelementptr. If the running sum is instructions,
709 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000710 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000711 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
712 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000713 for (++I; I != E && I->first == CurLoop; ++I)
714 NewOps.push_back(I->second);
715 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000716 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000717 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000718 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000719 Sum = InsertNoopCastOfTo(Sum, Ty);
720 Sum = InsertBinop(Instruction::Sub, Sum, W);
721 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000722 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000723 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000724 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000725 Sum = InsertNoopCastOfTo(Sum, Ty);
726 // Canonicalize a constant to the RHS.
727 if (isa<Constant>(Sum)) std::swap(Sum, W);
728 Sum = InsertBinop(Instruction::Add, Sum, W);
729 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000730 }
731 }
Dan Gohman29707de2010-03-03 05:29:13 +0000732
733 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000734}
Dan Gohman26494912009-05-19 02:15:55 +0000735
Dan Gohman056857a2009-04-18 17:56:28 +0000736Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000737 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000738
Dan Gohman29707de2010-03-03 05:29:13 +0000739 // Collect all the mul operands in a loop, along with their associated loops.
740 // Iterate in reverse so that constants are emitted last, all else equal.
741 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
742 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
743 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000744 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000745
Dan Gohman29707de2010-03-03 05:29:13 +0000746 // Sort by loop. Use a stable sort so that constants follow non-constants.
747 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
748
749 // Emit instructions to mul all the operands. Hoist as much as possible
750 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000751 Value *Prod = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000752 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
753 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
754 const SCEV *Op = I->second;
755 if (!Prod) {
756 // This is the first operand. Just expand it.
757 Prod = expand(Op);
758 ++I;
759 } else if (Op->isAllOnesValue()) {
760 // Instead of doing a multiply by negative one, just do a negate.
761 Prod = InsertNoopCastOfTo(Prod, Ty);
762 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
763 ++I;
764 } else {
765 // A simple mul.
766 Value *W = expandCodeFor(Op, Ty);
767 Prod = InsertNoopCastOfTo(Prod, Ty);
768 // Canonicalize a constant to the RHS.
769 if (isa<Constant>(Prod)) std::swap(Prod, W);
770 Prod = InsertBinop(Instruction::Mul, Prod, W);
771 ++I;
772 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000773 }
774
Dan Gohman29707de2010-03-03 05:29:13 +0000775 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000776}
777
Dan Gohman056857a2009-04-18 17:56:28 +0000778Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000779 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000780
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000781 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000782 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000783 const APInt &RHS = SC->getValue()->getValue();
784 if (RHS.isPowerOf2())
785 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000786 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000787 }
788
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000789 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000790 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000791}
792
Dan Gohman291c2e02009-05-24 18:06:31 +0000793/// Move parts of Base into Rest to leave Base with the minimal
794/// expression that provides a pointer operand suitable for a
795/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000796static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000797 ScalarEvolution &SE) {
798 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
799 Base = A->getStart();
800 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000801 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000802 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000803 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000804 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000805 }
806 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
807 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000808 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000809 NewAddOps.back() = Rest;
810 Rest = SE.getAddExpr(NewAddOps);
811 ExposePointerBase(Base, Rest, SE);
812 }
813}
814
Andrew Trick7fb669a2011-10-07 23:46:21 +0000815/// Determine if this is a well-behaved chain of instructions leading back to
816/// the PHI. If so, it may be reused by expanded expressions.
817bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
818 const Loop *L) {
819 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
820 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
821 return false;
822 // If any of the operands don't dominate the insert position, bail.
823 // Addrec operands are always loop-invariant, so this can only happen
824 // if there are instructions which haven't been hoisted.
825 if (L == IVIncInsertLoop) {
826 for (User::op_iterator OI = IncV->op_begin()+1,
827 OE = IncV->op_end(); OI != OE; ++OI)
828 if (Instruction *OInst = dyn_cast<Instruction>(OI))
829 if (!SE.DT->dominates(OInst, IVIncInsertPos))
830 return false;
831 }
832 // Advance to the next instruction.
833 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
834 if (!IncV)
835 return false;
836
837 if (IncV->mayHaveSideEffects())
838 return false;
839
840 if (IncV != PN)
841 return true;
842
843 return isNormalAddRecExprPHI(PN, IncV, L);
844}
845
Andrew Trickc908b432012-01-20 07:41:13 +0000846/// getIVIncOperand returns an induction variable increment's induction
847/// variable operand.
848///
849/// If allowScale is set, any type of GEP is allowed as long as the nonIV
850/// operands dominate InsertPos.
851///
852/// If allowScale is not set, ensure that a GEP increment conforms to one of the
853/// simple patterns generated by getAddRecExprPHILiterally and
854/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
855Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
856 Instruction *InsertPos,
857 bool allowScale) {
858 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000859 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000860
861 switch (IncV->getOpcode()) {
862 default:
Craig Topper9f008862014-04-15 04:59:12 +0000863 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000864 // Check for a simple Add/Sub or GEP of a loop invariant step.
865 case Instruction::Add:
866 case Instruction::Sub: {
867 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindola94df2672012-02-26 02:19:19 +0000868 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000869 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000870 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000871 }
872 case Instruction::BitCast:
873 return dyn_cast<Instruction>(IncV->getOperand(0));
874 case Instruction::GetElementPtr:
875 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
876 I != E; ++I) {
877 if (isa<Constant>(*I))
878 continue;
879 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000880 if (!SE.DT->dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000881 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000882 }
883 if (allowScale) {
884 // allow any kind of GEP as long as it can be hoisted.
885 continue;
886 }
887 // This must be a pointer addition of constants (pretty), which is already
888 // handled, or some number of address-size elements (ugly). Ugly geps
889 // have 2 operands. i1* is used by the expander to represent an
890 // address-size element.
891 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000892 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000893 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
894 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
895 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000896 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000897 break;
898 }
899 return dyn_cast<Instruction>(IncV->getOperand(0));
900 }
901}
902
903/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
904/// it available to other uses in this loop. Recursively hoist any operands,
905/// until we reach a value that dominates InsertPos.
906bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000907 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000908 return true;
909
910 // InsertPos must itself dominate IncV so that IncV's new position satisfies
911 // its existing users.
Andrew Tricka7a3de12012-05-22 17:39:59 +0000912 if (isa<PHINode>(InsertPos)
913 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000914 return false;
915
916 // Check that the chain of IV operands leading back to Phi can be hoisted.
917 SmallVector<Instruction*, 4> IVIncs;
918 for(;;) {
919 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
920 if (!Oper)
921 return false;
922 // IncV is safe to hoist.
923 IVIncs.push_back(IncV);
924 IncV = Oper;
Rafael Espindola94df2672012-02-26 02:19:19 +0000925 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000926 break;
927 }
928 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
929 E = IVIncs.rend(); I != E; ++I) {
930 (*I)->moveBefore(InsertPos);
931 }
932 return true;
933}
934
Andrew Trick7fb669a2011-10-07 23:46:21 +0000935/// Determine if this cyclic phi is in a form that would have been generated by
936/// LSR. We don't care if the phi was actually expanded in this pass, as long
937/// as it is in a low-cost form, for example, no implied multiplication. This
938/// should match any patterns generated by getAddRecExprPHILiterally and
939/// expandAddtoGEP.
940bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000941 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000942 for(Instruction *IVOper = IncV;
943 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
944 /*allowScale=*/false));) {
945 if (IVOper == PN)
946 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000947 }
Andrew Trickc908b432012-01-20 07:41:13 +0000948 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000949}
950
Andrew Trickceafa2c2011-11-30 06:07:54 +0000951/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
952/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
953/// need to materialize IV increments elsewhere to handle difficult situations.
954Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
955 Type *ExpandTy, Type *IntTy,
956 bool useSubtract) {
957 Value *IncV;
958 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
959 if (ExpandTy->isPointerTy()) {
960 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
961 // If the step isn't constant, don't use an implicitly scaled GEP, because
962 // that would require a multiply inside the loop.
963 if (!isa<ConstantInt>(StepV))
964 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
965 GEPPtrTy->getAddressSpace());
966 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
967 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
968 if (IncV->getType() != PN->getType()) {
969 IncV = Builder.CreateBitCast(IncV, PN->getType());
970 rememberInstruction(IncV);
971 }
972 } else {
973 IncV = useSubtract ?
974 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
975 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
976 rememberInstruction(IncV);
977 }
978 return IncV;
979}
980
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +0000981/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
982/// position. This routine assumes that this is possible (has been checked).
983static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
984 Instruction *Pos, PHINode *LoopPhi) {
985 do {
986 if (DT->dominates(InstToHoist, Pos))
987 break;
988 // Make sure the increment is where we want it. But don't move it
989 // down past a potential existing post-inc user.
990 InstToHoist->moveBefore(Pos);
991 Pos = InstToHoist;
992 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
993 } while (InstToHoist != LoopPhi);
994}
995
996/// \brief Check whether we can cheaply express the requested SCEV in terms of
997/// the available PHI SCEV by truncation and/or invertion of the step.
998static bool canBeCheaplyTransformed(ScalarEvolution &SE,
999 const SCEVAddRecExpr *Phi,
1000 const SCEVAddRecExpr *Requested,
1001 bool &InvertStep) {
1002 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1003 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1004
1005 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1006 return false;
1007
1008 // Try truncate it if necessary.
1009 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1010 if (!Phi)
1011 return false;
1012
1013 // Check whether truncation will help.
1014 if (Phi == Requested) {
1015 InvertStep = false;
1016 return true;
1017 }
1018
1019 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1020 if (SE.getAddExpr(Requested->getStart(),
1021 SE.getNegativeSCEV(Requested)) == Phi) {
1022 InvertStep = true;
1023 return true;
1024 }
1025
1026 return false;
1027}
1028
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001029static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1030 if (!isa<IntegerType>(AR->getType()))
1031 return false;
1032
1033 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1034 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1035 const SCEV *Step = AR->getStepRecurrence(SE);
1036 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1037 SE.getSignExtendExpr(AR, WideTy));
1038 const SCEV *ExtendAfterOp =
1039 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1040 return ExtendAfterOp == OpAfterExtend;
1041}
1042
1043static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1044 if (!isa<IntegerType>(AR->getType()))
1045 return false;
1046
1047 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1048 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1049 const SCEV *Step = AR->getStepRecurrence(SE);
1050 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1051 SE.getZeroExtendExpr(AR, WideTy));
1052 const SCEV *ExtendAfterOp =
1053 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1054 return ExtendAfterOp == OpAfterExtend;
1055}
1056
Dan Gohman51ad99d2010-01-21 02:09:26 +00001057/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1058/// the base addrec, which is the addrec without any non-loop-dominating
1059/// values, and return the PHI.
1060PHINode *
1061SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1062 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001063 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001064 Type *IntTy,
1065 Type *&TruncTy,
1066 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001067 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001068
Dan Gohman51ad99d2010-01-21 02:09:26 +00001069 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001070 BasicBlock *LatchBlock = L->getLoopLatch();
1071 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001072 PHINode *AddRecPhiMatch = nullptr;
1073 Instruction *IncV = nullptr;
1074 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001075 InvertStep = false;
1076
1077 // Only try partially matching scevs that need truncation and/or
1078 // step-inversion if we know this loop is outside the current loop.
1079 bool TryNonMatchingSCEV = IVIncInsertLoop &&
1080 SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1081
Andrew Trick7fb669a2011-10-07 23:46:21 +00001082 for (BasicBlock::iterator I = L->getHeader()->begin();
1083 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001084 if (!SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001085 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001086
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001087 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1088 if (!PhiSCEV)
1089 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001090
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001091 bool IsMatchingSCEV = PhiSCEV == Normalized;
1092 // We only handle truncation and inversion of phi recurrences for the
1093 // expanded expression if the expanded expression's loop dominates the
1094 // loop we insert to. Check now, so we can bail out early.
1095 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1096 continue;
1097
1098 Instruction *TempIncV =
1099 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1100
1101 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001102 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001103 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001104 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001105 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1106 continue;
1107 } else {
1108 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001109 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001110 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001111
1112 // Stop if we have found an exact match SCEV.
1113 if (IsMatchingSCEV) {
1114 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001115 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001116 InvertStep = false;
1117 AddRecPhiMatch = PN;
1118 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001119 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001120
1121 // Try whether the phi can be translated into the requested form
1122 // (truncated and/or offset by a constant).
1123 if ((!TruncTy || InvertStep) &&
1124 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1125 // Record the phi node. But don't stop we might find an exact match
1126 // later.
1127 AddRecPhiMatch = PN;
1128 IncV = TempIncV;
1129 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1130 }
1131 }
1132
1133 if (AddRecPhiMatch) {
1134 // Potentially, move the increment. We have made sure in
1135 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1136 if (L == IVIncInsertLoop)
1137 hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1138
Andrew Trick7fb669a2011-10-07 23:46:21 +00001139 // Ok, the add recurrence looks usable.
1140 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001141 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001142 // Remember the increment.
1143 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001144 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001145 }
1146 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001147
1148 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001149 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001150
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001151 // Another AddRec may need to be recursively expanded below. For example, if
1152 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1153 // loop. Remove this loop from the PostIncLoops set before expanding such
1154 // AddRecs. Otherwise, we cannot find a valid position for the step
1155 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1156 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1157 // so it's not worth implementing SmallPtrSet::swap.
1158 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1159 PostIncLoops.clear();
1160
Dan Gohman51ad99d2010-01-21 02:09:26 +00001161 // Expand code for the start value.
1162 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1163 L->getHeader()->begin());
1164
Andrew Trick244e2c32011-07-16 00:59:39 +00001165 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001166 assert(!isa<Instruction>(StartV) ||
1167 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1168 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001169
Andrew Trickceafa2c2011-11-30 06:07:54 +00001170 // Expand code for the step value. Do this before creating the PHI so that PHI
1171 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001172 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001173 // If the stride is negative, insert a sub instead of an add for the increment
1174 // (unless it's a constant, because subtracts of constants are canonicalized
1175 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001176 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001177 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001178 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001179 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001180 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1181
Sanjoy Das54ef8952015-02-26 19:51:35 +00001182 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1183 // we actually do emit an addition. It does not apply if we emit a
1184 // subtraction.
1185 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1186 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1187
Dan Gohman51ad99d2010-01-21 02:09:26 +00001188 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001189 BasicBlock *Header = L->getHeader();
1190 Builder.SetInsertPoint(Header, Header->begin());
1191 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001192 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001193 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001194 rememberInstruction(PN);
1195
1196 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001197 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001198 BasicBlock *Pred = *HPI;
1199
1200 // Add a start value.
1201 if (!L->contains(Pred)) {
1202 PN->addIncoming(StartV, Pred);
1203 continue;
1204 }
1205
Andrew Trickceafa2c2011-11-30 06:07:54 +00001206 // Create a step value and add it to the PHI.
1207 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1208 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001209 Instruction *InsertPos = L == IVIncInsertLoop ?
1210 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001211 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001212 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001213
Andrew Trick8eaae282013-07-14 02:50:07 +00001214 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001215 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001216 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001217 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001218 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1219 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001220 PN->addIncoming(IncV, Pred);
1221 }
1222
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001223 // After expanding subexpressions, restore the PostIncLoops set so the caller
1224 // can ensure that IVIncrement dominates the current uses.
1225 PostIncLoops = SavedPostIncLoops;
1226
Dan Gohman51ad99d2010-01-21 02:09:26 +00001227 // Remember this PHI, even in post-inc mode.
1228 InsertedValues.insert(PN);
1229
1230 return PN;
1231}
1232
1233Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001234 Type *STy = S->getType();
1235 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001236 const Loop *L = S->getLoop();
1237
1238 // Determine a normalized form of this expression, which is the expression
1239 // before any post-inc adjustment is made.
1240 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001241 if (PostIncLoops.count(L)) {
1242 PostIncLoopSet Loops;
1243 Loops.insert(L);
1244 Normalized =
Craig Topper9f008862014-04-15 04:59:12 +00001245 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
1246 nullptr, Loops, SE, *SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001247 }
1248
1249 // Strip off any non-loop-dominating component from the addrec start.
1250 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001251 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001252 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001253 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001254 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001255 Normalized = cast<SCEVAddRecExpr>(
1256 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1257 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001258 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001259 }
1260
1261 // Strip off any non-loop-dominating component from the addrec step.
1262 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001263 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001264 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001265 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001266 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001267 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001268 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1269 Start, Step, Normalized->getLoop(),
1270 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001271 }
1272
1273 // Expand the core addrec. If we need post-loop scaling, force it to
1274 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001275 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001276 // In some cases, we decide to reuse an existing phi node but need to truncate
1277 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001278 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001279 bool InvertStep = false;
1280 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1281 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001282
Dan Gohman8b0a4192010-03-01 17:49:51 +00001283 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001284 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001285 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001286 Result = PN;
1287 else {
1288 // In PostInc mode, use the post-incremented value.
1289 BasicBlock *LatchBlock = L->getLoopLatch();
1290 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1291 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001292
1293 // For an expansion to use the postinc form, the client must call
1294 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1295 // or dominated by IVIncInsertPos.
Andrew Trickceafa2c2011-11-30 06:07:54 +00001296 if (isa<Instruction>(Result)
1297 && !SE.DT->dominates(cast<Instruction>(Result),
1298 Builder.GetInsertPoint())) {
1299 // The induction variable's postinc expansion does not dominate this use.
1300 // IVUsers tries to prevent this case, so it is rare. However, it can
1301 // happen when an IVUser outside the loop is not dominated by the latch
1302 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1303 // all cases. Consider a phi outide whose operand is replaced during
1304 // expansion with the value of the postinc user. Without fundamentally
1305 // changing the way postinc users are tracked, the only remedy is
1306 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1307 // but hopefully expandCodeFor handles that.
1308 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001309 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001310 if (useSubtract)
1311 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001312 Value *StepV;
1313 {
1314 // Expand the step somewhere that dominates the loop header.
1315 BuilderType::InsertPointGuard Guard(Builder);
1316 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1317 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001318 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1319 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001320 }
1321
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001322 // We have decided to reuse an induction variable of a dominating loop. Apply
1323 // truncation and/or invertion of the step.
1324 if (TruncTy) {
1325 Type *ResTy = Result->getType();
1326 // Normalize the result type.
1327 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1328 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1329 // Truncate the result.
1330 if (TruncTy != Result->getType()) {
1331 Result = Builder.CreateTrunc(Result, TruncTy);
1332 rememberInstruction(Result);
1333 }
1334 // Invert the result.
1335 if (InvertStep) {
1336 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1337 Result);
1338 rememberInstruction(Result);
1339 }
1340 }
1341
Dan Gohman51ad99d2010-01-21 02:09:26 +00001342 // Re-apply any non-loop-dominating scale.
1343 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001344 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001345 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001346 Result = Builder.CreateMul(Result,
1347 expandCodeFor(PostLoopScale, IntTy));
1348 rememberInstruction(Result);
1349 }
1350
1351 // Re-apply any non-loop-dominating offset.
1352 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001353 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001354 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1355 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1356 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001357 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001358 Result = Builder.CreateAdd(Result,
1359 expandCodeFor(PostLoopOffset, IntTy));
1360 rememberInstruction(Result);
1361 }
1362 }
1363
1364 return Result;
1365}
1366
Dan Gohman056857a2009-04-18 17:56:28 +00001367Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001368 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1369
Chris Lattner229907c2011-07-18 04:54:35 +00001370 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001371 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001372
Dan Gohman426901a2009-06-13 16:25:49 +00001373 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001374 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001375 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001376 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001377 CanonicalIV = PN;
1378
1379 // Rewrite an AddRec in terms of the canonical induction variable, if
1380 // its type is more narrow.
1381 if (CanonicalIV &&
1382 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1383 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001384 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1385 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1386 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001387 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001388 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001389 BasicBlock::iterator NewInsertPt =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001390 std::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001391 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001392 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1393 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001394 ++NewInsertPt;
Craig Topper9f008862014-04-15 04:59:12 +00001395 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Dan Gohman426901a2009-06-13 16:25:49 +00001396 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001397 return V;
1398 }
1399
Nate Begeman2bca4d92005-07-30 00:12:19 +00001400 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001401 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001402 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001403 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001404 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1405 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001406
1407 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1408 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001409 const SCEV *Base = S->getStart();
1410 const SCEV *RestArray[1] = { Rest };
1411 // Dig into the expression to find the pointer base for a GEP.
1412 ExposePointerBase(Base, RestArray[0], SE);
1413 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001414 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001415 // Make sure the Base isn't something exotic, such as a multiplied
1416 // or divided pointer value. In those cases, the result type isn't
1417 // actually a pointer type.
1418 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1419 Value *StartV = expand(Base);
1420 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1421 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001422 }
1423 }
1424
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001425 // Just do a normal add. Pre-expand the operands to suppress folding.
1426 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1427 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001428 }
1429
Dan Gohmancd838702010-07-26 18:28:14 +00001430 // If we don't yet have a canonical IV, create one.
1431 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001432 // Create and insert the PHI node for the induction variable in the
1433 // specified loop.
1434 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001435 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001436 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1437 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001438 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001439
Hal Finkel3f5279c2013-08-18 00:16:23 +00001440 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001441 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001442 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001443 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001444 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001445 // There must be an incoming value for each predecessor, even the
1446 // duplicates!
1447 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001448 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001449 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001450
Gabor Greife82532a2010-07-09 15:40:10 +00001451 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001452 // Insert a unit add instruction right before the terminator
1453 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001454 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1455 "indvar.next",
1456 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001457 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001458 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001459 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001460 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001461 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001462 }
Gabor Greife82532a2010-07-09 15:40:10 +00001463 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001464 }
1465
Dan Gohmancd838702010-07-26 18:28:14 +00001466 // {0,+,1} --> Insert a canonical induction variable into the loop!
1467 if (S->isAffine() && S->getOperand(1)->isOne()) {
1468 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1469 "IVs with types different from the canonical IV should "
1470 "already have been handled!");
1471 return CanonicalIV;
1472 }
1473
Dan Gohman426901a2009-06-13 16:25:49 +00001474 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001475
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001476 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001477 if (S->isAffine()) // {0,+,F} --> i*F
1478 return
1479 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001480 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001481 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001482 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001483 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001484
1485 // If this is a chain of recurrences, turn it into a closed form, using the
1486 // folders, then expandCodeFor the closed form. This allows the folders to
1487 // simplify the expression without having to build a bunch of special code
1488 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001489 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001490
Dan Gohman426901a2009-06-13 16:25:49 +00001491 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001492 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001493 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001494 if (isa<SCEVAddRecExpr>(Ext))
1495 NewS = Ext;
1496
Dan Gohmanaf752342009-07-07 17:06:11 +00001497 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001498 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001499
Dan Gohman426901a2009-06-13 16:25:49 +00001500 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001501 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001502 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001503}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001504
Dan Gohman056857a2009-04-18 17:56:28 +00001505Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001506 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001507 Value *V = expandCodeFor(S->getOperand(),
1508 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001509 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001510 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001511 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001512}
1513
Dan Gohman056857a2009-04-18 17:56:28 +00001514Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001515 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001516 Value *V = expandCodeFor(S->getOperand(),
1517 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001518 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001519 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001520 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001521}
1522
Dan Gohman056857a2009-04-18 17:56:28 +00001523Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001524 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001525 Value *V = expandCodeFor(S->getOperand(),
1526 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001527 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001528 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001529 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001530}
1531
Dan Gohman056857a2009-04-18 17:56:28 +00001532Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001533 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001534 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001535 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1536 // In the case of mixed integer and pointer types, do the
1537 // rest of the comparisons as integer.
1538 if (S->getOperand(i)->getType() != Ty) {
1539 Ty = SE.getEffectiveSCEVType(Ty);
1540 LHS = InsertNoopCastOfTo(LHS, Ty);
1541 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001542 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001543 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001544 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001545 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001546 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001547 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001548 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001549 // In the case of mixed integer and pointer types, cast the
1550 // final result back to the pointer type.
1551 if (LHS->getType() != S->getType())
1552 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001553 return LHS;
1554}
1555
Dan Gohman056857a2009-04-18 17:56:28 +00001556Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001557 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001558 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001559 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1560 // In the case of mixed integer and pointer types, do the
1561 // rest of the comparisons as integer.
1562 if (S->getOperand(i)->getType() != Ty) {
1563 Ty = SE.getEffectiveSCEVType(Ty);
1564 LHS = InsertNoopCastOfTo(LHS, Ty);
1565 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001566 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001567 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001568 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001569 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001570 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001571 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001572 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001573 // In the case of mixed integer and pointer types, cast the
1574 // final result back to the pointer type.
1575 if (LHS->getType() != S->getType())
1576 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001577 return LHS;
1578}
1579
Chris Lattner229907c2011-07-18 04:54:35 +00001580Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001581 Instruction *IP) {
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001582 Builder.SetInsertPoint(IP->getParent(), IP);
1583 return expandCodeFor(SH, Ty);
1584}
1585
Chris Lattner229907c2011-07-18 04:54:35 +00001586Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001587 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001588 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001589 if (Ty) {
1590 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1591 "non-trivial casts should be done with the SCEVs directly!");
1592 V = InsertNoopCastOfTo(V, Ty);
1593 }
1594 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001595}
1596
Dan Gohman056857a2009-04-18 17:56:28 +00001597Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001598 // Compute an insertion point for this SCEV object. Hoist the instructions
1599 // as far out in the loop nest as possible.
Dan Gohman830fd382009-06-27 21:18:18 +00001600 Instruction *InsertPt = Builder.GetInsertPoint();
1601 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001602 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001603 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001604 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001605 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001606 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001607 else {
1608 // LSR sets the insertion point for AddRec start/step values to the
1609 // block start to simplify value reuse, even though it's an invalid
1610 // position. SCEVExpander must correct for this in all cases.
1611 InsertPt = L->getHeader()->getFirstInsertionPt();
1612 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001613 } else {
1614 // If the SCEV is computable at this level, insert it into the header
1615 // after the PHIs (and after any other instructions that we've inserted
1616 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001617 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1618 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickc908b432012-01-20 07:41:13 +00001619 while (InsertPt != Builder.GetInsertPoint()
1620 && (isInsertedInstruction(InsertPt)
1621 || isa<DbgInfoIntrinsic>(InsertPt))) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001622 InsertPt = std::next(BasicBlock::iterator(InsertPt));
Andrew Trickc908b432012-01-20 07:41:13 +00001623 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001624 break;
1625 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001626
Dan Gohmandaafbe62009-06-26 22:53:46 +00001627 // Check to see if we already expanded this here.
Andrew Trickd4e1b5e2013-01-14 21:00:37 +00001628 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1629 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001630 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001631 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001632
Benjamin Kramer6e931522013-09-30 15:40:17 +00001633 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman830fd382009-06-27 21:18:18 +00001634 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001635
1636 // Expand the expression into instructions.
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001637 Value *V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001638
Dan Gohmandaafbe62009-06-26 22:53:46 +00001639 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001640 //
1641 // This is independent of PostIncLoops. The mapped value simply materializes
1642 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001643 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001644 // its insertion point was already at the head of the loop.
1645 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001646 return V;
1647}
Dan Gohman63964b52009-06-05 16:35:53 +00001648
Dan Gohman6b751732010-02-14 03:12:47 +00001649void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001650 if (!PostIncLoops.empty())
1651 InsertedPostIncValues.insert(I);
1652 else
Dan Gohman6b751732010-02-14 03:12:47 +00001653 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001654}
1655
Dan Gohman63964b52009-06-05 16:35:53 +00001656/// getOrInsertCanonicalInductionVariable - This method returns the
1657/// canonical induction variable of the specified type for the specified
1658/// loop (inserting one if there is none). A canonical induction variable
1659/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001660PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001661SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001662 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001663 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001664
1665 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001666 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001667 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001668 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001669
1670 // Emit code for it.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001671 BuilderType::InsertPointGuard Guard(Builder);
Craig Topper9f008862014-04-15 04:59:12 +00001672 PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
1673 L->getHeader()->begin()));
Dan Gohman31158752010-07-20 16:46:58 +00001674
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001675 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001676}
Andrew Trickf9201c52011-10-11 02:28:51 +00001677
Andrew Trickf9201c52011-10-11 02:28:51 +00001678/// replaceCongruentIVs - Check for congruent phis in this loop header and
1679/// replace them with their most canonical representative. Return the number of
1680/// phis eliminated.
1681///
1682/// This does not depend on any SCEVExpander state but should be used in
1683/// the same context that SCEVExpander is used.
1684unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001685 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001686 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001687 // Find integer phis in order of increasing width.
1688 SmallVector<PHINode*, 8> Phis;
1689 for (BasicBlock::iterator I = L->getHeader()->begin();
1690 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1691 Phis.push_back(Phi);
1692 }
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001693 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001694 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1695 // Put pointers at the back and make sure pointer < pointer = false.
1696 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1697 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1698 return RHS->getType()->getPrimitiveSizeInBits() <
1699 LHS->getType()->getPrimitiveSizeInBits();
1700 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001701
Andrew Trickf9201c52011-10-11 02:28:51 +00001702 unsigned NumElim = 0;
1703 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick5adedf52012-01-07 01:12:09 +00001704 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1705 // so narrow phis can reuse them.
1706 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1707 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1708 PHINode *Phi = *PIter;
1709
Benjamin Kramera225ed82012-10-19 16:37:30 +00001710 // Fold constant phis. They may be congruent to other constant phis and
1711 // would confuse the logic below that expects proper IVs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 if (Value *V = SimplifyInstruction(Phi, DL, SE.TLI, SE.DT, SE.AC)) {
Benjamin Kramera225ed82012-10-19 16:37:30 +00001713 Phi->replaceAllUsesWith(V);
1714 DeadInsts.push_back(Phi);
1715 ++NumElim;
1716 DEBUG_WITH_TYPE(DebugType, dbgs()
1717 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1718 continue;
1719 }
1720
Andrew Trickf9201c52011-10-11 02:28:51 +00001721 if (!SE.isSCEVable(Phi->getType()))
1722 continue;
1723
1724 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1725 if (!OrigPhiRef) {
1726 OrigPhiRef = Phi;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001727 if (Phi->getType()->isIntegerTy() && TTI
1728 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001729 // This phi can be freely truncated to the narrowest phi type. Map the
1730 // truncated expression to it so it will be reused for narrow types.
1731 const SCEV *TruncExpr =
1732 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1733 ExprToIVMap[TruncExpr] = Phi;
1734 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001735 continue;
1736 }
1737
Andrew Trick5adedf52012-01-07 01:12:09 +00001738 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1739 // sense.
1740 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001741 continue;
1742
1743 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1744 Instruction *OrigInc =
1745 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1746 Instruction *IsomorphicInc =
1747 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1748
Andrew Trick5adedf52012-01-07 01:12:09 +00001749 // If this phi has the same width but is more canonical, replace the
Andrew Trickc908b432012-01-20 07:41:13 +00001750 // original with it. As part of the "more canonical" determination,
1751 // respect a prior decision to use an IV chain.
Andrew Trick5adedf52012-01-07 01:12:09 +00001752 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickc908b432012-01-20 07:41:13 +00001753 && !(ChainedPhis.count(Phi)
1754 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1755 && (ChainedPhis.count(Phi)
1756 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001757 std::swap(OrigPhiRef, Phi);
1758 std::swap(OrigInc, IsomorphicInc);
1759 }
1760 // Replacing the congruent phi is sufficient because acyclic redundancy
1761 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1762 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trickf730f392012-01-07 01:29:21 +00001763 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1764 // common case of a single IV increment so that DeleteDeadPHIs can remove
1765 // cycles that had postinc uses.
Andrew Trick5adedf52012-01-07 01:12:09 +00001766 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1767 IsomorphicInc->getType());
1768 if (OrigInc != IsomorphicInc
Andrew Trickd5d2db92012-01-10 01:45:08 +00001769 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickc908b432012-01-20 07:41:13 +00001770 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1771 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001772 DEBUG_WITH_TYPE(DebugType, dbgs()
1773 << "INDVARS: Eliminated congruent iv.inc: "
1774 << *IsomorphicInc << '\n');
Andrew Trick5adedf52012-01-07 01:12:09 +00001775 Value *NewInc = OrigInc;
1776 if (OrigInc->getType() != IsomorphicInc->getType()) {
Sanjoy Dasf1e9e1d2015-03-13 18:31:19 +00001777 Instruction *IP = nullptr;
1778 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1779 IP = PN->getParent()->getFirstInsertionPt();
1780 else
1781 IP = OrigInc->getNextNode();
1782
Andrew Trick23ef0d62012-01-14 03:17:23 +00001783 IRBuilder<> Builder(IP);
Andrew Trick5adedf52012-01-07 01:12:09 +00001784 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1785 NewInc = Builder.
1786 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1787 }
1788 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trickf9201c52011-10-11 02:28:51 +00001789 DeadInsts.push_back(IsomorphicInc);
1790 }
1791 }
1792 DEBUG_WITH_TYPE(DebugType, dbgs()
1793 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1794 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001795 Value *NewIV = OrigPhiRef;
1796 if (OrigPhiRef->getType() != Phi->getType()) {
1797 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1798 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1799 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1800 }
1801 Phi->replaceAllUsesWith(NewIV);
Andrew Trickf9201c52011-10-11 02:28:51 +00001802 DeadInsts.push_back(Phi);
1803 }
1804 return NumElim;
1805}
Andrew Trick653513b2012-07-13 23:33:10 +00001806
1807namespace {
1808// Search for a SCEV subexpression that is not safe to expand. Any expression
1809// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1810// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1811// instruction, but the important thing is that we prove the denominator is
1812// nonzero before expansion.
1813//
1814// IVUsers already checks that IV-derived expressions are safe. So this check is
1815// only needed when the expression includes some subexpression that is not IV
1816// derived.
1817//
1818// Currently, we only allow division by a nonzero constant here. If this is
1819// inadequate, we could easily allow division by SCEVUnknown by using
1820// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00001821//
1822// We cannot generally expand recurrences unless the step dominates the loop
1823// header. The expander handles the special case of affine recurrences by
1824// scaling the recurrence outside the loop, but this technique isn't generally
1825// applicable. Expanding a nested recurrence outside a loop requires computing
1826// binomial coefficients. This could be done, but the recurrence has to be in a
1827// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00001828struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00001829 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00001830 bool IsUnsafe;
1831
Andrew Trick57243da2013-10-25 21:35:56 +00001832 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00001833
1834 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00001835 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1836 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1837 if (!SC || SC->getValue()->isZero()) {
1838 IsUnsafe = true;
1839 return false;
1840 }
1841 }
1842 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1843 const SCEV *Step = AR->getStepRecurrence(SE);
1844 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1845 IsUnsafe = true;
1846 return false;
1847 }
1848 }
1849 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00001850 }
1851 bool isDone() const { return IsUnsafe; }
1852};
1853}
1854
1855namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00001856bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
1857 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00001858 visitAll(S, Search);
1859 return !Search.IsUnsafe;
1860}
1861}