blob: 77e4ec7ab40c39418e325143b884025e6aabf53c [file] [log] [blame]
Nick Lewyckyaf508372016-04-24 17:55:41 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
Nate Begeman2bca4d92005-07-30 00:12:19 +00002//
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.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000066 Ret = CastInst::Create(Op, V, Ty, "", &*IP);
Rafael Espindola09a42012012-02-27 02:13:03 +000067 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)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +000078 Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
Rafael Espindola09a42012012-02-27 02:13:03 +000079
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).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +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
David Majnemerdd9a8152015-10-27 07:36:42 +000089static BasicBlock::iterator findInsertPointAfter(Instruction *I,
David Majnemerdd9a8152015-10-27 07:36:42 +000090 BasicBlock *MustDominate) {
91 BasicBlock::iterator IP = ++I->getIterator();
92 if (auto *II = dyn_cast<InvokeInst>(I))
93 IP = II->getNormalDest()->begin();
David Majnemerdd9a8152015-10-27 07:36:42 +000094
95 while (isa<PHINode>(IP))
96 ++IP;
97
David Majnemerfa8681e42016-02-03 21:30:31 +000098 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
99 ++IP;
100 } else if (isa<CatchSwitchInst>(IP)) {
101 IP = MustDominate->getFirstInsertionPt();
102 } else {
103 assert(!IP->isEHPad() && "unexpected eh pad!");
David Majnemerdd9a8152015-10-27 07:36:42 +0000104 }
105
106 return IP;
107}
108
Dan Gohman830fd382009-06-27 21:18:18 +0000109/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
110/// which must be possible with a noop cast, doing what we can to share
111/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +0000112Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +0000113 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
114 assert((Op == Instruction::BitCast ||
115 Op == Instruction::PtrToInt ||
116 Op == Instruction::IntToPtr) &&
117 "InsertNoopCastOfTo cannot perform non-noop casts!");
118 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
119 "InsertNoopCastOfTo cannot change sizes!");
120
Dan Gohman0a40ad92009-04-16 03:18:22 +0000121 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +0000122 if (Op == Instruction::BitCast) {
123 if (V->getType() == Ty)
124 return V;
125 if (CastInst *CI = dyn_cast<CastInst>(V)) {
126 if (CI->getOperand(0)->getType() == Ty)
127 return CI->getOperand(0);
128 }
129 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000130 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000131 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000132 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000133 if (CastInst *CI = dyn_cast<CastInst>(V))
134 if ((CI->getOpcode() == Instruction::PtrToInt ||
135 CI->getOpcode() == Instruction::IntToPtr) &&
136 SE.getTypeSizeInBits(CI->getType()) ==
137 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
138 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
140 if ((CE->getOpcode() == Instruction::PtrToInt ||
141 CE->getOpcode() == Instruction::IntToPtr) &&
142 SE.getTypeSizeInBits(CE->getType()) ==
143 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
144 return CE->getOperand(0);
145 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000146
Dan Gohmand2772462010-06-19 13:25:23 +0000147 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000148 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000149 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000150
Dan Gohmand2772462010-06-19 13:25:23 +0000151 // Cast the argument at the beginning of the entry block, after
152 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000153 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000154 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
155 while ((isa<BitCastInst>(IP) &&
156 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
157 cast<BitCastInst>(IP)->getOperand(0) != A) ||
David Majnemerdd9a8152015-10-27 07:36:42 +0000158 isa<DbgInfoIntrinsic>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000159 ++IP;
160 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000161 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000162
Dan Gohmand2772462010-06-19 13:25:23 +0000163 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000164 Instruction *I = cast<Instruction>(V);
David Majnemer235acde2015-10-27 19:48:28 +0000165 BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
Dan Gohmand2772462010-06-19 13:25:23 +0000166 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000167}
168
Chris Lattnere71f1442007-04-13 05:04:18 +0000169/// InsertBinop - Insert the specified binary operator, doing a small amount
170/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000171Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000173 // Fold a binop with constant operands.
174 if (Constant *CLHS = dyn_cast<Constant>(LHS))
175 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000176 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000177
Chris Lattnere71f1442007-04-13 05:04:18 +0000178 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
179 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000180 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
181 // Scanning starts from the last instruction before the insertion point.
182 BasicBlock::iterator IP = Builder.GetInsertPoint();
183 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000184 --IP;
185 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000186 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
187 // generated code.
188 if (isa<DbgInfoIntrinsic>(IP))
189 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000190 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
191 IP->getOperand(1) == RHS)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000192 return &*IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000193 if (IP == BlockBegin) break;
194 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000195 }
Dan Gohman830fd382009-06-27 21:18:18 +0000196
Dan Gohman29707de2010-03-03 05:29:13 +0000197 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000198 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
Geoff Berry0c095172016-06-01 20:03:09 +0000199 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000200
201 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000202 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000203 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
204 BasicBlock *Preheader = L->getLoopPreheader();
205 if (!Preheader) break;
206
207 // Ok, move up a level.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000208 Builder.SetInsertPoint(Preheader->getTerminator());
Dan Gohman29707de2010-03-03 05:29:13 +0000209 }
210
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000211 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000212 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000213 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000214 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000215
Dan Gohmand195a222009-05-01 17:13:31 +0000216 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000217}
218
Dan Gohman17893622009-05-27 02:00:53 +0000219/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000220/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000221/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000222/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000223/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
224/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
225/// check to see if the divide was folded.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000226static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
227 const SCEV *Factor, ScalarEvolution &SE,
228 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000229 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000230 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000231 return true;
232
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000233 // x/x == 1.
234 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000235 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000236 return true;
237 }
238
Dan Gohman291c2e02009-05-24 18:06:31 +0000239 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000240 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000241 // 0/x == 0.
242 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000243 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000244 // Check for divisibility.
245 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
246 ConstantInt *CI =
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000247 ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000248 // If the quotient is zero and the remainder is non-zero, reject
249 // the value at this scale. It will be considered for subsequent
250 // smaller scales.
251 if (!CI->isZero()) {
252 const SCEV *Div = SE.getConstant(CI);
253 S = Div;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000254 Remainder = SE.getAddExpr(
255 Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000256 return true;
257 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000258 }
Dan Gohman17893622009-05-27 02:00:53 +0000259 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000260
261 // In a Mul, check if there is a constant operand which is a multiple
262 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000263 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264 // Size is known, check if there is a constant operand which is a multiple
265 // of the given factor. If so, we can factor it.
266 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
267 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000268 if (!C->getAPInt().srem(FC->getAPInt())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000269 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000270 NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000271 S = SE.getMulExpr(NewMulOps);
272 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000273 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000274 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000275
276 // In an AddRec, check if both start and step are divisible.
277 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000278 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000279 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000280 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000281 return false;
282 if (!StepRem->isZero())
283 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000284 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000285 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000286 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000287 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
288 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000289 return true;
290 }
291
292 return false;
293}
294
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000295/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
296/// is the number of SCEVAddRecExprs present, which are kept at the end of
297/// the list.
298///
299static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000300 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000301 ScalarEvolution &SE) {
302 unsigned NumAddRecs = 0;
303 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
304 ++NumAddRecs;
305 // Group Ops into non-addrecs and addrecs.
306 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
307 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
308 // Let ScalarEvolution sort and simplify the non-addrecs list.
309 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000310 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000311 SE.getAddExpr(NoAddRecs);
312 // If it returned an add, use the operands. Otherwise it simplified
313 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000314 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000315 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000316 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000317 else if (!Sum->isZero())
318 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000319 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000320 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000321}
322
323/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
324/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
325/// This helps expose more opportunities for folding parts of the expressions
326/// into GEP indices.
327///
328static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000329 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000330 ScalarEvolution &SE) {
331 // Find the addrecs.
332 SmallVector<const SCEV *, 8> AddRecs;
333 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
334 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
335 const SCEV *Start = A->getStart();
336 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000337 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000338 AddRecs.push_back(SE.getAddRecExpr(Zero,
339 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000340 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000341 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000342 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
343 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000344 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000345 e += Add->getNumOperands();
346 } else {
347 Ops[i] = Start;
348 }
349 }
350 if (!AddRecs.empty()) {
351 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000352 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000353 // Resort the operand list, moving any constants to the front.
354 SimplifyAddOperands(Ops, Ty, SE);
355 }
356}
357
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000358/// expandAddToGEP - Expand an addition expression with a pointer type into
359/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
360/// BasicAliasAnalysis and other passes analyze the result. See the rules
361/// for getelementptr vs. inttoptr in
362/// http://llvm.org/docs/LangRef.html#pointeraliasing
363/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000364///
Dan Gohman510bffc2010-01-19 22:26:02 +0000365/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000366/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
367/// they may introduce pointer arithmetic which may not be safely converted
368/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000369///
370/// Design note: It might seem desirable for this function to be more
371/// loop-aware. If some of the indices are loop-invariant while others
372/// aren't, it might seem desirable to emit multiple GEPs, keeping the
373/// loop-invariant portions of the overall computation outside the loop.
374/// However, there are a few reasons this is not done here. Hoisting simple
375/// arithmetic is a low-level optimization that often isn't very
376/// important until late in the optimization process. In fact, passes
377/// like InstructionCombining will combine GEPs, even if it means
378/// pushing loop-invariant computation down into loops, so even if the
379/// GEPs were split here, the work would quickly be undone. The
380/// LoopStrengthReduction pass, which is usually run quite late (and
381/// after the last InstructionCombining pass), takes care of hoisting
382/// loop-invariant portions of expressions, after considering what
383/// can be folded using target addressing modes.
384///
Dan Gohmanaf752342009-07-07 17:06:11 +0000385Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
386 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000387 PointerType *PTy,
388 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000389 Value *V) {
David Blaikie156d46e2015-03-24 23:34:31 +0000390 Type *OriginalElTy = PTy->getElementType();
391 Type *ElTy = OriginalElTy;
Dan Gohman26494912009-05-19 02:15:55 +0000392 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000393 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000394 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000395
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000396 // Split AddRecs up into parts as either of the parts may be usable
397 // without the other.
398 SplitAddRecs(Ops, Ty, SE);
399
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000401
Bob Wilson2107eb72009-12-04 01:33:04 +0000402 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000403 // operands into GEP indices, at each level. The first index in a GEP
404 // indexes into the array implied by the pointer operand; the rest of
405 // the indices index into the element or field type selected by the
406 // preceding index.
407 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000408 // If the scale size is not 0, attempt to factor out a scale for
409 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000410 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000411 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000412 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000413 if (!ElSize->isZero()) {
414 SmallVector<const SCEV *, 8> NewOps;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000415 for (const SCEV *Op : Ops) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000416 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000417 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000418 // Op now has ElSize factored out.
419 ScaledOps.push_back(Op);
420 if (!Remainder->isZero())
421 NewOps.push_back(Remainder);
422 AnyNonZeroIndices = true;
423 } else {
424 // The operand was not divisible, so add it to the list of operands
425 // we'll scan next iteration.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000426 NewOps.push_back(Op);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000427 }
Dan Gohman26494912009-05-19 02:15:55 +0000428 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000429 // If we made any changes, update Ops.
430 if (!ScaledOps.empty()) {
431 Ops = NewOps;
432 SimplifyAddOperands(Ops, Ty, SE);
433 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000434 }
Dan Gohman26494912009-05-19 02:15:55 +0000435 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000436
437 // Record the scaled array index for this level of the type. If
438 // we didn't find any operands that could be factored, tentatively
439 // assume that element zero was selected (since the zero offset
440 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000441 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000442 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000443 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
444 GepIndices.push_back(Scaled);
445
446 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000447 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000448 bool FoundFieldNo = false;
449 // An empty struct has no fields.
450 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000451 // Field offsets are known. See if a constant offset falls within any of
452 // the struct fields.
453 if (Ops.empty())
454 break;
455 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
456 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
457 const StructLayout &SL = *DL.getStructLayout(STy);
458 uint64_t FullOffset = C->getValue()->getZExtValue();
459 if (FullOffset < SL.getSizeInBytes()) {
460 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
461 GepIndices.push_back(
462 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
463 ElTy = STy->getTypeAtIndex(ElIdx);
464 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000465 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000466 AnyNonZeroIndices = true;
467 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000468 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000469 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000470 // If no struct field offsets were found, tentatively assume that
471 // field zero was selected (since the zero offset would obviously
472 // be folded away).
473 if (!FoundFieldNo) {
474 ElTy = STy->getTypeAtIndex(0u);
475 GepIndices.push_back(
476 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477 }
Dan Gohman26494912009-05-19 02:15:55 +0000478 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000479
Chris Lattner229907c2011-07-18 04:54:35 +0000480 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000481 ElTy = ATy->getElementType();
482 else
483 break;
Dan Gohman26494912009-05-19 02:15:55 +0000484 }
485
Dan Gohman8b0a4192010-03-01 17:49:51 +0000486 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000487 // the base to i8* and do an ugly getelementptr with that. It's still
488 // better than ptrtoint+arithmetic+inttoptr at least.
489 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000490 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000491 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000492 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000493
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000494 assert(!isa<Instruction>(V) ||
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000495 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000496
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000497 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000498 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000499
500 // Fold a GEP with constant operands.
501 if (Constant *CLHS = dyn_cast<Constant>(V))
502 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie4a2e73b2015-04-02 18:55:32 +0000503 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
504 CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000505
506 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
507 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000508 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
509 // Scanning starts from the last instruction before the insertion point.
510 BasicBlock::iterator IP = Builder.GetInsertPoint();
511 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000512 --IP;
513 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000514 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
515 // generated code.
516 if (isa<DbgInfoIntrinsic>(IP))
517 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000518 if (IP->getOpcode() == Instruction::GetElementPtr &&
519 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000520 return &*IP;
Dan Gohman26494912009-05-19 02:15:55 +0000521 if (IP == BlockBegin) break;
522 }
523 }
524
Dan Gohman29707de2010-03-03 05:29:13 +0000525 // Save the original insertion point so we can restore it when we're done.
Geoff Berry0c095172016-06-01 20:03:09 +0000526 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000527
528 // Move the insertion point out of as many loops as we can.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000529 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000530 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
531 BasicBlock *Preheader = L->getLoopPreheader();
532 if (!Preheader) break;
533
534 // Ok, move up a level.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000535 Builder.SetInsertPoint(Preheader->getTerminator());
Dan Gohman29707de2010-03-03 05:29:13 +0000536 }
537
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000538 // Emit a GEP.
David Blaikie93c54442015-04-03 19:41:44 +0000539 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000540 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000541
Dan Gohman26494912009-05-19 02:15:55 +0000542 return GEP;
543 }
544
Geoff Berry0c095172016-06-01 20:03:09 +0000545 {
546 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman29707de2010-03-03 05:29:13 +0000547
Geoff Berry0c095172016-06-01 20:03:09 +0000548 // Move the insertion point out of as many loops as we can.
549 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
550 if (!L->isLoopInvariant(V)) break;
Dan Gohman29707de2010-03-03 05:29:13 +0000551
Geoff Berry0c095172016-06-01 20:03:09 +0000552 bool AnyIndexNotLoopInvariant =
553 std::any_of(GepIndices.begin(), GepIndices.end(),
554 [L](Value *Op) { return !L->isLoopInvariant(Op); });
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000555
Geoff Berry0c095172016-06-01 20:03:09 +0000556 if (AnyIndexNotLoopInvariant)
557 break;
Dan Gohman29707de2010-03-03 05:29:13 +0000558
Geoff Berry0c095172016-06-01 20:03:09 +0000559 BasicBlock *Preheader = L->getLoopPreheader();
560 if (!Preheader) break;
Dan Gohman29707de2010-03-03 05:29:13 +0000561
Geoff Berry0c095172016-06-01 20:03:09 +0000562 // Ok, move up a level.
563 Builder.SetInsertPoint(Preheader->getTerminator());
564 }
565
566 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
567 // because ScalarEvolution may have changed the address arithmetic to
568 // compute a value which is beyond the end of the allocated object.
569 Value *Casted = V;
570 if (V->getType() != PTy)
571 Casted = InsertNoopCastOfTo(Casted, PTy);
572 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
573 Ops.push_back(SE.getUnknown(GEP));
574 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000575 }
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.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000598 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000599 if (!Pair.second)
600 return Pair.first->second;
601
Dan Gohman29707de2010-03-03 05:29:13 +0000602 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000603 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000604 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000605 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
606 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000607 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
Dan Gohman8ea83d82010-11-18 00:34:22 +0000608 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000609 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000610 }
611 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000612 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000613 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
614 L = AR->getLoop();
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000615 for (const SCEV *Op : N->operands())
616 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000617 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000618 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000619 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
620 const Loop *Result = getRelevantLoop(C->getOperand());
621 return RelevantLoops[C] = Result;
622 }
623 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000624 const Loop *Result = PickMostRelevantLoop(
625 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
Dan Gohman8ea83d82010-11-18 00:34:22 +0000626 return RelevantLoops[D] = Result;
627 }
Dan Gohman29707de2010-03-03 05:29:13 +0000628 llvm_unreachable("Unexpected SCEV type!");
629}
630
Dan Gohmanb29cda92010-04-15 17:08:50 +0000631namespace {
632
Dan Gohman29707de2010-03-03 05:29:13 +0000633/// LoopCompare - Compare loops by PickMostRelevantLoop.
634class LoopCompare {
635 DominatorTree &DT;
636public:
637 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
638
639 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
640 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000641 // Keep pointer operands sorted at the end.
642 if (LHS.second->getType()->isPointerTy() !=
643 RHS.second->getType()->isPointerTy())
644 return LHS.second->getType()->isPointerTy();
645
Dan Gohman29707de2010-03-03 05:29:13 +0000646 // Compare loops with PickMostRelevantLoop.
647 if (LHS.first != RHS.first)
648 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
649
650 // If one operand is a non-constant negative and the other is not,
651 // put the non-constant negative on the right so that a sub can
652 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000653 if (LHS.second->isNonConstantNegative()) {
654 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000655 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000656 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000657 return true;
658
659 // Otherwise they are equivalent according to this comparison.
660 return false;
661 }
662};
663
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000664}
Dan Gohmanb29cda92010-04-15 17:08:50 +0000665
Dan Gohman056857a2009-04-18 17:56:28 +0000666Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000667 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000668
Dan Gohman29707de2010-03-03 05:29:13 +0000669 // Collect all the add operands in a loop, along with their associated loops.
670 // Iterate in reverse so that constants are emitted last, all else equal, and
671 // so that pointer operands are inserted first, which the code below relies on
672 // to form more involved GEPs.
673 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
674 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
675 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000676 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000677
Dan Gohman29707de2010-03-03 05:29:13 +0000678 // Sort by loop. Use a stable sort so that constants follow non-constants and
679 // pointer operands precede non-pointer operands.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000680 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000681
Dan Gohman29707de2010-03-03 05:29:13 +0000682 // Emit instructions to add all the operands. Hoist as much as possible
683 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000684 Value *Sum = nullptr;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000685 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
Dan Gohman29707de2010-03-03 05:29:13 +0000686 const Loop *CurLoop = I->first;
687 const SCEV *Op = I->second;
688 if (!Sum) {
689 // This is the first operand. Just expand it.
690 Sum = expand(Op);
691 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000692 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000693 // The running sum expression is a pointer. Try to form a getelementptr
694 // at this level with that as the base.
695 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000696 for (; I != E && I->first == CurLoop; ++I) {
697 // If the operand is SCEVUnknown and not instructions, peek through
698 // it, to enable more of it to be folded into the GEP.
699 const SCEV *X = I->second;
700 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
701 if (!isa<Instruction>(U->getValue()))
702 X = SE.getSCEV(U->getValue());
703 NewOps.push_back(X);
704 }
Dan Gohman29707de2010-03-03 05:29:13 +0000705 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000706 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000707 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000708 // Try to form a getelementptr. If the running sum is instructions,
709 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000710 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000711 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
712 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000713 for (++I; I != E && I->first == CurLoop; ++I)
714 NewOps.push_back(I->second);
715 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000716 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000717 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000718 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000719 Sum = InsertNoopCastOfTo(Sum, Ty);
720 Sum = InsertBinop(Instruction::Sub, Sum, W);
721 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000722 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000723 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000724 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000725 Sum = InsertNoopCastOfTo(Sum, Ty);
726 // Canonicalize a constant to the RHS.
727 if (isa<Constant>(Sum)) std::swap(Sum, W);
728 Sum = InsertBinop(Instruction::Add, Sum, W);
729 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000730 }
731 }
Dan Gohman29707de2010-03-03 05:29:13 +0000732
733 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000734}
Dan Gohman26494912009-05-19 02:15:55 +0000735
Dan Gohman056857a2009-04-18 17:56:28 +0000736Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000737 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000738
Dan Gohman29707de2010-03-03 05:29:13 +0000739 // Collect all the mul operands in a loop, along with their associated loops.
740 // Iterate in reverse so that constants are emitted last, all else equal.
741 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
742 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
743 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000744 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000745
Dan Gohman29707de2010-03-03 05:29:13 +0000746 // Sort by loop. Use a stable sort so that constants follow non-constants.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000747 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman29707de2010-03-03 05:29:13 +0000748
749 // Emit instructions to mul all the operands. Hoist as much as possible
750 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000751 Value *Prod = nullptr;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000752 for (const auto &I : OpsAndLoops) {
753 const SCEV *Op = I.second;
Dan Gohman29707de2010-03-03 05:29:13 +0000754 if (!Prod) {
755 // This is the first operand. Just expand it.
756 Prod = expand(Op);
Dan Gohman29707de2010-03-03 05:29:13 +0000757 } else if (Op->isAllOnesValue()) {
758 // Instead of doing a multiply by negative one, just do a negate.
759 Prod = InsertNoopCastOfTo(Prod, Ty);
760 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
Dan Gohman29707de2010-03-03 05:29:13 +0000761 } else {
762 // A simple mul.
763 Value *W = expandCodeFor(Op, Ty);
764 Prod = InsertNoopCastOfTo(Prod, Ty);
765 // Canonicalize a constant to the RHS.
766 if (isa<Constant>(Prod)) std::swap(Prod, W);
Jingyue Wu6f72aed2015-06-24 19:28:40 +0000767 const APInt *RHS;
768 if (match(W, m_Power2(RHS))) {
769 // Canonicalize Prod*(1<<C) to Prod<<C.
770 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
771 Prod = InsertBinop(Instruction::Shl, Prod,
772 ConstantInt::get(Ty, RHS->logBase2()));
773 } else {
774 Prod = InsertBinop(Instruction::Mul, Prod, W);
775 }
Dan Gohman29707de2010-03-03 05:29:13 +0000776 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000777 }
778
Dan Gohman29707de2010-03-03 05:29:13 +0000779 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000780}
781
Dan Gohman056857a2009-04-18 17:56:28 +0000782Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000783 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000784
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000785 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000786 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000787 const APInt &RHS = SC->getAPInt();
Nick Lewycky3c947042008-07-08 05:05:37 +0000788 if (RHS.isPowerOf2())
789 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000790 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000791 }
792
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000793 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000794 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000795}
796
Dan Gohman291c2e02009-05-24 18:06:31 +0000797/// Move parts of Base into Rest to leave Base with the minimal
798/// expression that provides a pointer operand suitable for a
799/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000800static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000801 ScalarEvolution &SE) {
802 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
803 Base = A->getStart();
804 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000805 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000806 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000807 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000808 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000809 }
810 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
811 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000812 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000813 NewAddOps.back() = Rest;
814 Rest = SE.getAddExpr(NewAddOps);
815 ExposePointerBase(Base, Rest, SE);
816 }
817}
818
Andrew Trick7fb669a2011-10-07 23:46:21 +0000819/// Determine if this is a well-behaved chain of instructions leading back to
820/// the PHI. If so, it may be reused by expanded expressions.
821bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
822 const Loop *L) {
823 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
824 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
825 return false;
826 // If any of the operands don't dominate the insert position, bail.
827 // Addrec operands are always loop-invariant, so this can only happen
828 // if there are instructions which haven't been hoisted.
829 if (L == IVIncInsertLoop) {
830 for (User::op_iterator OI = IncV->op_begin()+1,
831 OE = IncV->op_end(); OI != OE; ++OI)
832 if (Instruction *OInst = dyn_cast<Instruction>(OI))
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000833 if (!SE.DT.dominates(OInst, IVIncInsertPos))
Andrew Trick7fb669a2011-10-07 23:46:21 +0000834 return false;
835 }
836 // Advance to the next instruction.
837 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
838 if (!IncV)
839 return false;
840
841 if (IncV->mayHaveSideEffects())
842 return false;
843
844 if (IncV != PN)
845 return true;
846
847 return isNormalAddRecExprPHI(PN, IncV, L);
848}
849
Andrew Trickc908b432012-01-20 07:41:13 +0000850/// getIVIncOperand returns an induction variable increment's induction
851/// variable operand.
852///
853/// If allowScale is set, any type of GEP is allowed as long as the nonIV
854/// operands dominate InsertPos.
855///
856/// If allowScale is not set, ensure that a GEP increment conforms to one of the
857/// simple patterns generated by getAddRecExprPHILiterally and
858/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
859Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
860 Instruction *InsertPos,
861 bool allowScale) {
862 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000863 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000864
865 switch (IncV->getOpcode()) {
866 default:
Craig Topper9f008862014-04-15 04:59:12 +0000867 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000868 // Check for a simple Add/Sub or GEP of a loop invariant step.
869 case Instruction::Add:
870 case Instruction::Sub: {
871 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000872 if (!OInst || SE.DT.dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000873 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000874 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000875 }
876 case Instruction::BitCast:
877 return dyn_cast<Instruction>(IncV->getOperand(0));
878 case Instruction::GetElementPtr:
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000879 for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
Andrew Trickc908b432012-01-20 07:41:13 +0000880 if (isa<Constant>(*I))
881 continue;
882 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000883 if (!SE.DT.dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000884 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000885 }
886 if (allowScale) {
887 // allow any kind of GEP as long as it can be hoisted.
888 continue;
889 }
890 // This must be a pointer addition of constants (pretty), which is already
891 // handled, or some number of address-size elements (ugly). Ugly geps
892 // have 2 operands. i1* is used by the expander to represent an
893 // address-size element.
894 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000895 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000896 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
897 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
898 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000899 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000900 break;
901 }
902 return dyn_cast<Instruction>(IncV->getOperand(0));
903 }
904}
905
Geoff Berry0c095172016-06-01 20:03:09 +0000906/// If the insert point of the current builder or any of the builders on the
907/// stack of saved builders has 'I' as its insert point, update it to point to
908/// the instruction after 'I'. This is intended to be used when the instruction
909/// 'I' is being moved. If this fixup is not done and 'I' is moved to a
910/// different block, the inconsistent insert point (with a mismatched
911/// Instruction and Block) can lead to an instruction being inserted in a block
912/// other than its parent.
913void SCEVExpander::fixupInsertPoints(Instruction *I) {
914 BasicBlock::iterator It(*I);
915 BasicBlock::iterator NewInsertPt = std::next(It);
916 if (Builder.GetInsertPoint() == It)
917 Builder.SetInsertPoint(&*NewInsertPt);
918 for (auto *InsertPtGuard : InsertPointGuards)
919 if (InsertPtGuard->GetInsertPoint() == It)
920 InsertPtGuard->SetInsertPoint(NewInsertPt);
921}
922
Andrew Trickc908b432012-01-20 07:41:13 +0000923/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
924/// it available to other uses in this loop. Recursively hoist any operands,
925/// until we reach a value that dominates InsertPos.
926bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000927 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000928 return true;
929
930 // InsertPos must itself dominate IncV so that IncV's new position satisfies
931 // its existing users.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000932 if (isa<PHINode>(InsertPos) ||
933 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000934 return false;
935
Sanjoy Dasb771eb62015-12-08 00:13:17 +0000936 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
937 return false;
938
Andrew Trickc908b432012-01-20 07:41:13 +0000939 // Check that the chain of IV operands leading back to Phi can be hoisted.
940 SmallVector<Instruction*, 4> IVIncs;
941 for(;;) {
942 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
943 if (!Oper)
944 return false;
945 // IncV is safe to hoist.
946 IVIncs.push_back(IncV);
947 IncV = Oper;
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000948 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000949 break;
950 }
Sanjoy Dasb37c4c42015-11-21 23:20:10 +0000951 for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
Geoff Berry0c095172016-06-01 20:03:09 +0000952 fixupInsertPoints(*I);
Andrew Trickc908b432012-01-20 07:41:13 +0000953 (*I)->moveBefore(InsertPos);
954 }
955 return true;
956}
957
Andrew Trick7fb669a2011-10-07 23:46:21 +0000958/// Determine if this cyclic phi is in a form that would have been generated by
959/// LSR. We don't care if the phi was actually expanded in this pass, as long
960/// as it is in a low-cost form, for example, no implied multiplication. This
961/// should match any patterns generated by getAddRecExprPHILiterally and
962/// expandAddtoGEP.
963bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000964 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000965 for(Instruction *IVOper = IncV;
966 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
967 /*allowScale=*/false));) {
968 if (IVOper == PN)
969 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000970 }
Andrew Trickc908b432012-01-20 07:41:13 +0000971 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000972}
973
Andrew Trickceafa2c2011-11-30 06:07:54 +0000974/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
975/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
976/// need to materialize IV increments elsewhere to handle difficult situations.
977Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
978 Type *ExpandTy, Type *IntTy,
979 bool useSubtract) {
980 Value *IncV;
981 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
982 if (ExpandTy->isPointerTy()) {
983 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
984 // If the step isn't constant, don't use an implicitly scaled GEP, because
985 // that would require a multiply inside the loop.
986 if (!isa<ConstantInt>(StepV))
987 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
988 GEPPtrTy->getAddressSpace());
989 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
990 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
991 if (IncV->getType() != PN->getType()) {
992 IncV = Builder.CreateBitCast(IncV, PN->getType());
993 rememberInstruction(IncV);
994 }
995 } else {
996 IncV = useSubtract ?
997 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
998 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
999 rememberInstruction(IncV);
1000 }
1001 return IncV;
1002}
1003
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001004/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
1005/// position. This routine assumes that this is possible (has been checked).
Geoff Berry0c095172016-06-01 20:03:09 +00001006void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1007 Instruction *Pos, PHINode *LoopPhi) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001008 do {
1009 if (DT->dominates(InstToHoist, Pos))
1010 break;
1011 // Make sure the increment is where we want it. But don't move it
1012 // down past a potential existing post-inc user.
Geoff Berry0c095172016-06-01 20:03:09 +00001013 fixupInsertPoints(InstToHoist);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001014 InstToHoist->moveBefore(Pos);
1015 Pos = InstToHoist;
1016 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1017 } while (InstToHoist != LoopPhi);
1018}
1019
1020/// \brief Check whether we can cheaply express the requested SCEV in terms of
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001021/// the available PHI SCEV by truncation and/or inversion of the step.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001022static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1023 const SCEVAddRecExpr *Phi,
1024 const SCEVAddRecExpr *Requested,
1025 bool &InvertStep) {
1026 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1027 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1028
1029 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1030 return false;
1031
1032 // Try truncate it if necessary.
1033 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1034 if (!Phi)
1035 return false;
1036
1037 // Check whether truncation will help.
1038 if (Phi == Requested) {
1039 InvertStep = false;
1040 return true;
1041 }
1042
1043 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1044 if (SE.getAddExpr(Requested->getStart(),
1045 SE.getNegativeSCEV(Requested)) == Phi) {
1046 InvertStep = true;
1047 return true;
1048 }
1049
1050 return false;
1051}
1052
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001053static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1054 if (!isa<IntegerType>(AR->getType()))
1055 return false;
1056
1057 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1058 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1059 const SCEV *Step = AR->getStepRecurrence(SE);
1060 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1061 SE.getSignExtendExpr(AR, WideTy));
1062 const SCEV *ExtendAfterOp =
1063 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1064 return ExtendAfterOp == OpAfterExtend;
1065}
1066
1067static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1068 if (!isa<IntegerType>(AR->getType()))
1069 return false;
1070
1071 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1072 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1073 const SCEV *Step = AR->getStepRecurrence(SE);
1074 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1075 SE.getZeroExtendExpr(AR, WideTy));
1076 const SCEV *ExtendAfterOp =
1077 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1078 return ExtendAfterOp == OpAfterExtend;
1079}
1080
Dan Gohman51ad99d2010-01-21 02:09:26 +00001081/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1082/// the base addrec, which is the addrec without any non-loop-dominating
1083/// values, and return the PHI.
1084PHINode *
1085SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1086 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001087 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001088 Type *IntTy,
1089 Type *&TruncTy,
1090 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001091 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001092
Dan Gohman51ad99d2010-01-21 02:09:26 +00001093 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001094 BasicBlock *LatchBlock = L->getLoopLatch();
1095 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001096 PHINode *AddRecPhiMatch = nullptr;
1097 Instruction *IncV = nullptr;
1098 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001099 InvertStep = false;
1100
1101 // Only try partially matching scevs that need truncation and/or
1102 // step-inversion if we know this loop is outside the current loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001103 bool TryNonMatchingSCEV =
1104 IVIncInsertLoop &&
1105 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001106
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001107 for (auto &I : *L->getHeader()) {
1108 auto *PN = dyn_cast<PHINode>(&I);
1109 if (!PN || !SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001110 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001111
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001112 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1113 if (!PhiSCEV)
1114 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001115
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001116 bool IsMatchingSCEV = PhiSCEV == Normalized;
1117 // We only handle truncation and inversion of phi recurrences for the
1118 // expanded expression if the expanded expression's loop dominates the
1119 // loop we insert to. Check now, so we can bail out early.
1120 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1121 continue;
1122
1123 Instruction *TempIncV =
1124 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1125
1126 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001127 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001128 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001129 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001130 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1131 continue;
1132 } else {
1133 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001134 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001135 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001136
1137 // Stop if we have found an exact match SCEV.
1138 if (IsMatchingSCEV) {
1139 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001140 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001141 InvertStep = false;
1142 AddRecPhiMatch = PN;
1143 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001144 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001145
1146 // Try whether the phi can be translated into the requested form
1147 // (truncated and/or offset by a constant).
1148 if ((!TruncTy || InvertStep) &&
1149 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1150 // Record the phi node. But don't stop we might find an exact match
1151 // later.
1152 AddRecPhiMatch = PN;
1153 IncV = TempIncV;
1154 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1155 }
1156 }
1157
1158 if (AddRecPhiMatch) {
1159 // Potentially, move the increment. We have made sure in
1160 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1161 if (L == IVIncInsertLoop)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001162 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001163
Andrew Trick7fb669a2011-10-07 23:46:21 +00001164 // Ok, the add recurrence looks usable.
1165 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001166 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001167 // Remember the increment.
1168 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001169 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001170 }
1171 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001172
1173 // Save the original insertion point so we can restore it when we're done.
Geoff Berry0c095172016-06-01 20:03:09 +00001174 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001175
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001176 // Another AddRec may need to be recursively expanded below. For example, if
1177 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1178 // loop. Remove this loop from the PostIncLoops set before expanding such
1179 // AddRecs. Otherwise, we cannot find a valid position for the step
1180 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1181 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1182 // so it's not worth implementing SmallPtrSet::swap.
1183 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1184 PostIncLoops.clear();
1185
Dan Gohman51ad99d2010-01-21 02:09:26 +00001186 // Expand code for the start value.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001187 Value *StartV =
1188 expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001189
Andrew Trick244e2c32011-07-16 00:59:39 +00001190 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001191 assert(!isa<Instruction>(StartV) ||
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001192 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1193 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001194
Andrew Trickceafa2c2011-11-30 06:07:54 +00001195 // Expand code for the step value. Do this before creating the PHI so that PHI
1196 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001197 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001198 // If the stride is negative, insert a sub instead of an add for the increment
1199 // (unless it's a constant, because subtracts of constants are canonicalized
1200 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001201 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001202 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001203 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001204 // Expand the step somewhere that dominates the loop header.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001205 Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001206
Sanjoy Das54ef8952015-02-26 19:51:35 +00001207 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1208 // we actually do emit an addition. It does not apply if we emit a
1209 // subtraction.
1210 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1211 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1212
Dan Gohman51ad99d2010-01-21 02:09:26 +00001213 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001214 BasicBlock *Header = L->getHeader();
1215 Builder.SetInsertPoint(Header, Header->begin());
1216 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001217 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001218 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001219 rememberInstruction(PN);
1220
1221 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001222 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001223 BasicBlock *Pred = *HPI;
1224
1225 // Add a start value.
1226 if (!L->contains(Pred)) {
1227 PN->addIncoming(StartV, Pred);
1228 continue;
1229 }
1230
Andrew Trickceafa2c2011-11-30 06:07:54 +00001231 // Create a step value and add it to the PHI.
1232 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1233 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001234 Instruction *InsertPos = L == IVIncInsertLoop ?
1235 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001236 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001237 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001238
Andrew Trick8eaae282013-07-14 02:50:07 +00001239 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001240 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001241 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001242 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001243 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1244 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001245 PN->addIncoming(IncV, Pred);
1246 }
1247
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001248 // After expanding subexpressions, restore the PostIncLoops set so the caller
1249 // can ensure that IVIncrement dominates the current uses.
1250 PostIncLoops = SavedPostIncLoops;
1251
Dan Gohman51ad99d2010-01-21 02:09:26 +00001252 // Remember this PHI, even in post-inc mode.
1253 InsertedValues.insert(PN);
1254
1255 return PN;
1256}
1257
1258Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001259 Type *STy = S->getType();
1260 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001261 const Loop *L = S->getLoop();
1262
1263 // Determine a normalized form of this expression, which is the expression
1264 // before any post-inc adjustment is made.
1265 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001266 if (PostIncLoops.count(L)) {
1267 PostIncLoopSet Loops;
1268 Loops.insert(L);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001269 Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1270 Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001271 }
1272
1273 // Strip off any non-loop-dominating component from the addrec start.
1274 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001275 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001276 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001277 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001278 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001279 Normalized = cast<SCEVAddRecExpr>(
1280 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1281 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001282 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001283 }
1284
1285 // Strip off any non-loop-dominating component from the addrec step.
1286 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001287 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001288 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001289 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001290 Step = SE.getConstant(Normalized->getType(), 1);
Keno Fischer1efc3b72016-07-13 01:28:12 +00001291 if (!Start->isZero()) {
1292 // The normalization below assumes that Start is constant zero, so if
1293 // it isn't re-associate Start to PostLoopOffset.
1294 assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1295 PostLoopOffset = Start;
1296 Start = SE.getConstant(Normalized->getType(), 0);
1297 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001298 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001299 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1300 Start, Step, Normalized->getLoop(),
1301 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001302 }
1303
1304 // Expand the core addrec. If we need post-loop scaling, force it to
1305 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001306 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001307 // In some cases, we decide to reuse an existing phi node but need to truncate
1308 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001309 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001310 bool InvertStep = false;
1311 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1312 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001313
Dan Gohman8b0a4192010-03-01 17:49:51 +00001314 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001315 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001316 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001317 Result = PN;
1318 else {
1319 // In PostInc mode, use the post-incremented value.
1320 BasicBlock *LatchBlock = L->getLoopLatch();
1321 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1322 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001323
1324 // For an expansion to use the postinc form, the client must call
1325 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1326 // or dominated by IVIncInsertPos.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001327 if (isa<Instruction>(Result) &&
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001328 !SE.DT.dominates(cast<Instruction>(Result),
1329 &*Builder.GetInsertPoint())) {
Andrew Trickceafa2c2011-11-30 06:07:54 +00001330 // The induction variable's postinc expansion does not dominate this use.
1331 // IVUsers tries to prevent this case, so it is rare. However, it can
1332 // happen when an IVUser outside the loop is not dominated by the latch
1333 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1334 // all cases. Consider a phi outide whose operand is replaced during
1335 // expansion with the value of the postinc user. Without fundamentally
1336 // changing the way postinc users are tracked, the only remedy is
1337 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1338 // but hopefully expandCodeFor handles that.
1339 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001340 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001341 if (useSubtract)
1342 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001343 Value *StepV;
1344 {
1345 // Expand the step somewhere that dominates the loop header.
Geoff Berry0c095172016-06-01 20:03:09 +00001346 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001347 StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Benjamin Kramer6e931522013-09-30 15:40:17 +00001348 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001349 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1350 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001351 }
1352
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001353 // We have decided to reuse an induction variable of a dominating loop. Apply
1354 // truncation and/or invertion of the step.
1355 if (TruncTy) {
1356 Type *ResTy = Result->getType();
1357 // Normalize the result type.
1358 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1359 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1360 // Truncate the result.
1361 if (TruncTy != Result->getType()) {
1362 Result = Builder.CreateTrunc(Result, TruncTy);
1363 rememberInstruction(Result);
1364 }
1365 // Invert the result.
1366 if (InvertStep) {
1367 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1368 Result);
1369 rememberInstruction(Result);
1370 }
1371 }
1372
Dan Gohman51ad99d2010-01-21 02:09:26 +00001373 // Re-apply any non-loop-dominating scale.
1374 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001375 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001376 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001377 Result = Builder.CreateMul(Result,
1378 expandCodeFor(PostLoopScale, IntTy));
1379 rememberInstruction(Result);
1380 }
1381
1382 // Re-apply any non-loop-dominating offset.
1383 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001384 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001385 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1386 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1387 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001388 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001389 Result = Builder.CreateAdd(Result,
1390 expandCodeFor(PostLoopOffset, IntTy));
1391 rememberInstruction(Result);
1392 }
1393 }
1394
1395 return Result;
1396}
1397
Dan Gohman056857a2009-04-18 17:56:28 +00001398Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001399 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1400
Chris Lattner229907c2011-07-18 04:54:35 +00001401 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001402 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001403
Dan Gohman426901a2009-06-13 16:25:49 +00001404 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001405 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001406 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001407 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001408 CanonicalIV = PN;
1409
1410 // Rewrite an AddRec in terms of the canonical induction variable, if
1411 // its type is more narrow.
1412 if (CanonicalIV &&
1413 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1414 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001415 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1416 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1417 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001418 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001419 S->getNoWrapFlags(SCEV::FlagNW)));
David Majnemer235acde2015-10-27 19:48:28 +00001420 BasicBlock::iterator NewInsertPt =
1421 findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
Craig Topper9f008862014-04-15 04:59:12 +00001422 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001423 &*NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001424 return V;
1425 }
1426
Nate Begeman2bca4d92005-07-30 00:12:19 +00001427 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001428 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001429 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001430 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001431 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1432 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001433
1434 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1435 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001436 const SCEV *Base = S->getStart();
1437 const SCEV *RestArray[1] = { Rest };
1438 // Dig into the expression to find the pointer base for a GEP.
1439 ExposePointerBase(Base, RestArray[0], SE);
1440 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001441 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001442 // Make sure the Base isn't something exotic, such as a multiplied
1443 // or divided pointer value. In those cases, the result type isn't
1444 // actually a pointer type.
1445 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1446 Value *StartV = expand(Base);
1447 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1448 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001449 }
1450 }
1451
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001452 // Just do a normal add. Pre-expand the operands to suppress folding.
Patrik Hagglund96f13af2016-06-20 10:19:04 +00001453 //
1454 // The LHS and RHS values are factored out of the expand call to make the
1455 // output independent of the argument evaluation order.
1456 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1457 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1458 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001459 }
1460
Dan Gohmancd838702010-07-26 18:28:14 +00001461 // If we don't yet have a canonical IV, create one.
1462 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001463 // Create and insert the PHI node for the induction variable in the
1464 // specified loop.
1465 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001466 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001467 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001468 &Header->front());
Dan Gohmancd838702010-07-26 18:28:14 +00001469 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001470
Hal Finkel3f5279c2013-08-18 00:16:23 +00001471 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001472 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001473 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001474 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001475 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001476 // There must be an incoming value for each predecessor, even the
1477 // duplicates!
1478 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001479 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001480 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001481
Gabor Greife82532a2010-07-09 15:40:10 +00001482 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001483 // Insert a unit add instruction right before the terminator
1484 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001485 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1486 "indvar.next",
1487 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001488 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001489 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001490 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001491 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001492 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001493 }
Gabor Greife82532a2010-07-09 15:40:10 +00001494 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001495 }
1496
Dan Gohmancd838702010-07-26 18:28:14 +00001497 // {0,+,1} --> Insert a canonical induction variable into the loop!
1498 if (S->isAffine() && S->getOperand(1)->isOne()) {
1499 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1500 "IVs with types different from the canonical IV should "
1501 "already have been handled!");
1502 return CanonicalIV;
1503 }
1504
Dan Gohman426901a2009-06-13 16:25:49 +00001505 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001506
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001507 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001508 if (S->isAffine()) // {0,+,F} --> i*F
1509 return
1510 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001511 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001512 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001513 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001514 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001515
1516 // If this is a chain of recurrences, turn it into a closed form, using the
1517 // folders, then expandCodeFor the closed form. This allows the folders to
1518 // simplify the expression without having to build a bunch of special code
1519 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001520 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001521
Dan Gohman426901a2009-06-13 16:25:49 +00001522 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001523 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001524 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001525 if (isa<SCEVAddRecExpr>(Ext))
1526 NewS = Ext;
1527
Dan Gohmanaf752342009-07-07 17:06:11 +00001528 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001529 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001530
Dan Gohman426901a2009-06-13 16:25:49 +00001531 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001532 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001533 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001534}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001535
Dan Gohman056857a2009-04-18 17:56:28 +00001536Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001537 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001538 Value *V = expandCodeFor(S->getOperand(),
1539 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001540 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001541 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001542 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001543}
1544
Dan Gohman056857a2009-04-18 17:56:28 +00001545Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001546 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001547 Value *V = expandCodeFor(S->getOperand(),
1548 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001549 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001550 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001551 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001552}
1553
Dan Gohman056857a2009-04-18 17:56:28 +00001554Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001555 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001556 Value *V = expandCodeFor(S->getOperand(),
1557 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001558 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001559 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001560 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001561}
1562
Dan Gohman056857a2009-04-18 17:56:28 +00001563Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *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.CreateICmpSGT(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, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001577 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001578 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +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 Lewyckycdb7e542007-11-25 22:41:31 +00001584 return LHS;
1585}
1586
Dan Gohman056857a2009-04-18 17:56:28 +00001587Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001588 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001589 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001590 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1591 // In the case of mixed integer and pointer types, do the
1592 // rest of the comparisons as integer.
1593 if (S->getOperand(i)->getType() != Ty) {
1594 Ty = SE.getEffectiveSCEVType(Ty);
1595 LHS = InsertNoopCastOfTo(LHS, Ty);
1596 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001597 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001598 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001599 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001600 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001601 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001602 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001603 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001604 // In the case of mixed integer and pointer types, cast the
1605 // final result back to the pointer type.
1606 if (LHS->getType() != S->getType())
1607 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001608 return LHS;
1609}
1610
Chris Lattner229907c2011-07-18 04:54:35 +00001611Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001612 Instruction *IP) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001613 assert(IP);
1614 Builder.SetInsertPoint(IP);
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001615 return expandCodeFor(SH, Ty);
1616}
1617
Chris Lattner229907c2011-07-18 04:54:35 +00001618Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001619 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001620 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001621 if (Ty) {
1622 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1623 "non-trivial casts should be done with the SCEVs directly!");
1624 V = InsertNoopCastOfTo(V, Ty);
1625 }
1626 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001627}
1628
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001629Value *SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1630 const Instruction *InsertPt) {
1631 SetVector<Value *> *Set = SE.getSCEVValues(S);
Junmo Park6ebdc142016-02-16 06:46:58 +00001632 // If the expansion is not in CanonicalMode, and the SCEV contains any
1633 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1634 if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1635 // If S is scConstant, it may be worse to reuse an existing Value.
1636 if (S->getSCEVType() != scConstant && Set) {
1637 // Choose a Value from the set which dominates the insertPt.
1638 // insertPt should be inside the Value's parent loop so as not to break
1639 // the LCSSA form.
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001640 for (auto const &Ent : *Set) {
Junmo Park6ebdc142016-02-16 06:46:58 +00001641 Instruction *EntInst = nullptr;
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001642 if (Ent && isa<Instruction>(Ent) &&
1643 (EntInst = cast<Instruction>(Ent)) &&
1644 S->getType() == Ent->getType() &&
Junmo Park6ebdc142016-02-16 06:46:58 +00001645 EntInst->getFunction() == InsertPt->getFunction() &&
1646 SE.DT.dominates(EntInst, InsertPt) &&
1647 (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001648 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) {
1649 return Ent;
1650 }
Junmo Park6ebdc142016-02-16 06:46:58 +00001651 }
1652 }
1653 }
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001654 return nullptr;
Junmo Park6ebdc142016-02-16 06:46:58 +00001655}
1656
Wei Mia49559b2016-02-04 01:27:38 +00001657// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1658// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1659// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1660// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1661// the expansion will try to reuse Value from ExprValueMap, and only when it
1662// fails, expand the SCEV literally.
Dan Gohman056857a2009-04-18 17:56:28 +00001663Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001664 // Compute an insertion point for this SCEV object. Hoist the instructions
1665 // as far out in the loop nest as possible.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001666 Instruction *InsertPt = &*Builder.GetInsertPoint();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001667 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001668 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001669 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001670 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001671 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001672 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001673 else {
1674 // LSR sets the insertion point for AddRec start/step values to the
1675 // block start to simplify value reuse, even though it's an invalid
1676 // position. SCEVExpander must correct for this in all cases.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001677 InsertPt = &*L->getHeader()->getFirstInsertionPt();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001678 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001679 } else {
1680 // If the SCEV is computable at this level, insert it into the header
1681 // after the PHIs (and after any other instructions that we've inserted
1682 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001683 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001684 InsertPt = &*L->getHeader()->getFirstInsertionPt();
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001685 while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1686 (isInsertedInstruction(InsertPt) ||
1687 isa<DbgInfoIntrinsic>(InsertPt))) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001688 InsertPt = &*std::next(InsertPt->getIterator());
Andrew Trickc908b432012-01-20 07:41:13 +00001689 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001690 break;
1691 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001692
Dan Gohmandaafbe62009-06-26 22:53:46 +00001693 // Check to see if we already expanded this here.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001694 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001695 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001696 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001697
Geoff Berry0c095172016-06-01 20:03:09 +00001698 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001699 Builder.SetInsertPoint(InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001700
1701 // Expand the expression into instructions.
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001702 Value *V = FindValueInExprValueMap(S, InsertPt);
Junmo Park6ebdc142016-02-16 06:46:58 +00001703
Wei Mia49559b2016-02-04 01:27:38 +00001704 if (!V)
1705 V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001706
Dan Gohmandaafbe62009-06-26 22:53:46 +00001707 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001708 //
1709 // This is independent of PostIncLoops. The mapped value simply materializes
1710 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001711 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001712 // its insertion point was already at the head of the loop.
1713 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001714 return V;
1715}
Dan Gohman63964b52009-06-05 16:35:53 +00001716
Dan Gohman6b751732010-02-14 03:12:47 +00001717void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001718 if (!PostIncLoops.empty())
1719 InsertedPostIncValues.insert(I);
1720 else
Dan Gohman6b751732010-02-14 03:12:47 +00001721 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001722}
1723
Dan Gohman63964b52009-06-05 16:35:53 +00001724/// getOrInsertCanonicalInductionVariable - This method returns the
1725/// canonical induction variable of the specified type for the specified
1726/// loop (inserting one if there is none). A canonical induction variable
1727/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001728PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001729SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001730 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001731 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001732
1733 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001734 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001735 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001736 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001737
1738 // Emit code for it.
Geoff Berry0c095172016-06-01 20:03:09 +00001739 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001740 PHINode *V =
1741 cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
Dan Gohman31158752010-07-20 16:46:58 +00001742
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001743 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001744}
Andrew Trickf9201c52011-10-11 02:28:51 +00001745
Andrew Trickf9201c52011-10-11 02:28:51 +00001746/// replaceCongruentIVs - Check for congruent phis in this loop header and
1747/// replace them with their most canonical representative. Return the number of
1748/// phis eliminated.
1749///
1750/// This does not depend on any SCEVExpander state but should be used in
1751/// the same context that SCEVExpander is used.
1752unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001753 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001754 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001755 // Find integer phis in order of increasing width.
1756 SmallVector<PHINode*, 8> Phis;
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001757 for (auto &I : *L->getHeader()) {
1758 if (auto *PN = dyn_cast<PHINode>(&I))
1759 Phis.push_back(PN);
1760 else
1761 break;
Andrew Trick5adedf52012-01-07 01:12:09 +00001762 }
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001763
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001764 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001765 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1766 // Put pointers at the back and make sure pointer < pointer = false.
1767 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1768 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1769 return RHS->getType()->getPrimitiveSizeInBits() <
1770 LHS->getType()->getPrimitiveSizeInBits();
1771 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001772
Andrew Trickf9201c52011-10-11 02:28:51 +00001773 unsigned NumElim = 0;
1774 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Eric Christopher572e03a2015-06-19 01:53:21 +00001775 // Process phis from wide to narrow. Map wide phis to their truncation
Andrew Trick5adedf52012-01-07 01:12:09 +00001776 // so narrow phis can reuse them.
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001777 for (PHINode *Phi : Phis) {
Silviu Baranga308a7c72015-11-03 16:27:04 +00001778 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1779 if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1780 return V;
1781 if (!SE.isSCEVable(PN->getType()))
1782 return nullptr;
1783 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1784 if (!Const)
1785 return nullptr;
1786 return Const->getValue();
1787 };
1788
Benjamin Kramera225ed82012-10-19 16:37:30 +00001789 // Fold constant phis. They may be congruent to other constant phis and
1790 // would confuse the logic below that expects proper IVs.
Silviu Baranga308a7c72015-11-03 16:27:04 +00001791 if (Value *V = SimplifyPHINode(Phi)) {
1792 if (V->getType() != Phi->getType())
1793 continue;
Benjamin Kramera225ed82012-10-19 16:37:30 +00001794 Phi->replaceAllUsesWith(V);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001795 DeadInsts.emplace_back(Phi);
Benjamin Kramera225ed82012-10-19 16:37:30 +00001796 ++NumElim;
1797 DEBUG_WITH_TYPE(DebugType, dbgs()
1798 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1799 continue;
1800 }
1801
Andrew Trickf9201c52011-10-11 02:28:51 +00001802 if (!SE.isSCEVable(Phi->getType()))
1803 continue;
1804
1805 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1806 if (!OrigPhiRef) {
1807 OrigPhiRef = Phi;
Sanjoy Das0b6518d2016-05-10 00:32:31 +00001808 if (Phi->getType()->isIntegerTy() && TTI &&
1809 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001810 // This phi can be freely truncated to the narrowest phi type. Map the
1811 // truncated expression to it so it will be reused for narrow types.
1812 const SCEV *TruncExpr =
1813 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1814 ExprToIVMap[TruncExpr] = Phi;
1815 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001816 continue;
1817 }
1818
Andrew Trick5adedf52012-01-07 01:12:09 +00001819 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1820 // sense.
1821 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001822 continue;
1823
1824 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001825 Instruction *OrigInc = dyn_cast<Instruction>(
1826 OrigPhiRef->getIncomingValueForBlock(LatchBlock));
Andrew Trickf9201c52011-10-11 02:28:51 +00001827 Instruction *IsomorphicInc =
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001828 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
Andrew Trickf9201c52011-10-11 02:28:51 +00001829
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001830 if (OrigInc && IsomorphicInc) {
1831 // If this phi has the same width but is more canonical, replace the
1832 // original with it. As part of the "more canonical" determination,
1833 // respect a prior decision to use an IV chain.
1834 if (OrigPhiRef->getType() == Phi->getType() &&
1835 !(ChainedPhis.count(Phi) ||
1836 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1837 (ChainedPhis.count(Phi) ||
1838 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1839 std::swap(OrigPhiRef, Phi);
1840 std::swap(OrigInc, IsomorphicInc);
Andrew Trick5adedf52012-01-07 01:12:09 +00001841 }
Sanjoy Das4e8c8032016-05-11 17:41:41 +00001842 // Replacing the congruent phi is sufficient because acyclic
1843 // redundancy elimination, CSE/GVN, should handle the
1844 // rest. However, once SCEV proves that a phi is congruent,
1845 // it's often the head of an IV user cycle that is isomorphic
1846 // with the original phi. It's worth eagerly cleaning up the
1847 // common case of a single IV increment so that DeleteDeadPHIs
1848 // can remove cycles that had postinc uses.
1849 const SCEV *TruncExpr =
1850 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1851 if (OrigInc != IsomorphicInc &&
1852 TruncExpr == SE.getSCEV(IsomorphicInc) &&
1853 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1854 hoistIVInc(OrigInc, IsomorphicInc)) {
1855 DEBUG_WITH_TYPE(DebugType,
1856 dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1857 << *IsomorphicInc << '\n');
1858 Value *NewInc = OrigInc;
1859 if (OrigInc->getType() != IsomorphicInc->getType()) {
1860 Instruction *IP = nullptr;
1861 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1862 IP = &*PN->getParent()->getFirstInsertionPt();
1863 else
1864 IP = OrigInc->getNextNode();
1865
1866 IRBuilder<> Builder(IP);
1867 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1868 NewInc = Builder.CreateTruncOrBitCast(
1869 OrigInc, IsomorphicInc->getType(), IVName);
1870 }
1871 IsomorphicInc->replaceAllUsesWith(NewInc);
1872 DeadInsts.emplace_back(IsomorphicInc);
1873 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001874 }
1875 }
Sanjoy Das0b6518d2016-05-10 00:32:31 +00001876 DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
1877 << *Phi << '\n');
Andrew Trickf9201c52011-10-11 02:28:51 +00001878 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001879 Value *NewIV = OrigPhiRef;
1880 if (OrigPhiRef->getType() != Phi->getType()) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001881 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
Andrew Trick5adedf52012-01-07 01:12:09 +00001882 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1883 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1884 }
1885 Phi->replaceAllUsesWith(NewIV);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001886 DeadInsts.emplace_back(Phi);
Andrew Trickf9201c52011-10-11 02:28:51 +00001887 }
1888 return NumElim;
1889}
Andrew Trick653513b2012-07-13 23:33:10 +00001890
Igor Laevsky4709c032015-08-10 18:23:58 +00001891Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1892 const Instruction *At, Loop *L) {
1893 using namespace llvm::PatternMatch;
1894
Igor Laevsky06044f92015-08-17 16:37:04 +00001895 SmallVector<BasicBlock *, 4> ExitingBlocks;
1896 L->getExitingBlocks(ExitingBlocks);
Igor Laevsky4709c032015-08-10 18:23:58 +00001897
Igor Laevsky06044f92015-08-17 16:37:04 +00001898 // Look for suitable value in simple conditions at the loop exits.
1899 for (BasicBlock *BB : ExitingBlocks) {
Igor Laevsky4709c032015-08-10 18:23:58 +00001900 ICmpInst::Predicate Pred;
1901 Instruction *LHS, *RHS;
1902 BasicBlock *TrueBB, *FalseBB;
1903
1904 if (!match(BB->getTerminator(),
1905 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1906 TrueBB, FalseBB)))
1907 continue;
1908
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001909 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
Igor Laevsky4709c032015-08-10 18:23:58 +00001910 return LHS;
1911
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001912 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
Igor Laevsky4709c032015-08-10 18:23:58 +00001913 return RHS;
1914 }
1915
Junmo Park6ebdc142016-02-16 06:46:58 +00001916 // Use expand's logic which is used for reusing a previous Value in
1917 // ExprValueMap.
Hans Wennborg685e8ff2016-07-26 23:25:13 +00001918 if (Value *Val = FindValueInExprValueMap(S, At))
Junmo Park6ebdc142016-02-16 06:46:58 +00001919 return Val;
1920
Igor Laevsky4709c032015-08-10 18:23:58 +00001921 // There is potential to make this significantly smarter, but this simple
1922 // heuristic already gets some interesting cases.
1923
1924 // Can not find suitable value.
1925 return nullptr;
1926}
1927
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001928bool SCEVExpander::isHighCostExpansionHelper(
Igor Laevsky4709c032015-08-10 18:23:58 +00001929 const SCEV *S, Loop *L, const Instruction *At,
1930 SmallPtrSetImpl<const SCEV *> &Processed) {
1931
1932 // If we can find an existing value for this scev avaliable at the point "At"
1933 // then consider the expression cheap.
1934 if (At && findExistingExpansion(S, At, L) != nullptr)
1935 return false;
Wei Mie2538b52015-05-28 21:49:07 +00001936
1937 // Zero/One operand expressions
1938 switch (S->getSCEVType()) {
1939 case scUnknown:
1940 case scConstant:
1941 return false;
1942 case scTruncate:
Igor Laevsky4709c032015-08-10 18:23:58 +00001943 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1944 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001945 case scZeroExtend:
1946 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001947 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001948 case scSignExtend:
1949 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
Igor Laevsky4709c032015-08-10 18:23:58 +00001950 L, At, Processed);
Wei Mie2538b52015-05-28 21:49:07 +00001951 }
1952
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001953 if (!Processed.insert(S).second)
1954 return false;
1955
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001956 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1957 // If the divisor is a power of two and the SCEV type fits in a native
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001958 // integer, consider the division cheap irrespective of whether it occurs in
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001959 // the user code since it can be lowered into a right shift.
1960 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001961 if (SC->getAPInt().isPowerOf2()) {
Sanjoy Dasa9f1e272015-04-14 03:20:32 +00001962 const DataLayout &DL =
1963 L->getHeader()->getParent()->getParent()->getDataLayout();
1964 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1965 return DL.isIllegalInteger(Width);
1966 }
1967
1968 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1969 // HowManyLessThans produced to compute a precise expression, rather than a
1970 // UDiv from the user's code. If we can't find a UDiv in the code with some
1971 // simple searching, assume the former consider UDivExpr expensive to
1972 // compute.
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001973 BasicBlock *ExitingBB = L->getExitingBlock();
1974 if (!ExitingBB)
1975 return true;
1976
Igor Laevsky06044f92015-08-17 16:37:04 +00001977 // At the beginning of this function we already tried to find existing value
1978 // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1979 // involving division. This is just a simple search heuristic.
1980 if (!At)
1981 At = &ExitingBB->back();
1982 if (!findExistingExpansion(
1983 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001984 return true;
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001985 }
1986
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00001987 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1988 // the exit condition.
1989 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1990 return true;
1991
Wei Mie2538b52015-05-28 21:49:07 +00001992 // Recurse past nary expressions, which commonly occur in the
1993 // BackedgeTakenCount. They may already exist in program code, and if not,
1994 // they are not too expensive rematerialize.
1995 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
Sanjoy Dasb37c4c42015-11-21 23:20:10 +00001996 for (auto *Op : NAry->operands())
1997 if (isHighCostExpansionHelper(Op, L, At, Processed))
Wei Mie2538b52015-05-28 21:49:07 +00001998 return true;
Wei Mie2538b52015-05-28 21:49:07 +00001999 }
2000
Sanjoy Das2e6bb3b2015-04-14 03:20:28 +00002001 // If we haven't recognized an expensive SCEV pattern, assume it's an
2002 // expression produced by program code.
2003 return false;
2004}
2005
Silviu Barangae3c05342015-11-02 14:41:02 +00002006Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2007 Instruction *IP) {
2008 assert(IP);
2009 switch (Pred->getKind()) {
2010 case SCEVPredicate::P_Union:
2011 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2012 case SCEVPredicate::P_Equal:
2013 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002014 case SCEVPredicate::P_Wrap: {
2015 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2016 return expandWrapPredicate(AddRecPred, IP);
2017 }
Silviu Barangae3c05342015-11-02 14:41:02 +00002018 }
2019 llvm_unreachable("Unknown SCEV predicate type");
2020}
2021
2022Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
2023 Instruction *IP) {
2024 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2025 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2026
2027 Builder.SetInsertPoint(IP);
2028 auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2029 return I;
2030}
2031
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002032Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2033 Instruction *Loc, bool Signed) {
2034 assert(AR->isAffine() && "Cannot generate RT check for "
2035 "non-affine expression");
2036
Silviu Baranga6f444df2016-04-08 14:29:09 +00002037 SCEVUnionPredicate Pred;
2038 const SCEV *ExitCount =
2039 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002040
2041 assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2042
Silviu Baranga795c6292016-04-25 09:27:16 +00002043 const SCEV *Step = AR->getStepRecurrence(SE);
2044 const SCEV *Start = AR->getStart();
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002045
Silviu Baranga795c6292016-04-25 09:27:16 +00002046 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2047 unsigned DstBits = SE.getTypeSizeInBits(AR->getType());
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002048
Silviu Baranga795c6292016-04-25 09:27:16 +00002049 // The expression {Start,+,Step} has nusw/nssw if
2050 // Step < 0, Start - |Step| * Backedge <= Start
2051 // Step >= 0, Start + |Step| * Backedge > Start
2052 // and |Step| * Backedge doesn't unsigned overflow.
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002053
Silviu Baranga795c6292016-04-25 09:27:16 +00002054 IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2055 Builder.SetInsertPoint(Loc);
2056 Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2057
2058 IntegerType *Ty =
2059 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(AR->getType()));
2060
2061 Value *StepValue = expandCodeFor(Step, Ty, Loc);
2062 Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2063 Value *StartValue = expandCodeFor(Start, Ty, Loc);
2064
2065 ConstantInt *Zero =
2066 ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002067
2068 Builder.SetInsertPoint(Loc);
Silviu Baranga795c6292016-04-25 09:27:16 +00002069 // Compute |Step|
2070 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2071 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002072
Silviu Baranga795c6292016-04-25 09:27:16 +00002073 // Get the backedge taken count and truncate or extended to the AR type.
2074 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2075 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2076 Intrinsic::umul_with_overflow, Ty);
2077
2078 // Compute |Step| * Backedge
2079 CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2080 Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2081 Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2082
2083 // Compute:
2084 // Start + |Step| * Backedge < Start
2085 // Start - |Step| * Backedge > Start
2086 Value *Add = Builder.CreateAdd(StartValue, MulV);
2087 Value *Sub = Builder.CreateSub(StartValue, MulV);
2088
2089 Value *EndCompareGT = Builder.CreateICmp(
2090 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2091
2092 Value *EndCompareLT = Builder.CreateICmp(
2093 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2094
2095 // Select the answer based on the sign of Step.
2096 Value *EndCheck =
2097 Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2098
2099 // If the backedge taken count type is larger than the AR type,
2100 // check that we don't drop any bits by truncating it. If we are
2101 // droping bits, then we have overflow (unless the step is zero).
2102 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2103 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2104 auto *BackedgeCheck =
2105 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2106 ConstantInt::get(Loc->getContext(), MaxVal));
2107 BackedgeCheck = Builder.CreateAnd(
2108 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2109
2110 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2111 }
2112
2113 EndCheck = Builder.CreateOr(EndCheck, OfMul);
2114 return EndCheck;
Silviu Barangaea63a7f2016-02-08 17:02:45 +00002115}
2116
2117Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2118 Instruction *IP) {
2119 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2120 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2121
2122 // Add a check for NUSW
2123 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2124 NUSWCheck = generateOverflowCheck(A, IP, false);
2125
2126 // Add a check for NSSW
2127 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2128 NSSWCheck = generateOverflowCheck(A, IP, true);
2129
2130 if (NUSWCheck && NSSWCheck)
2131 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2132
2133 if (NUSWCheck)
2134 return NUSWCheck;
2135
2136 if (NSSWCheck)
2137 return NSSWCheck;
2138
2139 return ConstantInt::getFalse(IP->getContext());
2140}
2141
Silviu Barangae3c05342015-11-02 14:41:02 +00002142Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2143 Instruction *IP) {
2144 auto *BoolType = IntegerType::get(IP->getContext(), 1);
2145 Value *Check = ConstantInt::getNullValue(BoolType);
2146
2147 // Loop over all checks in this set.
2148 for (auto Pred : Union->getPredicates()) {
2149 auto *NextCheck = expandCodeForPredicate(Pred, IP);
2150 Builder.SetInsertPoint(IP);
2151 Check = Builder.CreateOr(Check, NextCheck);
2152 }
2153
2154 return Check;
2155}
2156
Andrew Trick653513b2012-07-13 23:33:10 +00002157namespace {
2158// Search for a SCEV subexpression that is not safe to expand. Any expression
2159// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2160// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2161// instruction, but the important thing is that we prove the denominator is
2162// nonzero before expansion.
2163//
2164// IVUsers already checks that IV-derived expressions are safe. So this check is
2165// only needed when the expression includes some subexpression that is not IV
2166// derived.
2167//
2168// Currently, we only allow division by a nonzero constant here. If this is
2169// inadequate, we could easily allow division by SCEVUnknown by using
2170// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00002171//
2172// We cannot generally expand recurrences unless the step dominates the loop
2173// header. The expander handles the special case of affine recurrences by
2174// scaling the recurrence outside the loop, but this technique isn't generally
2175// applicable. Expanding a nested recurrence outside a loop requires computing
2176// binomial coefficients. This could be done, but the recurrence has to be in a
2177// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00002178struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00002179 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00002180 bool IsUnsafe;
2181
Andrew Trick57243da2013-10-25 21:35:56 +00002182 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00002183
2184 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00002185 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2186 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2187 if (!SC || SC->getValue()->isZero()) {
2188 IsUnsafe = true;
2189 return false;
2190 }
2191 }
2192 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2193 const SCEV *Step = AR->getStepRecurrence(SE);
2194 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2195 IsUnsafe = true;
2196 return false;
2197 }
2198 }
2199 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00002200 }
2201 bool isDone() const { return IsUnsafe; }
2202};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002203}
Andrew Trick653513b2012-07-13 23:33:10 +00002204
2205namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00002206bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2207 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00002208 visitAll(S, Search);
2209 return !Search.IsUnsafe;
2210}
2211}