blob: d0b3643113073166be1575678411ad25649dec54 [file] [log] [blame]
Nate Begeman2bca4d92005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman2bca4d92005-07-30 00:12:19 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution expander,
11// which is used to generate the code corresponding to a given scalar evolution
12// expression.
13//
14//===----------------------------------------------------------------------===//
15
Nate Begeman2bca4d92005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallSet.h"
Benjamin Kramer8dd637a2014-06-21 11:47:18 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/LLVMContext.h"
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +000026#include "llvm/IR/Module.h"
Jingyue Wu6f72aed2015-06-24 19:28:40 +000027#include "llvm/IR/PatternMatch.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000028#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/Support/raw_ostream.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000030
Nate Begeman2bca4d92005-07-30 00:12:19 +000031using namespace llvm;
Jingyue Wu6f72aed2015-06-24 19:28:40 +000032using namespace PatternMatch;
Nate Begeman2bca4d92005-07-30 00:12:19 +000033
Gabor Greif8e66a422010-07-09 16:42:04 +000034/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000035/// reusing an existing cast if a suitable one exists, moving an existing
36/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000037/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000038Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000039 Instruction::CastOps Op,
40 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000041 // This function must be called with the builder having a valid insertion
42 // point. It doesn't need to be the actual IP where the uses of the returned
43 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000044 // We use this precondition to produce a cast that will dominate all its
45 // uses. In particular, this is crucial for the case where the builder's
46 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000047 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000048 // where the uses will be added (only that it dominates it), we are
49 // not allowed to move it.
50 BasicBlock::iterator BIP = Builder.GetInsertPoint();
51
Craig Topper9f008862014-04-15 04:59:12 +000052 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000053
Dan Gohmand2772462010-06-19 13:25:23 +000054 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000055 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000056 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000057 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000058 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000059 // If the cast isn't where we want it, create a new cast at IP.
60 // Likewise, do not reuse a cast at BIP because it must dominate
61 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000062 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000063 // Create a new cast, and leave the old cast in place in case
64 // it is being used as an insert point. Clear its operand
65 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000066 Ret = CastInst::Create(Op, V, Ty, "", IP);
67 Ret->takeName(CI);
68 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000069 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000070 break;
Dan Gohmand2772462010-06-19 13:25:23 +000071 }
Rafael Espindola09a42012012-02-27 02:13:03 +000072 Ret = CI;
73 break;
Dan Gohmand2772462010-06-19 13:25:23 +000074 }
75
76 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000077 if (!Ret)
78 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
79
80 // We assert at the end of the function since IP might point to an
81 // instruction with different dominance properties than a cast
82 // (an invoke for example) and not dominate BIP (but the cast does).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000083 assert(SE.DT.dominates(Ret, BIP));
Rafael Espindola09a42012012-02-27 02:13:03 +000084
85 rememberInstruction(Ret);
86 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000087}
88
Dan Gohman830fd382009-06-27 21:18:18 +000089/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
90/// which must be possible with a noop cast, doing what we can to share
91/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +000092Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +000093 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
94 assert((Op == Instruction::BitCast ||
95 Op == Instruction::PtrToInt ||
96 Op == Instruction::IntToPtr) &&
97 "InsertNoopCastOfTo cannot perform non-noop casts!");
98 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
99 "InsertNoopCastOfTo cannot change sizes!");
100
Dan Gohman0a40ad92009-04-16 03:18:22 +0000101 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +0000102 if (Op == Instruction::BitCast) {
103 if (V->getType() == Ty)
104 return V;
105 if (CastInst *CI = dyn_cast<CastInst>(V)) {
106 if (CI->getOperand(0)->getType() == Ty)
107 return CI->getOperand(0);
108 }
109 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000110 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000111 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000112 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000113 if (CastInst *CI = dyn_cast<CastInst>(V))
114 if ((CI->getOpcode() == Instruction::PtrToInt ||
115 CI->getOpcode() == Instruction::IntToPtr) &&
116 SE.getTypeSizeInBits(CI->getType()) ==
117 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
118 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
120 if ((CE->getOpcode() == Instruction::PtrToInt ||
121 CE->getOpcode() == Instruction::IntToPtr) &&
122 SE.getTypeSizeInBits(CE->getType()) ==
123 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
124 return CE->getOperand(0);
125 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000126
Dan Gohmand2772462010-06-19 13:25:23 +0000127 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000128 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000129 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000130
Dan Gohmand2772462010-06-19 13:25:23 +0000131 // Cast the argument at the beginning of the entry block, after
132 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000133 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000134 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
135 while ((isa<BitCastInst>(IP) &&
136 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
137 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000138 isa<DbgInfoIntrinsic>(IP) ||
139 isa<LandingPadInst>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000140 ++IP;
141 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000142 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000143
Dan Gohmand2772462010-06-19 13:25:23 +0000144 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000145 Instruction *I = cast<Instruction>(V);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000146 BasicBlock::iterator IP = I; ++IP;
147 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
148 IP = II->getNormalDest()->begin();
David Majnemer0bc0eef2015-08-15 02:46:08 +0000149 if (CatchPadInst *CPI = dyn_cast<CatchPadInst>(I))
150 IP = CPI->getNormalDest()->begin();
Rafael Espindola82d95752012-02-18 17:22:58 +0000151 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000152 ++IP;
Dan Gohmand2772462010-06-19 13:25:23 +0000153 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000154}
155
Chris Lattnere71f1442007-04-13 05:04:18 +0000156/// InsertBinop - Insert the specified binary operator, doing a small amount
157/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000158Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
159 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000160 // Fold a binop with constant operands.
161 if (Constant *CLHS = dyn_cast<Constant>(LHS))
162 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000163 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000164
Chris Lattnere71f1442007-04-13 05:04:18 +0000165 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
166 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000167 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
168 // Scanning starts from the last instruction before the insertion point.
169 BasicBlock::iterator IP = Builder.GetInsertPoint();
170 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000171 --IP;
172 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000173 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
174 // generated code.
175 if (isa<DbgInfoIntrinsic>(IP))
176 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000177 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
178 IP->getOperand(1) == RHS)
179 return IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000180 if (IP == BlockBegin) break;
181 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000182 }
Dan Gohman830fd382009-06-27 21:18:18 +0000183
Dan Gohman29707de2010-03-03 05:29:13 +0000184 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000185 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
186 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000187
188 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000189 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000190 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
191 BasicBlock *Preheader = L->getLoopPreheader();
192 if (!Preheader) break;
193
194 // Ok, move up a level.
195 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
196 }
197
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000198 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000199 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000200 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000201 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000202
Dan Gohmand195a222009-05-01 17:13:31 +0000203 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000204}
205
Dan Gohman17893622009-05-27 02:00:53 +0000206/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000207/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000208/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000209/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000210/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
211/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
212/// check to see if the divide was folded.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000213static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
214 const SCEV *Factor, ScalarEvolution &SE,
215 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000216 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000217 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000218 return true;
219
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000220 // x/x == 1.
221 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000222 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000223 return true;
224 }
225
Dan Gohman291c2e02009-05-24 18:06:31 +0000226 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000227 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000228 // 0/x == 0.
229 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000230 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000231 // Check for divisibility.
232 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
233 ConstantInt *CI =
234 ConstantInt::get(SE.getContext(),
235 C->getValue()->getValue().sdiv(
236 FC->getValue()->getValue()));
237 // If the quotient is zero and the remainder is non-zero, reject
238 // the value at this scale. It will be considered for subsequent
239 // smaller scales.
240 if (!CI->isZero()) {
241 const SCEV *Div = SE.getConstant(CI);
242 S = Div;
243 Remainder =
244 SE.getAddExpr(Remainder,
245 SE.getConstant(C->getValue()->getValue().srem(
246 FC->getValue()->getValue())));
247 return true;
248 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000249 }
Dan Gohman17893622009-05-27 02:00:53 +0000250 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000251
252 // In a Mul, check if there is a constant operand which is a multiple
253 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000254 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000255 // Size is known, check if there is a constant operand which is a multiple
256 // of the given factor. If so, we can factor it.
257 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
258 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
259 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
260 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
261 NewMulOps[0] = SE.getConstant(
262 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
263 S = SE.getMulExpr(NewMulOps);
264 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000265 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000266 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000267
268 // In an AddRec, check if both start and step are divisible.
269 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000270 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000271 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000272 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000273 return false;
274 if (!StepRem->isZero())
275 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000276 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000277 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000278 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000279 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
280 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000281 return true;
282 }
283
284 return false;
285}
286
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000287/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
288/// is the number of SCEVAddRecExprs present, which are kept at the end of
289/// the list.
290///
291static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000292 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000293 ScalarEvolution &SE) {
294 unsigned NumAddRecs = 0;
295 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
296 ++NumAddRecs;
297 // Group Ops into non-addrecs and addrecs.
298 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
299 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
300 // Let ScalarEvolution sort and simplify the non-addrecs list.
301 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000302 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000303 SE.getAddExpr(NoAddRecs);
304 // If it returned an add, use the operands. Otherwise it simplified
305 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000306 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000307 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000308 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000309 else if (!Sum->isZero())
310 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000311 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000312 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000313}
314
315/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
316/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
317/// This helps expose more opportunities for folding parts of the expressions
318/// into GEP indices.
319///
320static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000321 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000322 ScalarEvolution &SE) {
323 // Find the addrecs.
324 SmallVector<const SCEV *, 8> AddRecs;
325 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
326 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
327 const SCEV *Start = A->getStart();
328 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000329 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000330 AddRecs.push_back(SE.getAddRecExpr(Zero,
331 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000332 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000333 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000334 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
335 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000336 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000337 e += Add->getNumOperands();
338 } else {
339 Ops[i] = Start;
340 }
341 }
342 if (!AddRecs.empty()) {
343 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000344 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000345 // Resort the operand list, moving any constants to the front.
346 SimplifyAddOperands(Ops, Ty, SE);
347 }
348}
349
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000350/// expandAddToGEP - Expand an addition expression with a pointer type into
351/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
352/// BasicAliasAnalysis and other passes analyze the result. See the rules
353/// for getelementptr vs. inttoptr in
354/// http://llvm.org/docs/LangRef.html#pointeraliasing
355/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000356///
Dan Gohman510bffc2010-01-19 22:26:02 +0000357/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000358/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
359/// they may introduce pointer arithmetic which may not be safely converted
360/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000361///
362/// Design note: It might seem desirable for this function to be more
363/// loop-aware. If some of the indices are loop-invariant while others
364/// aren't, it might seem desirable to emit multiple GEPs, keeping the
365/// loop-invariant portions of the overall computation outside the loop.
366/// However, there are a few reasons this is not done here. Hoisting simple
367/// arithmetic is a low-level optimization that often isn't very
368/// important until late in the optimization process. In fact, passes
369/// like InstructionCombining will combine GEPs, even if it means
370/// pushing loop-invariant computation down into loops, so even if the
371/// GEPs were split here, the work would quickly be undone. The
372/// LoopStrengthReduction pass, which is usually run quite late (and
373/// after the last InstructionCombining pass), takes care of hoisting
374/// loop-invariant portions of expressions, after considering what
375/// can be folded using target addressing modes.
376///
Dan Gohmanaf752342009-07-07 17:06:11 +0000377Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
378 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000379 PointerType *PTy,
380 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000381 Value *V) {
David Blaikie156d46e2015-03-24 23:34:31 +0000382 Type *OriginalElTy = PTy->getElementType();
383 Type *ElTy = OriginalElTy;
Dan Gohman26494912009-05-19 02:15:55 +0000384 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000385 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000386 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000387
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000388 // Split AddRecs up into parts as either of the parts may be usable
389 // without the other.
390 SplitAddRecs(Ops, Ty, SE);
391
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000393
Bob Wilson2107eb72009-12-04 01:33:04 +0000394 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000395 // operands into GEP indices, at each level. The first index in a GEP
396 // indexes into the array implied by the pointer operand; the rest of
397 // the indices index into the element or field type selected by the
398 // preceding index.
399 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000400 // If the scale size is not 0, attempt to factor out a scale for
401 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000402 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000403 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000404 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000405 if (!ElSize->isZero()) {
406 SmallVector<const SCEV *, 8> NewOps;
407 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
408 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000409 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000410 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000411 // Op now has ElSize factored out.
412 ScaledOps.push_back(Op);
413 if (!Remainder->isZero())
414 NewOps.push_back(Remainder);
415 AnyNonZeroIndices = true;
416 } else {
417 // The operand was not divisible, so add it to the list of operands
418 // we'll scan next iteration.
419 NewOps.push_back(Ops[i]);
420 }
Dan Gohman26494912009-05-19 02:15:55 +0000421 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000422 // If we made any changes, update Ops.
423 if (!ScaledOps.empty()) {
424 Ops = NewOps;
425 SimplifyAddOperands(Ops, Ty, SE);
426 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000427 }
Dan Gohman26494912009-05-19 02:15:55 +0000428 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000429
430 // Record the scaled array index for this level of the type. If
431 // we didn't find any operands that could be factored, tentatively
432 // assume that element zero was selected (since the zero offset
433 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000434 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000435 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000436 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
437 GepIndices.push_back(Scaled);
438
439 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000440 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000441 bool FoundFieldNo = false;
442 // An empty struct has no fields.
443 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000444 // Field offsets are known. See if a constant offset falls within any of
445 // the struct fields.
446 if (Ops.empty())
447 break;
448 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
449 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
450 const StructLayout &SL = *DL.getStructLayout(STy);
451 uint64_t FullOffset = C->getValue()->getZExtValue();
452 if (FullOffset < SL.getSizeInBytes()) {
453 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
454 GepIndices.push_back(
455 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
456 ElTy = STy->getTypeAtIndex(ElIdx);
457 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000458 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 AnyNonZeroIndices = true;
460 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000461 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000462 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000463 // If no struct field offsets were found, tentatively assume that
464 // field zero was selected (since the zero offset would obviously
465 // be folded away).
466 if (!FoundFieldNo) {
467 ElTy = STy->getTypeAtIndex(0u);
468 GepIndices.push_back(
469 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
470 }
Dan Gohman26494912009-05-19 02:15:55 +0000471 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000472
Chris Lattner229907c2011-07-18 04:54:35 +0000473 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000474 ElTy = ATy->getElementType();
475 else
476 break;
Dan Gohman26494912009-05-19 02:15:55 +0000477 }
478
Dan Gohman8b0a4192010-03-01 17:49:51 +0000479 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000480 // the base to i8* and do an ugly getelementptr with that. It's still
481 // better than ptrtoint+arithmetic+inttoptr at least.
482 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000483 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000484 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000485 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000486
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000487 assert(!isa<Instruction>(V) ||
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000488 SE.DT.dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000489
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000490 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000491 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000492
493 // Fold a GEP with constant operands.
494 if (Constant *CLHS = dyn_cast<Constant>(V))
495 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie4a2e73b2015-04-02 18:55:32 +0000496 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
497 CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000498
499 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
500 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000501 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
502 // Scanning starts from the last instruction before the insertion point.
503 BasicBlock::iterator IP = Builder.GetInsertPoint();
504 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000505 --IP;
506 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000507 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
508 // generated code.
509 if (isa<DbgInfoIntrinsic>(IP))
510 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000511 if (IP->getOpcode() == Instruction::GetElementPtr &&
512 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
513 return IP;
514 if (IP == BlockBegin) break;
515 }
516 }
517
Dan Gohman29707de2010-03-03 05:29:13 +0000518 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000519 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000520
521 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000522 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000523 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
524 BasicBlock *Preheader = L->getLoopPreheader();
525 if (!Preheader) break;
526
527 // Ok, move up a level.
528 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
529 }
530
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000531 // Emit a GEP.
David Blaikie93c54442015-04-03 19:41:44 +0000532 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000533 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000534
Dan Gohman26494912009-05-19 02:15:55 +0000535 return GEP;
536 }
537
Dan Gohman29707de2010-03-03 05:29:13 +0000538 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000539 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000540
541 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000542 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000543 if (!L->isLoopInvariant(V)) break;
544
545 bool AnyIndexNotLoopInvariant = false;
546 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
547 E = GepIndices.end(); I != E; ++I)
548 if (!L->isLoopInvariant(*I)) {
549 AnyIndexNotLoopInvariant = true;
550 break;
551 }
552 if (AnyIndexNotLoopInvariant)
553 break;
554
555 BasicBlock *Preheader = L->getLoopPreheader();
556 if (!Preheader) break;
557
558 // Ok, move up a level.
559 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
560 }
561
Dan Gohman31a9b982009-07-28 01:40:03 +0000562 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
563 // because ScalarEvolution may have changed the address arithmetic to
564 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000565 Value *Casted = V;
566 if (V->getType() != PTy)
567 Casted = InsertNoopCastOfTo(Casted, PTy);
David Blaikie156d46e2015-03-24 23:34:31 +0000568 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000569 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000570 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000571 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000572 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000573
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000574 // Restore the original insert point.
575 Builder.restoreIP(SaveInsertPt);
576
Dan Gohman26494912009-05-19 02:15:55 +0000577 return expand(SE.getAddExpr(Ops));
578}
579
Dan Gohman29707de2010-03-03 05:29:13 +0000580/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
581/// SCEV expansion. If they are nested, this is the most nested. If they are
582/// neighboring, pick the later.
583static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
584 DominatorTree &DT) {
585 if (!A) return B;
586 if (!B) return A;
587 if (A->contains(B)) return B;
588 if (B->contains(A)) return A;
589 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
590 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
591 return A; // Arbitrarily break the tie.
592}
593
Dan Gohman8ea83d82010-11-18 00:34:22 +0000594/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000595/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000596const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
597 // Test whether we've already computed the most relevant loop for this SCEV.
598 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
Craig Topper9f008862014-04-15 04:59:12 +0000599 RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000600 if (!Pair.second)
601 return Pair.first->second;
602
Dan Gohman29707de2010-03-03 05:29:13 +0000603 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000604 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000605 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000606 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
607 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000608 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
Dan Gohman8ea83d82010-11-18 00:34:22 +0000609 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000610 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000611 }
612 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000613 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000614 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
615 L = AR->getLoop();
616 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
617 I != E; ++I)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000618 L = PickMostRelevantLoop(L, getRelevantLoop(*I), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000619 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000620 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000621 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
622 const Loop *Result = getRelevantLoop(C->getOperand());
623 return RelevantLoops[C] = Result;
624 }
625 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000626 const Loop *Result = PickMostRelevantLoop(
627 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000628 return RelevantLoops[D] = Result;
629 }
Dan Gohman29707de2010-03-03 05:29:13 +0000630 llvm_unreachable("Unexpected SCEV type!");
631}
632
Dan Gohmanb29cda92010-04-15 17:08:50 +0000633namespace {
634
Dan Gohman29707de2010-03-03 05:29:13 +0000635/// LoopCompare - Compare loops by PickMostRelevantLoop.
636class LoopCompare {
637 DominatorTree &DT;
638public:
639 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
640
641 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
642 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000643 // Keep pointer operands sorted at the end.
644 if (LHS.second->getType()->isPointerTy() !=
645 RHS.second->getType()->isPointerTy())
646 return LHS.second->getType()->isPointerTy();
647
Dan Gohman29707de2010-03-03 05:29:13 +0000648 // Compare loops with PickMostRelevantLoop.
649 if (LHS.first != RHS.first)
650 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
651
652 // If one operand is a non-constant negative and the other is not,
653 // put the non-constant negative on the right so that a sub can
654 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000655 if (LHS.second->isNonConstantNegative()) {
656 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000657 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000658 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000659 return true;
660
661 // Otherwise they are equivalent according to this comparison.
662 return false;
663 }
664};
665
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000666}
Dan Gohmanb29cda92010-04-15 17:08:50 +0000667
Dan Gohman056857a2009-04-18 17:56:28 +0000668Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000669 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000670
Dan Gohman29707de2010-03-03 05:29:13 +0000671 // Collect all the add operands in a loop, along with their associated loops.
672 // Iterate in reverse so that constants are emitted last, all else equal, and
673 // so that pointer operands are inserted first, which the code below relies on
674 // to form more involved GEPs.
675 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
676 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
677 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000678 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000679
Dan Gohman29707de2010-03-03 05:29:13 +0000680 // Sort by loop. Use a stable sort so that constants follow non-constants and
681 // pointer operands precede non-pointer operands.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000682 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000683
Dan Gohman29707de2010-03-03 05:29:13 +0000684 // Emit instructions to add all the operands. Hoist as much as possible
685 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000686 Value *Sum = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000687 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
688 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
689 const Loop *CurLoop = I->first;
690 const SCEV *Op = I->second;
691 if (!Sum) {
692 // This is the first operand. Just expand it.
693 Sum = expand(Op);
694 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000695 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000696 // The running sum expression is a pointer. Try to form a getelementptr
697 // at this level with that as the base.
698 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000699 for (; I != E && I->first == CurLoop; ++I) {
700 // If the operand is SCEVUnknown and not instructions, peek through
701 // it, to enable more of it to be folded into the GEP.
702 const SCEV *X = I->second;
703 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
704 if (!isa<Instruction>(U->getValue()))
705 X = SE.getSCEV(U->getValue());
706 NewOps.push_back(X);
707 }
Dan Gohman29707de2010-03-03 05:29:13 +0000708 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000709 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000710 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000711 // Try to form a getelementptr. If the running sum is instructions,
712 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000713 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000714 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
715 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000716 for (++I; I != E && I->first == CurLoop; ++I)
717 NewOps.push_back(I->second);
718 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000719 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000720 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000721 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000722 Sum = InsertNoopCastOfTo(Sum, Ty);
723 Sum = InsertBinop(Instruction::Sub, Sum, W);
724 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000725 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000726 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000727 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000728 Sum = InsertNoopCastOfTo(Sum, Ty);
729 // Canonicalize a constant to the RHS.
730 if (isa<Constant>(Sum)) std::swap(Sum, W);
731 Sum = InsertBinop(Instruction::Add, Sum, W);
732 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000733 }
734 }
Dan Gohman29707de2010-03-03 05:29:13 +0000735
736 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000737}
Dan Gohman26494912009-05-19 02:15:55 +0000738
Dan Gohman056857a2009-04-18 17:56:28 +0000739Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000740 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000741
Dan Gohman29707de2010-03-03 05:29:13 +0000742 // Collect all the mul operands in a loop, along with their associated loops.
743 // Iterate in reverse so that constants are emitted last, all else equal.
744 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
745 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
746 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000747 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000748
Dan Gohman29707de2010-03-03 05:29:13 +0000749 // Sort by loop. Use a stable sort so that constants follow non-constants.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000750 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman29707de2010-03-03 05:29:13 +0000751
752 // Emit instructions to mul all the operands. Hoist as much as possible
753 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000754 Value *Prod = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000755 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
Jingyue Wu6f72aed2015-06-24 19:28:40 +0000756 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ++I) {
Dan Gohman29707de2010-03-03 05:29:13 +0000757 const SCEV *Op = I->second;
758 if (!Prod) {
759 // This is the first operand. Just expand it.
760 Prod = expand(Op);
Dan Gohman29707de2010-03-03 05:29:13 +0000761 } else if (Op->isAllOnesValue()) {
762 // Instead of doing a multiply by negative one, just do a negate.
763 Prod = InsertNoopCastOfTo(Prod, Ty);
764 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
Dan Gohman29707de2010-03-03 05:29:13 +0000765 } else {
766 // A simple mul.
767 Value *W = expandCodeFor(Op, Ty);
768 Prod = InsertNoopCastOfTo(Prod, Ty);
769 // Canonicalize a constant to the RHS.
770 if (isa<Constant>(Prod)) std::swap(Prod, W);
Jingyue Wu6f72aed2015-06-24 19:28:40 +0000771 const APInt *RHS;
772 if (match(W, m_Power2(RHS))) {
773 // Canonicalize Prod*(1<<C) to Prod<<C.
774 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
775 Prod = InsertBinop(Instruction::Shl, Prod,
776 ConstantInt::get(Ty, RHS->logBase2()));
777 } else {
778 Prod = InsertBinop(Instruction::Mul, Prod, W);
779 }
Dan Gohman29707de2010-03-03 05:29:13 +0000780 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000781 }
782
Dan Gohman29707de2010-03-03 05:29:13 +0000783 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000784}
785
Dan Gohman056857a2009-04-18 17:56:28 +0000786Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000787 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000788
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000789 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000791 const APInt &RHS = SC->getValue()->getValue();
792 if (RHS.isPowerOf2())
793 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000794 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000795 }
796
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000797 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000798 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000799}
800
Dan Gohman291c2e02009-05-24 18:06:31 +0000801/// Move parts of Base into Rest to leave Base with the minimal
802/// expression that provides a pointer operand suitable for a
803/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000804static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000805 ScalarEvolution &SE) {
806 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
807 Base = A->getStart();
808 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000809 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000810 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000811 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000812 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000813 }
814 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
815 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000816 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000817 NewAddOps.back() = Rest;
818 Rest = SE.getAddExpr(NewAddOps);
819 ExposePointerBase(Base, Rest, SE);
820 }
821}
822
Andrew Trick7fb669a2011-10-07 23:46:21 +0000823/// Determine if this is a well-behaved chain of instructions leading back to
824/// the PHI. If so, it may be reused by expanded expressions.
825bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
826 const Loop *L) {
827 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
828 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
829 return false;
830 // If any of the operands don't dominate the insert position, bail.
831 // Addrec operands are always loop-invariant, so this can only happen
832 // if there are instructions which haven't been hoisted.
833 if (L == IVIncInsertLoop) {
834 for (User::op_iterator OI = IncV->op_begin()+1,
835 OE = IncV->op_end(); OI != OE; ++OI)
836 if (Instruction *OInst = dyn_cast<Instruction>(OI))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000837 if (!SE.DT.dominates(OInst, IVIncInsertPos))
Andrew Trick7fb669a2011-10-07 23:46:21 +0000838 return false;
839 }
840 // Advance to the next instruction.
841 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
842 if (!IncV)
843 return false;
844
845 if (IncV->mayHaveSideEffects())
846 return false;
847
848 if (IncV != PN)
849 return true;
850
851 return isNormalAddRecExprPHI(PN, IncV, L);
852}
853
Andrew Trickc908b432012-01-20 07:41:13 +0000854/// getIVIncOperand returns an induction variable increment's induction
855/// variable operand.
856///
857/// If allowScale is set, any type of GEP is allowed as long as the nonIV
858/// operands dominate InsertPos.
859///
860/// If allowScale is not set, ensure that a GEP increment conforms to one of the
861/// simple patterns generated by getAddRecExprPHILiterally and
862/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
863Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
864 Instruction *InsertPos,
865 bool allowScale) {
866 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000867 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000868
869 switch (IncV->getOpcode()) {
870 default:
Craig Topper9f008862014-04-15 04:59:12 +0000871 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000872 // Check for a simple Add/Sub or GEP of a loop invariant step.
873 case Instruction::Add:
874 case Instruction::Sub: {
875 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000876 if (!OInst || SE.DT.dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000877 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000878 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000879 }
880 case Instruction::BitCast:
881 return dyn_cast<Instruction>(IncV->getOperand(0));
882 case Instruction::GetElementPtr:
883 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
884 I != E; ++I) {
885 if (isa<Constant>(*I))
886 continue;
887 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000888 if (!SE.DT.dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000889 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000890 }
891 if (allowScale) {
892 // allow any kind of GEP as long as it can be hoisted.
893 continue;
894 }
895 // This must be a pointer addition of constants (pretty), which is already
896 // handled, or some number of address-size elements (ugly). Ugly geps
897 // have 2 operands. i1* is used by the expander to represent an
898 // address-size element.
899 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000900 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000901 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
902 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
903 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000904 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000905 break;
906 }
907 return dyn_cast<Instruction>(IncV->getOperand(0));
908 }
909}
910
911/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
912/// it available to other uses in this loop. Recursively hoist any operands,
913/// until we reach a value that dominates InsertPos.
914bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000915 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000916 return true;
917
918 // InsertPos must itself dominate IncV so that IncV's new position satisfies
919 // its existing users.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000920 if (isa<PHINode>(InsertPos) ||
921 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000922 return false;
923
924 // Check that the chain of IV operands leading back to Phi can be hoisted.
925 SmallVector<Instruction*, 4> IVIncs;
926 for(;;) {
927 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
928 if (!Oper)
929 return false;
930 // IncV is safe to hoist.
931 IVIncs.push_back(IncV);
932 IncV = Oper;
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000933 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000934 break;
935 }
936 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
937 E = IVIncs.rend(); I != E; ++I) {
938 (*I)->moveBefore(InsertPos);
939 }
940 return true;
941}
942
Andrew Trick7fb669a2011-10-07 23:46:21 +0000943/// Determine if this cyclic phi is in a form that would have been generated by
944/// LSR. We don't care if the phi was actually expanded in this pass, as long
945/// as it is in a low-cost form, for example, no implied multiplication. This
946/// should match any patterns generated by getAddRecExprPHILiterally and
947/// expandAddtoGEP.
948bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000949 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000950 for(Instruction *IVOper = IncV;
951 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
952 /*allowScale=*/false));) {
953 if (IVOper == PN)
954 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000955 }
Andrew Trickc908b432012-01-20 07:41:13 +0000956 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000957}
958
Andrew Trickceafa2c2011-11-30 06:07:54 +0000959/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
960/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
961/// need to materialize IV increments elsewhere to handle difficult situations.
962Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
963 Type *ExpandTy, Type *IntTy,
964 bool useSubtract) {
965 Value *IncV;
966 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
967 if (ExpandTy->isPointerTy()) {
968 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
969 // If the step isn't constant, don't use an implicitly scaled GEP, because
970 // that would require a multiply inside the loop.
971 if (!isa<ConstantInt>(StepV))
972 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
973 GEPPtrTy->getAddressSpace());
974 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
975 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
976 if (IncV->getType() != PN->getType()) {
977 IncV = Builder.CreateBitCast(IncV, PN->getType());
978 rememberInstruction(IncV);
979 }
980 } else {
981 IncV = useSubtract ?
982 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
983 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
984 rememberInstruction(IncV);
985 }
986 return IncV;
987}
988
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +0000989/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
990/// position. This routine assumes that this is possible (has been checked).
991static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
992 Instruction *Pos, PHINode *LoopPhi) {
993 do {
994 if (DT->dominates(InstToHoist, Pos))
995 break;
996 // Make sure the increment is where we want it. But don't move it
997 // down past a potential existing post-inc user.
998 InstToHoist->moveBefore(Pos);
999 Pos = InstToHoist;
1000 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1001 } while (InstToHoist != LoopPhi);
1002}
1003
1004/// \brief Check whether we can cheaply express the requested SCEV in terms of
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001005/// the available PHI SCEV by truncation and/or inversion of the step.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001006static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1007 const SCEVAddRecExpr *Phi,
1008 const SCEVAddRecExpr *Requested,
1009 bool &InvertStep) {
1010 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1011 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1012
1013 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1014 return false;
1015
1016 // Try truncate it if necessary.
1017 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1018 if (!Phi)
1019 return false;
1020
1021 // Check whether truncation will help.
1022 if (Phi == Requested) {
1023 InvertStep = false;
1024 return true;
1025 }
1026
1027 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1028 if (SE.getAddExpr(Requested->getStart(),
1029 SE.getNegativeSCEV(Requested)) == Phi) {
1030 InvertStep = true;
1031 return true;
1032 }
1033
1034 return false;
1035}
1036
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001037static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1038 if (!isa<IntegerType>(AR->getType()))
1039 return false;
1040
1041 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1042 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1043 const SCEV *Step = AR->getStepRecurrence(SE);
1044 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1045 SE.getSignExtendExpr(AR, WideTy));
1046 const SCEV *ExtendAfterOp =
1047 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1048 return ExtendAfterOp == OpAfterExtend;
1049}
1050
1051static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1052 if (!isa<IntegerType>(AR->getType()))
1053 return false;
1054
1055 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1056 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1057 const SCEV *Step = AR->getStepRecurrence(SE);
1058 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1059 SE.getZeroExtendExpr(AR, WideTy));
1060 const SCEV *ExtendAfterOp =
1061 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1062 return ExtendAfterOp == OpAfterExtend;
1063}
1064
Dan Gohman51ad99d2010-01-21 02:09:26 +00001065/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1066/// the base addrec, which is the addrec without any non-loop-dominating
1067/// values, and return the PHI.
1068PHINode *
1069SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1070 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001072 Type *IntTy,
1073 Type *&TruncTy,
1074 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001075 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001076
Dan Gohman51ad99d2010-01-21 02:09:26 +00001077 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001078 BasicBlock *LatchBlock = L->getLoopLatch();
1079 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001080 PHINode *AddRecPhiMatch = nullptr;
1081 Instruction *IncV = nullptr;
1082 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001083 InvertStep = false;
1084
1085 // Only try partially matching scevs that need truncation and/or
1086 // step-inversion if we know this loop is outside the current loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001087 bool TryNonMatchingSCEV =
1088 IVIncInsertLoop &&
1089 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001090
Andrew Trick7fb669a2011-10-07 23:46:21 +00001091 for (BasicBlock::iterator I = L->getHeader()->begin();
1092 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001093 if (!SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001094 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001095
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001096 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1097 if (!PhiSCEV)
1098 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001099
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001100 bool IsMatchingSCEV = PhiSCEV == Normalized;
1101 // We only handle truncation and inversion of phi recurrences for the
1102 // expanded expression if the expanded expression's loop dominates the
1103 // loop we insert to. Check now, so we can bail out early.
1104 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1105 continue;
1106
1107 Instruction *TempIncV =
1108 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1109
1110 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001111 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001112 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001113 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001114 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1115 continue;
1116 } else {
1117 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001118 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001119 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001120
1121 // Stop if we have found an exact match SCEV.
1122 if (IsMatchingSCEV) {
1123 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001124 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001125 InvertStep = false;
1126 AddRecPhiMatch = PN;
1127 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001128 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001129
1130 // Try whether the phi can be translated into the requested form
1131 // (truncated and/or offset by a constant).
1132 if ((!TruncTy || InvertStep) &&
1133 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1134 // Record the phi node. But don't stop we might find an exact match
1135 // later.
1136 AddRecPhiMatch = PN;
1137 IncV = TempIncV;
1138 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1139 }
1140 }
1141
1142 if (AddRecPhiMatch) {
1143 // Potentially, move the increment. We have made sure in
1144 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1145 if (L == IVIncInsertLoop)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001146 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001147
Andrew Trick7fb669a2011-10-07 23:46:21 +00001148 // Ok, the add recurrence looks usable.
1149 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001150 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001151 // Remember the increment.
1152 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001153 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001154 }
1155 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001156
1157 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001158 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001159
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001160 // Another AddRec may need to be recursively expanded below. For example, if
1161 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1162 // loop. Remove this loop from the PostIncLoops set before expanding such
1163 // AddRecs. Otherwise, we cannot find a valid position for the step
1164 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1165 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1166 // so it's not worth implementing SmallPtrSet::swap.
1167 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1168 PostIncLoops.clear();
1169
Dan Gohman51ad99d2010-01-21 02:09:26 +00001170 // Expand code for the start value.
1171 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1172 L->getHeader()->begin());
1173
Andrew Trick244e2c32011-07-16 00:59:39 +00001174 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001175 assert(!isa<Instruction>(StartV) ||
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001176 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1177 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001178
Andrew Trickceafa2c2011-11-30 06:07:54 +00001179 // Expand code for the step value. Do this before creating the PHI so that PHI
1180 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001181 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001182 // If the stride is negative, insert a sub instead of an add for the increment
1183 // (unless it's a constant, because subtracts of constants are canonicalized
1184 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001185 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001186 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001187 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001188 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001189 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1190
Sanjoy Das54ef8952015-02-26 19:51:35 +00001191 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1192 // we actually do emit an addition. It does not apply if we emit a
1193 // subtraction.
1194 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1195 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1196
Dan Gohman51ad99d2010-01-21 02:09:26 +00001197 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001198 BasicBlock *Header = L->getHeader();
1199 Builder.SetInsertPoint(Header, Header->begin());
1200 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001201 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001202 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001203 rememberInstruction(PN);
1204
1205 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001206 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001207 BasicBlock *Pred = *HPI;
1208
1209 // Add a start value.
1210 if (!L->contains(Pred)) {
1211 PN->addIncoming(StartV, Pred);
1212 continue;
1213 }
1214
Andrew Trickceafa2c2011-11-30 06:07:54 +00001215 // Create a step value and add it to the PHI.
1216 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1217 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001218 Instruction *InsertPos = L == IVIncInsertLoop ?
1219 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001220 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001221 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001222
Andrew Trick8eaae282013-07-14 02:50:07 +00001223 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001224 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001225 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001226 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001227 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1228 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001229 PN->addIncoming(IncV, Pred);
1230 }
1231
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001232 // After expanding subexpressions, restore the PostIncLoops set so the caller
1233 // can ensure that IVIncrement dominates the current uses.
1234 PostIncLoops = SavedPostIncLoops;
1235
Dan Gohman51ad99d2010-01-21 02:09:26 +00001236 // Remember this PHI, even in post-inc mode.
1237 InsertedValues.insert(PN);
1238
1239 return PN;
1240}
1241
1242Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001243 Type *STy = S->getType();
1244 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001245 const Loop *L = S->getLoop();
1246
1247 // Determine a normalized form of this expression, which is the expression
1248 // before any post-inc adjustment is made.
1249 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001250 if (PostIncLoops.count(L)) {
1251 PostIncLoopSet Loops;
1252 Loops.insert(L);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001253 Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1254 Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001255 }
1256
1257 // Strip off any non-loop-dominating component from the addrec start.
1258 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001259 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001260 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001261 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001262 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001263 Normalized = cast<SCEVAddRecExpr>(
1264 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1265 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001266 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001267 }
1268
1269 // Strip off any non-loop-dominating component from the addrec step.
1270 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001271 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001272 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001273 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001274 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001275 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001276 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1277 Start, Step, Normalized->getLoop(),
1278 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001279 }
1280
1281 // Expand the core addrec. If we need post-loop scaling, force it to
1282 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001283 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001284 // In some cases, we decide to reuse an existing phi node but need to truncate
1285 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001286 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001287 bool InvertStep = false;
1288 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1289 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001290
Dan Gohman8b0a4192010-03-01 17:49:51 +00001291 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001292 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001293 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001294 Result = PN;
1295 else {
1296 // In PostInc mode, use the post-incremented value.
1297 BasicBlock *LatchBlock = L->getLoopLatch();
1298 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1299 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001300
1301 // For an expansion to use the postinc form, the client must call
1302 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1303 // or dominated by IVIncInsertPos.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001304 if (isa<Instruction>(Result) &&
1305 !SE.DT.dominates(cast<Instruction>(Result), Builder.GetInsertPoint())) {
Andrew Trickceafa2c2011-11-30 06:07:54 +00001306 // The induction variable's postinc expansion does not dominate this use.
1307 // IVUsers tries to prevent this case, so it is rare. However, it can
1308 // happen when an IVUser outside the loop is not dominated by the latch
1309 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1310 // all cases. Consider a phi outide whose operand is replaced during
1311 // expansion with the value of the postinc user. Without fundamentally
1312 // changing the way postinc users are tracked, the only remedy is
1313 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1314 // but hopefully expandCodeFor handles that.
1315 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001316 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001317 if (useSubtract)
1318 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001319 Value *StepV;
1320 {
1321 // Expand the step somewhere that dominates the loop header.
1322 BuilderType::InsertPointGuard Guard(Builder);
1323 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1324 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001325 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1326 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001327 }
1328
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001329 // We have decided to reuse an induction variable of a dominating loop. Apply
1330 // truncation and/or invertion of the step.
1331 if (TruncTy) {
1332 Type *ResTy = Result->getType();
1333 // Normalize the result type.
1334 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1335 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1336 // Truncate the result.
1337 if (TruncTy != Result->getType()) {
1338 Result = Builder.CreateTrunc(Result, TruncTy);
1339 rememberInstruction(Result);
1340 }
1341 // Invert the result.
1342 if (InvertStep) {
1343 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1344 Result);
1345 rememberInstruction(Result);
1346 }
1347 }
1348
Dan Gohman51ad99d2010-01-21 02:09:26 +00001349 // Re-apply any non-loop-dominating scale.
1350 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001351 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001352 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001353 Result = Builder.CreateMul(Result,
1354 expandCodeFor(PostLoopScale, IntTy));
1355 rememberInstruction(Result);
1356 }
1357
1358 // Re-apply any non-loop-dominating offset.
1359 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001360 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001361 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1362 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1363 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001364 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001365 Result = Builder.CreateAdd(Result,
1366 expandCodeFor(PostLoopOffset, IntTy));
1367 rememberInstruction(Result);
1368 }
1369 }
1370
1371 return Result;
1372}
1373
Dan Gohman056857a2009-04-18 17:56:28 +00001374Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001375 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1376
Chris Lattner229907c2011-07-18 04:54:35 +00001377 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001378 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001379
Dan Gohman426901a2009-06-13 16:25:49 +00001380 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001381 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001382 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001383 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001384 CanonicalIV = PN;
1385
1386 // Rewrite an AddRec in terms of the canonical induction variable, if
1387 // its type is more narrow.
1388 if (CanonicalIV &&
1389 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1390 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001391 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1392 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1393 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001394 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001395 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001396 BasicBlock::iterator NewInsertPt =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001397 std::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001398 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001399 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1400 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001401 ++NewInsertPt;
Craig Topper9f008862014-04-15 04:59:12 +00001402 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Dan Gohman426901a2009-06-13 16:25:49 +00001403 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001404 return V;
1405 }
1406
Nate Begeman2bca4d92005-07-30 00:12:19 +00001407 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001408 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001409 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001410 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001411 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1412 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001413
1414 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1415 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001416 const SCEV *Base = S->getStart();
1417 const SCEV *RestArray[1] = { Rest };
1418 // Dig into the expression to find the pointer base for a GEP.
1419 ExposePointerBase(Base, RestArray[0], SE);
1420 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001421 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001422 // Make sure the Base isn't something exotic, such as a multiplied
1423 // or divided pointer value. In those cases, the result type isn't
1424 // actually a pointer type.
1425 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1426 Value *StartV = expand(Base);
1427 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1428 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001429 }
1430 }
1431
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001432 // Just do a normal add. Pre-expand the operands to suppress folding.
1433 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1434 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001435 }
1436
Dan Gohmancd838702010-07-26 18:28:14 +00001437 // If we don't yet have a canonical IV, create one.
1438 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001439 // Create and insert the PHI node for the induction variable in the
1440 // specified loop.
1441 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001442 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001443 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1444 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001445 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001446
Hal Finkel3f5279c2013-08-18 00:16:23 +00001447 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001448 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001449 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001450 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001451 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001452 // There must be an incoming value for each predecessor, even the
1453 // duplicates!
1454 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001455 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001456 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001457
Gabor Greife82532a2010-07-09 15:40:10 +00001458 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001459 // Insert a unit add instruction right before the terminator
1460 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001461 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1462 "indvar.next",
1463 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001464 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001465 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001466 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001467 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001468 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001469 }
Gabor Greife82532a2010-07-09 15:40:10 +00001470 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001471 }
1472
Dan Gohmancd838702010-07-26 18:28:14 +00001473 // {0,+,1} --> Insert a canonical induction variable into the loop!
1474 if (S->isAffine() && S->getOperand(1)->isOne()) {
1475 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1476 "IVs with types different from the canonical IV should "
1477 "already have been handled!");
1478 return CanonicalIV;
1479 }
1480
Dan Gohman426901a2009-06-13 16:25:49 +00001481 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001482
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001483 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001484 if (S->isAffine()) // {0,+,F} --> i*F
1485 return
1486 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001487 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001488 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001489 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001490 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001491
1492 // If this is a chain of recurrences, turn it into a closed form, using the
1493 // folders, then expandCodeFor the closed form. This allows the folders to
1494 // simplify the expression without having to build a bunch of special code
1495 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001496 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001497
Dan Gohman426901a2009-06-13 16:25:49 +00001498 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001499 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001500 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001501 if (isa<SCEVAddRecExpr>(Ext))
1502 NewS = Ext;
1503
Dan Gohmanaf752342009-07-07 17:06:11 +00001504 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001505 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001506
Dan Gohman426901a2009-06-13 16:25:49 +00001507 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001508 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001509 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001510}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001511
Dan Gohman056857a2009-04-18 17:56:28 +00001512Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001513 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001514 Value *V = expandCodeFor(S->getOperand(),
1515 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001516 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001517 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001518 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001519}
1520
Dan Gohman056857a2009-04-18 17:56:28 +00001521Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001522 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001523 Value *V = expandCodeFor(S->getOperand(),
1524 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001525 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001526 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001527 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001528}
1529
Dan Gohman056857a2009-04-18 17:56:28 +00001530Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001531 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001532 Value *V = expandCodeFor(S->getOperand(),
1533 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001534 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001535 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001536 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001537}
1538
Dan Gohman056857a2009-04-18 17:56:28 +00001539Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001540 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001541 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001542 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1543 // In the case of mixed integer and pointer types, do the
1544 // rest of the comparisons as integer.
1545 if (S->getOperand(i)->getType() != Ty) {
1546 Ty = SE.getEffectiveSCEVType(Ty);
1547 LHS = InsertNoopCastOfTo(LHS, Ty);
1548 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001549 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001550 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001551 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001552 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001553 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001554 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001555 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001556 // In the case of mixed integer and pointer types, cast the
1557 // final result back to the pointer type.
1558 if (LHS->getType() != S->getType())
1559 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001560 return LHS;
1561}
1562
Dan Gohman056857a2009-04-18 17:56:28 +00001563Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001564 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001565 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001566 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1567 // In the case of mixed integer and pointer types, do the
1568 // rest of the comparisons as integer.
1569 if (S->getOperand(i)->getType() != Ty) {
1570 Ty = SE.getEffectiveSCEVType(Ty);
1571 LHS = InsertNoopCastOfTo(LHS, Ty);
1572 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001573 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001574 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001575 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001576 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001577 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001578 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001579 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001580 // In the case of mixed integer and pointer types, cast the
1581 // final result back to the pointer type.
1582 if (LHS->getType() != S->getType())
1583 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001584 return LHS;
1585}
1586
Chris Lattner229907c2011-07-18 04:54:35 +00001587Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001588 Instruction *IP) {
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001589 Builder.SetInsertPoint(IP->getParent(), IP);
1590 return expandCodeFor(SH, Ty);
1591}
1592
Chris Lattner229907c2011-07-18 04:54:35 +00001593Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001594 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001595 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001596 if (Ty) {
1597 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1598 "non-trivial casts should be done with the SCEVs directly!");
1599 V = InsertNoopCastOfTo(V, Ty);
1600 }
1601 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001602}
1603
Dan Gohman056857a2009-04-18 17:56:28 +00001604Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001605 // Compute an insertion point for this SCEV object. Hoist the instructions
1606 // as far out in the loop nest as possible.
Dan Gohman830fd382009-06-27 21:18:18 +00001607 Instruction *InsertPt = Builder.GetInsertPoint();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001608 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001609 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001610 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001611 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001612 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001613 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001614 else {
1615 // LSR sets the insertion point for AddRec start/step values to the
1616 // block start to simplify value reuse, even though it's an invalid
1617 // position. SCEVExpander must correct for this in all cases.
1618 InsertPt = L->getHeader()->getFirstInsertionPt();
1619 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001620 } else {
1621 // If the SCEV is computable at this level, insert it into the header
1622 // after the PHIs (and after any other instructions that we've inserted
1623 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001624 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1625 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickc908b432012-01-20 07:41:13 +00001626 while (InsertPt != Builder.GetInsertPoint()
1627 && (isInsertedInstruction(InsertPt)
1628 || isa<DbgInfoIntrinsic>(InsertPt))) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001629 InsertPt = std::next(BasicBlock::iterator(InsertPt));
Andrew Trickc908b432012-01-20 07:41:13 +00001630 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001631 break;
1632 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001633
Dan Gohmandaafbe62009-06-26 22:53:46 +00001634 // Check to see if we already expanded this here.
Andrew Trickd4e1b5e2013-01-14 21:00:37 +00001635 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1636 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001637 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001638 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001639
Benjamin Kramer6e931522013-09-30 15:40:17 +00001640 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman830fd382009-06-27 21:18:18 +00001641 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001642
1643 // Expand the expression into instructions.
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001644 Value *V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001645
Dan Gohmandaafbe62009-06-26 22:53:46 +00001646 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001647 //
1648 // This is independent of PostIncLoops. The mapped value simply materializes
1649 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001650 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001651 // its insertion point was already at the head of the loop.
1652 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001653 return V;
1654}
Dan Gohman63964b52009-06-05 16:35:53 +00001655
Dan Gohman6b751732010-02-14 03:12:47 +00001656void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001657 if (!PostIncLoops.empty())
1658 InsertedPostIncValues.insert(I);
1659 else
Dan Gohman6b751732010-02-14 03:12:47 +00001660 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001661}
1662
Dan Gohman63964b52009-06-05 16:35:53 +00001663/// getOrInsertCanonicalInductionVariable - This method returns the
1664/// canonical induction variable of the specified type for the specified
1665/// loop (inserting one if there is none). A canonical induction variable
1666/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001667PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001668SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001669 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001670 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001671
1672 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001673 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001674 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001675 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001676
1677 // Emit code for it.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001678 BuilderType::InsertPointGuard Guard(Builder);
Craig Topper9f008862014-04-15 04:59:12 +00001679 PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
1680 L->getHeader()->begin()));
Dan Gohman31158752010-07-20 16:46:58 +00001681
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001682 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001683}
Andrew Trickf9201c52011-10-11 02:28:51 +00001684
Andrew Trickf9201c52011-10-11 02:28:51 +00001685/// replaceCongruentIVs - Check for congruent phis in this loop header and
1686/// replace them with their most canonical representative. Return the number of
1687/// phis eliminated.
1688///
1689/// This does not depend on any SCEVExpander state but should be used in
1690/// the same context that SCEVExpander is used.
1691unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001692 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001693 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001694 // Find integer phis in order of increasing width.
1695 SmallVector<PHINode*, 8> Phis;
1696 for (BasicBlock::iterator I = L->getHeader()->begin();
1697 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1698 Phis.push_back(Phi);
1699 }
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001700 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001701 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1702 // Put pointers at the back and make sure pointer < pointer = false.
1703 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1704 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1705 return RHS->getType()->getPrimitiveSizeInBits() <
1706 LHS->getType()->getPrimitiveSizeInBits();
1707 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001708
Andrew Trickf9201c52011-10-11 02:28:51 +00001709 unsigned NumElim = 0;
1710 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Eric Christopher572e03a2015-06-19 01:53:21 +00001711 // Process phis from wide to narrow. Map wide phis to their truncation
Andrew Trick5adedf52012-01-07 01:12:09 +00001712 // so narrow phis can reuse them.
1713 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1714 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1715 PHINode *Phi = *PIter;
1716
Benjamin Kramera225ed82012-10-19 16:37:30 +00001717 // Fold constant phis. They may be congruent to other constant phis and
1718 // would confuse the logic below that expects proper IVs.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001719 if (Value *V = SimplifyInstruction(Phi, DL, &SE.TLI, &SE.DT, &SE.AC)) {
Benjamin Kramera225ed82012-10-19 16:37:30 +00001720 Phi->replaceAllUsesWith(V);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001721 DeadInsts.emplace_back(Phi);
Benjamin Kramera225ed82012-10-19 16:37:30 +00001722 ++NumElim;
1723 DEBUG_WITH_TYPE(DebugType, dbgs()
1724 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1725 continue;
1726 }
1727
Andrew Trickf9201c52011-10-11 02:28:51 +00001728 if (!SE.isSCEVable(Phi->getType()))
1729 continue;
1730
1731 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1732 if (!OrigPhiRef) {
1733 OrigPhiRef = Phi;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001734 if (Phi->getType()->isIntegerTy() && TTI
1735 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001736 // This phi can be freely truncated to the narrowest phi type. Map the
1737 // truncated expression to it so it will be reused for narrow types.
1738 const SCEV *TruncExpr =
1739 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1740 ExprToIVMap[TruncExpr] = Phi;
1741 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001742 continue;
1743 }
1744
Andrew Trick5adedf52012-01-07 01:12:09 +00001745 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1746 // sense.
1747 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001748 continue;
1749
1750 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1751 Instruction *OrigInc =
1752 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1753 Instruction *IsomorphicInc =
1754 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1755
Andrew Trick5adedf52012-01-07 01:12:09 +00001756 // If this phi has the same width but is more canonical, replace the
Andrew Trickc908b432012-01-20 07:41:13 +00001757 // original with it. As part of the "more canonical" determination,
1758 // respect a prior decision to use an IV chain.
Andrew Trick5adedf52012-01-07 01:12:09 +00001759 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickc908b432012-01-20 07:41:13 +00001760 && !(ChainedPhis.count(Phi)
1761 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1762 && (ChainedPhis.count(Phi)
1763 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001764 std::swap(OrigPhiRef, Phi);
1765 std::swap(OrigInc, IsomorphicInc);
1766 }
1767 // Replacing the congruent phi is sufficient because acyclic redundancy
1768 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1769 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trickf730f392012-01-07 01:29:21 +00001770 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1771 // common case of a single IV increment so that DeleteDeadPHIs can remove
1772 // cycles that had postinc uses.
Andrew Trick5adedf52012-01-07 01:12:09 +00001773 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1774 IsomorphicInc->getType());
1775 if (OrigInc != IsomorphicInc
Andrew Trickd5d2db92012-01-10 01:45:08 +00001776 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickc908b432012-01-20 07:41:13 +00001777 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1778 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001779 DEBUG_WITH_TYPE(DebugType, dbgs()
1780 << "INDVARS: Eliminated congruent iv.inc: "
1781 << *IsomorphicInc << '\n');
Andrew Trick5adedf52012-01-07 01:12:09 +00001782 Value *NewInc = OrigInc;
1783 if (OrigInc->getType() != IsomorphicInc->getType()) {
Sanjoy Dasf1e9e1d2015-03-13 18:31:19 +00001784 Instruction *IP = nullptr;
1785 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1786 IP = PN->getParent()->getFirstInsertionPt();
1787 else
1788 IP = OrigInc->getNextNode();
1789
Andrew Trick23ef0d62012-01-14 03:17:23 +00001790 IRBuilder<> Builder(IP);
Andrew Trick5adedf52012-01-07 01:12:09 +00001791 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1792 NewInc = Builder.
1793 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1794 }
1795 IsomorphicInc->replaceAllUsesWith(NewInc);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001796 DeadInsts.emplace_back(IsomorphicInc);
Andrew Trickf9201c52011-10-11 02:28:51 +00001797 }
1798 }
1799 DEBUG_WITH_TYPE(DebugType, dbgs()
1800 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1801 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001802 Value *NewIV = OrigPhiRef;
1803 if (OrigPhiRef->getType() != Phi->getType()) {
1804 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1805 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1806 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1807 }
1808 Phi->replaceAllUsesWith(NewIV);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001809 DeadInsts.emplace_back(Phi);
Andrew Trickf9201c52011-10-11 02:28:51 +00001810 }
1811 return NumElim;
1812}
Andrew Trick653513b2012-07-13 23:33:10 +00001813
Igor Laevsky4709c032015-08-10 18:23:58 +00001814Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1815 const Instruction *At, Loop *L) {
1816 using namespace llvm::PatternMatch;
1817
1818 SmallVector<BasicBlock *, 4> Latches;
1819 L->getLoopLatches(Latches);
1820
1821 // Look for suitable value in simple conditions at the loop latches.
1822 for (BasicBlock *BB : Latches) {
1823 ICmpInst::Predicate Pred;
1824 Instruction *LHS, *RHS;
1825 BasicBlock *TrueBB, *FalseBB;
1826
1827 if (!match(BB->getTerminator(),
1828 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1829 TrueBB, FalseBB)))
1830 continue;
1831
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001832 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
Igor Laevsky4709c032015-08-10 18:23:58 +00001833 return LHS;
1834
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001835 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
Igor Laevsky4709c032015-08-10 18:23:58 +00001836 return RHS;
1837 }
1838
1839 // There is potential to make this significantly smarter, but this simple
1840 // heuristic already gets some interesting cases.
1841
1842 // Can not find suitable value.
1843 return nullptr;
1844}
1845
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001846bool SCEVExpander::isHighCostExpansionHelper(
Igor Laevsky4709c032015-08-10 18:23:58 +00001847 const SCEV *S, Loop *L, const Instruction *At,
1848 SmallPtrSetImpl<const SCEV *> &Processed) {
1849
1850 // If we can find an existing value for this scev avaliable at the point "At"
1851 // then consider the expression cheap.
1852 if (At && findExistingExpansion(S, At, L) != nullptr)
1853 return false;
Wei Mie2538b52015-05-28 21:49:07 +00001854
1855 // Zero/One operand expressions
1856 switch (S->getSCEVType()) {
1857 case scUnknown:
1858 case scConstant:
1859 return false;
1860 case scTruncate:
Igor Laevsky4709c032015-08-10 18:23:58 +00001861 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1862 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001863 case scZeroExtend:
1864 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001865 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001866 case scSignExtend:
1867 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001868 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001869 }
1870
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001871 if (!Processed.insert(S).second)
1872 return false;
1873
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001874 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1875 // If the divisor is a power of two and the SCEV type fits in a native
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001876 // integer, consider the division cheap irrespective of whether it occurs in
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001877 // the user code since it can be lowered into a right shift.
1878 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1879 if (SC->getValue()->getValue().isPowerOf2()) {
1880 const DataLayout &DL =
1881 L->getHeader()->getParent()->getParent()->getDataLayout();
1882 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1883 return DL.isIllegalInteger(Width);
1884 }
1885
1886 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1887 // HowManyLessThans produced to compute a precise expression, rather than a
1888 // UDiv from the user's code. If we can't find a UDiv in the code with some
1889 // simple searching, assume the former consider UDivExpr expensive to
1890 // compute.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001891 BasicBlock *ExitingBB = L->getExitingBlock();
1892 if (!ExitingBB)
1893 return true;
1894
1895 BranchInst *ExitingBI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1896 if (!ExitingBI || !ExitingBI->isConditional())
1897 return true;
1898
1899 ICmpInst *OrigCond = dyn_cast<ICmpInst>(ExitingBI->getCondition());
1900 if (!OrigCond)
1901 return true;
1902
1903 const SCEV *RHS = SE.getSCEV(OrigCond->getOperand(1));
1904 RHS = SE.getMinusSCEV(RHS, SE.getConstant(RHS->getType(), 1));
1905 if (RHS != S) {
1906 const SCEV *LHS = SE.getSCEV(OrigCond->getOperand(0));
1907 LHS = SE.getMinusSCEV(LHS, SE.getConstant(LHS->getType(), 1));
1908 if (LHS != S)
1909 return true;
1910 }
1911 }
1912
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001913 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1914 // the exit condition.
1915 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1916 return true;
1917
Wei Mie2538b52015-05-28 21:49:07 +00001918 // Recurse past nary expressions, which commonly occur in the
1919 // BackedgeTakenCount. They may already exist in program code, and if not,
1920 // they are not too expensive rematerialize.
1921 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1922 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
1923 I != E; ++I) {
Igor Laevsky4709c032015-08-10 18:23:58 +00001924 if (isHighCostExpansionHelper(*I, L, At, Processed))
Wei Mie2538b52015-05-28 21:49:07 +00001925 return true;
1926 }
1927 }
1928
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001929 // If we haven't recognized an expensive SCEV pattern, assume it's an
1930 // expression produced by program code.
1931 return false;
1932}
1933
Andrew Trick653513b2012-07-13 23:33:10 +00001934namespace {
1935// Search for a SCEV subexpression that is not safe to expand. Any expression
1936// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1937// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1938// instruction, but the important thing is that we prove the denominator is
1939// nonzero before expansion.
1940//
1941// IVUsers already checks that IV-derived expressions are safe. So this check is
1942// only needed when the expression includes some subexpression that is not IV
1943// derived.
1944//
1945// Currently, we only allow division by a nonzero constant here. If this is
1946// inadequate, we could easily allow division by SCEVUnknown by using
1947// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00001948//
1949// We cannot generally expand recurrences unless the step dominates the loop
1950// header. The expander handles the special case of affine recurrences by
1951// scaling the recurrence outside the loop, but this technique isn't generally
1952// applicable. Expanding a nested recurrence outside a loop requires computing
1953// binomial coefficients. This could be done, but the recurrence has to be in a
1954// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00001955struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00001956 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00001957 bool IsUnsafe;
1958
Andrew Trick57243da2013-10-25 21:35:56 +00001959 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00001960
1961 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00001962 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1963 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1964 if (!SC || SC->getValue()->isZero()) {
1965 IsUnsafe = true;
1966 return false;
1967 }
1968 }
1969 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1970 const SCEV *Step = AR->getStepRecurrence(SE);
1971 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1972 IsUnsafe = true;
1973 return false;
1974 }
1975 }
1976 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00001977 }
1978 bool isDone() const { return IsUnsafe; }
1979};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001980}
Andrew Trick653513b2012-07-13 23:33:10 +00001981
1982namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00001983bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
1984 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00001985 visitAll(S, Search);
1986 return !Search.IsUnsafe;
1987}
1988}