blob: ca5cf1663b83af74db62bce5f57f76ba749996ba [file] [log] [blame]
Nick Lewycky7be77392016-04-24 17:55:41 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
Nate Begeman36f891bd2005-07-30 00:12:19 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Begeman36f891bd2005-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 Begeman36f891bd2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth974a4452014-01-07 11:48:04 +000018#include "llvm/ADT/SmallSet.h"
Benjamin Kramerb7f1fb42014-06-21 11:47:18 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthe4ba75f2013-01-07 14:41:08 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/LLVMContext.h"
Sanjoy Dasdee1e822015-04-14 03:20:28 +000026#include "llvm/IR/Module.h"
Jingyue Wu5d593152015-06-24 19:28:40 +000027#include "llvm/IR/PatternMatch.h"
Andrew Trickc5701912011-10-07 23:46:21 +000028#include "llvm/Support/Debug.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000029#include "llvm/Support/raw_ostream.h"
Andrew Trickd152d032011-07-16 00:59:39 +000030
Nate Begeman36f891bd2005-07-30 00:12:19 +000031using namespace llvm;
Jingyue Wu5d593152015-06-24 19:28:40 +000032using namespace PatternMatch;
Nate Begeman36f891bd2005-07-30 00:12:19 +000033
Gabor Greif19e5ada2010-07-09 16:42:04 +000034/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-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 Greif19e5ada2010-07-09 16:42:04 +000037/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000038Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000039 Instruction::CastOps Op,
40 BasicBlock::iterator IP) {
Rafael Espindola919a5032012-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 Espindola23b6ec92012-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 Ledruc8e41c52012-07-23 08:51:15 +000047 // Since we don't know the builder's insertion point is actually
Rafael Espindola919a5032012-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 Topper570e52c2014-04-15 04:59:12 +000052 Instruction *Ret = nullptr;
Rafael Espindolaef4c80e2012-02-18 17:22:58 +000053
Dan Gohman485c43f2010-06-19 13:25:23 +000054 // Check to see if there is already a cast!
Chandler Carruth36b699f2014-03-09 03:16:01 +000055 for (User *U : V->users())
Gabor Greiff64f9cf2010-07-09 16:39:02 +000056 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000057 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000058 if (CI->getOpcode() == Op) {
Rafael Espindolab84d5402012-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 Espindola919a5032012-02-22 03:21:39 +000062 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohman485c43f2010-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 Smithd3a5adc2015-10-10 00:53:03 +000066 Ret = CastInst::Create(Op, V, Ty, "", &*IP);
Rafael Espindola23b6ec92012-02-27 02:13:03 +000067 Ret->takeName(CI);
68 CI->replaceAllUsesWith(Ret);
Dan Gohman485c43f2010-06-19 13:25:23 +000069 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola23b6ec92012-02-27 02:13:03 +000070 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000071 }
Rafael Espindola23b6ec92012-02-27 02:13:03 +000072 Ret = CI;
73 break;
Dan Gohman485c43f2010-06-19 13:25:23 +000074 }
75
76 // Create a new cast.
Rafael Espindola23b6ec92012-02-27 02:13:03 +000077 if (!Ret)
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +000078 Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
Rafael Espindola23b6ec92012-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 Smithd3a5adc2015-10-10 00:53:03 +000083 assert(SE.DT.dominates(Ret, &*BIP));
Rafael Espindola23b6ec92012-02-27 02:13:03 +000084
85 rememberInstruction(Ret);
86 return Ret;
Dan Gohman485c43f2010-06-19 13:25:23 +000087}
88
David Majnemer1089dfc2015-10-27 07:36:42 +000089static BasicBlock::iterator findInsertPointAfter(Instruction *I,
David Majnemer1089dfc2015-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 Majnemer1089dfc2015-10-27 07:36:42 +000094
95 while (isa<PHINode>(IP))
96 ++IP;
97
David Majnemer5b210662016-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 Majnemer1089dfc2015-10-27 07:36:42 +0000104 }
105
106 return IP;
107}
108
Dan Gohman267a3852009-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 Lattnerdb125cf2011-07-18 04:54:35 +0000112Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-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 Gohman2d1be872009-04-16 03:18:22 +0000121 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-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 Gohmanf04fa482009-04-16 15:52:57 +0000130 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +0000131 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +0000132 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-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 Gohman80dcdee2009-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 Gohmanf04fa482009-04-16 15:52:57 +0000146
Dan Gohman485c43f2010-06-19 13:25:23 +0000147 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000148 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000149 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000150
Dan Gohman485c43f2010-06-19 13:25:23 +0000151 // Cast the argument at the beginning of the entry block, after
152 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000153 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-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 Majnemer1089dfc2015-10-27 07:36:42 +0000158 isa<DbgInfoIntrinsic>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000159 ++IP;
160 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000161 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000162
Dan Gohman485c43f2010-06-19 13:25:23 +0000163 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000164 Instruction *I = cast<Instruction>(V);
Florian Hahn26ac94d2018-06-25 20:55:26 +0000165 BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
Dan Gohman485c43f2010-06-19 13:25:23 +0000166 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000167}
168
Chris Lattner7fec90e2007-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 Gohman267a3852009-06-27 21:18:18 +0000171Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-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 Andersonbaf3c402009-07-29 18:55:55 +0000176 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000177
Chris Lattner7fec90e2007-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 Gohman267a3852009-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 Matyjewicz8a087692008-06-15 19:07:39 +0000184 --IP;
185 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-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++;
Serguei Katkovfe51c812017-12-27 08:26:22 +0000190
191 // Conservatively, do not use any instruction which has any of wrap/exact
192 // flags installed.
193 // TODO: Instead of simply disable poison instructions we can be clever
194 // here and match SCEV to this instruction.
195 auto canGeneratePoison = [](Instruction *I) {
196 if (isa<OverflowingBinaryOperator>(I) &&
197 (I->hasNoSignedWrap() || I->hasNoUnsignedWrap()))
198 return true;
199 if (isa<PossiblyExactOperator>(I) && I->isExact())
200 return true;
201 return false;
202 };
Dan Gohman5be18e82009-05-19 02:15:55 +0000203 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
Serguei Katkovfe51c812017-12-27 08:26:22 +0000204 IP->getOperand(1) == RHS && !canGeneratePoison(&*IP))
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000205 return &*IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000206 if (IP == BlockBegin) break;
207 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000208 }
Dan Gohman267a3852009-06-27 21:18:18 +0000209
Dan Gohman087bd1e2010-03-03 05:29:13 +0000210 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramerd4278822013-09-30 15:40:17 +0000211 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
Geoff Berrye81e8032016-06-01 20:03:09 +0000212 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000213
Reid Kleckner56976902016-12-12 18:52:32 +0000214 // Move the insertion point out of as many loops as we can.
215 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
216 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
217 BasicBlock *Preheader = L->getLoopPreheader();
218 if (!Preheader) break;
Sanjoy Dasb2e86a32016-11-10 07:56:12 +0000219
Reid Kleckner56976902016-12-12 18:52:32 +0000220 // Ok, move up a level.
221 Builder.SetInsertPoint(Preheader->getTerminator());
Dan Gohman087bd1e2010-03-03 05:29:13 +0000222 }
223
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000224 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000225 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramerd4278822013-09-30 15:40:17 +0000226 BO->setDebugLoc(Loc);
Dan Gohmana10756e2010-01-21 02:09:26 +0000227 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000228
Dan Gohmancf5ab822009-05-01 17:13:31 +0000229 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000230}
231
Dan Gohman4a4f7672009-05-27 02:00:53 +0000232/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000233/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000234/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000235/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000236/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
237/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
238/// check to see if the divide was folded.
Mehdi Amini529919f2015-03-10 02:37:25 +0000239static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
240 const SCEV *Factor, ScalarEvolution &SE,
241 const DataLayout &DL) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000242 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000243 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000244 return true;
245
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000246 // x/x == 1.
247 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000248 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000249 return true;
250 }
251
Dan Gohman453aa4f2009-05-24 18:06:31 +0000252 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000253 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000254 // 0/x == 0.
255 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000256 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000257 // Check for divisibility.
258 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
259 ConstantInt *CI =
Sanjoy Das4b892412015-12-17 20:28:46 +0000260 ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000261 // If the quotient is zero and the remainder is non-zero, reject
262 // the value at this scale. It will be considered for subsequent
263 // smaller scales.
264 if (!CI->isZero()) {
265 const SCEV *Div = SE.getConstant(CI);
266 S = Div;
Sanjoy Das4b892412015-12-17 20:28:46 +0000267 Remainder = SE.getAddExpr(
268 Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000269 return true;
270 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000271 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000272 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000273
274 // In a Mul, check if there is a constant operand which is a multiple
275 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000276 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000277 // Size is known, check if there is a constant operand which is a multiple
278 // of the given factor. If so, we can factor it.
279 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
280 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
Sanjoy Das4b892412015-12-17 20:28:46 +0000281 if (!C->getAPInt().srem(FC->getAPInt())) {
Mehdi Amini529919f2015-03-10 02:37:25 +0000282 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Sanjoy Das4b892412015-12-17 20:28:46 +0000283 NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
Mehdi Amini529919f2015-03-10 02:37:25 +0000284 S = SE.getMulExpr(NewMulOps);
285 return true;
Dan Gohman453aa4f2009-05-24 18:06:31 +0000286 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000287 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000288
289 // In an AddRec, check if both start and step are divisible.
290 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000291 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000292 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola39d8dcb2014-02-18 15:33:12 +0000293 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000294 return false;
295 if (!StepRem->isZero())
296 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000297 const SCEV *Start = A->getStart();
Rafael Espindola39d8dcb2014-02-18 15:33:12 +0000298 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000299 return false;
Andrew Trick6f71dd72013-07-14 03:10:08 +0000300 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
301 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000302 return true;
303 }
304
305 return false;
306}
307
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000308/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
309/// is the number of SCEVAddRecExprs present, which are kept at the end of
310/// the list.
311///
312static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000313 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000314 ScalarEvolution &SE) {
315 unsigned NumAddRecs = 0;
316 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
317 ++NumAddRecs;
318 // Group Ops into non-addrecs and addrecs.
319 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
320 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
321 // Let ScalarEvolution sort and simplify the non-addrecs list.
322 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000323 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000324 SE.getAddExpr(NoAddRecs);
325 // If it returned an add, use the operands. Otherwise it simplified
326 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000327 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000328 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000329 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000330 else if (!Sum->isZero())
331 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000332 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000333 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000334}
335
336/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
337/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
338/// This helps expose more opportunities for folding parts of the expressions
339/// into GEP indices.
340///
341static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000342 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000343 ScalarEvolution &SE) {
344 // Find the addrecs.
345 SmallVector<const SCEV *, 8> AddRecs;
346 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
347 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
348 const SCEV *Start = A->getStart();
349 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000350 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000351 AddRecs.push_back(SE.getAddRecExpr(Zero,
352 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000353 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000354 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000355 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
356 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000357 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000358 e += Add->getNumOperands();
359 } else {
360 Ops[i] = Start;
361 }
362 }
363 if (!AddRecs.empty()) {
364 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000365 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000366 // Resort the operand list, moving any constants to the front.
367 SimplifyAddOperands(Ops, Ty, SE);
368 }
369}
370
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000371/// expandAddToGEP - Expand an addition expression with a pointer type into
372/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
373/// BasicAliasAnalysis and other passes analyze the result. See the rules
374/// for getelementptr vs. inttoptr in
375/// http://llvm.org/docs/LangRef.html#pointeraliasing
376/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000377///
Dan Gohman3abf9052010-01-19 22:26:02 +0000378/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000379/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
380/// they may introduce pointer arithmetic which may not be safely converted
381/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000382///
383/// Design note: It might seem desirable for this function to be more
384/// loop-aware. If some of the indices are loop-invariant while others
385/// aren't, it might seem desirable to emit multiple GEPs, keeping the
386/// loop-invariant portions of the overall computation outside the loop.
387/// However, there are a few reasons this is not done here. Hoisting simple
388/// arithmetic is a low-level optimization that often isn't very
389/// important until late in the optimization process. In fact, passes
390/// like InstructionCombining will combine GEPs, even if it means
391/// pushing loop-invariant computation down into loops, so even if the
392/// GEPs were split here, the work would quickly be undone. The
393/// LoopStrengthReduction pass, which is usually run quite late (and
394/// after the last InstructionCombining pass), takes care of hoisting
395/// loop-invariant portions of expressions, after considering what
396/// can be folded using target addressing modes.
397///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000398Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
399 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000400 PointerType *PTy,
401 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000402 Value *V) {
David Blaikie4e933df2015-03-24 23:34:31 +0000403 Type *OriginalElTy = PTy->getElementType();
404 Type *ElTy = OriginalElTy;
Dan Gohman5be18e82009-05-19 02:15:55 +0000405 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000406 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000407 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000408
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000409 // Split AddRecs up into parts as either of the parts may be usable
410 // without the other.
411 SplitAddRecs(Ops, Ty, SE);
412
Mehdi Amini529919f2015-03-10 02:37:25 +0000413 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenault14807bd2013-09-10 19:55:24 +0000414
Bob Wilsoneb356992009-12-04 01:33:04 +0000415 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000416 // operands into GEP indices, at each level. The first index in a GEP
417 // indexes into the array implied by the pointer operand; the rest of
418 // the indices index into the element or field type selected by the
419 // preceding index.
420 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000421 // If the scale size is not 0, attempt to factor out a scale for
422 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000423 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000424 if (ElTy->isSized()) {
Matt Arsenault14807bd2013-09-10 19:55:24 +0000425 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000426 if (!ElSize->isZero()) {
427 SmallVector<const SCEV *, 8> NewOps;
Sanjoy Das108f8f32015-11-21 23:20:10 +0000428 for (const SCEV *Op : Ops) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000429 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Amini529919f2015-03-10 02:37:25 +0000430 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman150dfa82010-01-28 06:32:46 +0000431 // Op now has ElSize factored out.
432 ScaledOps.push_back(Op);
433 if (!Remainder->isZero())
434 NewOps.push_back(Remainder);
435 AnyNonZeroIndices = true;
436 } else {
437 // The operand was not divisible, so add it to the list of operands
438 // we'll scan next iteration.
Sanjoy Das108f8f32015-11-21 23:20:10 +0000439 NewOps.push_back(Op);
Dan Gohman150dfa82010-01-28 06:32:46 +0000440 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000441 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000442 // If we made any changes, update Ops.
443 if (!ScaledOps.empty()) {
444 Ops = NewOps;
445 SimplifyAddOperands(Ops, Ty, SE);
446 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000447 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000448 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000449
450 // Record the scaled array index for this level of the type. If
451 // we didn't find any operands that could be factored, tentatively
452 // assume that element zero was selected (since the zero offset
453 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000454 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000455 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000456 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
457 GepIndices.push_back(Scaled);
458
459 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000460 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 bool FoundFieldNo = false;
462 // An empty struct has no fields.
463 if (STy->getNumElements() == 0) break;
Mehdi Amini529919f2015-03-10 02:37:25 +0000464 // Field offsets are known. See if a constant offset falls within any of
465 // the struct fields.
466 if (Ops.empty())
467 break;
468 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
469 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
470 const StructLayout &SL = *DL.getStructLayout(STy);
471 uint64_t FullOffset = C->getValue()->getZExtValue();
472 if (FullOffset < SL.getSizeInBytes()) {
473 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
474 GepIndices.push_back(
475 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
476 ElTy = STy->getTypeAtIndex(ElIdx);
477 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000478 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Amini529919f2015-03-10 02:37:25 +0000479 AnyNonZeroIndices = true;
480 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000481 }
Mehdi Amini529919f2015-03-10 02:37:25 +0000482 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000483 // If no struct field offsets were found, tentatively assume that
484 // field zero was selected (since the zero offset would obviously
485 // be folded away).
486 if (!FoundFieldNo) {
487 ElTy = STy->getTypeAtIndex(0u);
488 GepIndices.push_back(
489 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
490 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000491 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000492
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000493 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000494 ElTy = ATy->getElementType();
495 else
496 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000497 }
498
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000499 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000500 // the base to i8* and do an ugly getelementptr with that. It's still
501 // better than ptrtoint+arithmetic+inttoptr at least.
502 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000503 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000504 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000505 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000506
Rafael Espindola705b48d2012-02-21 03:51:14 +0000507 assert(!isa<Instruction>(V) ||
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000508 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
Rafael Espindola4b045782012-02-21 01:19:51 +0000509
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000510 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000511 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000512
513 // Fold a GEP with constant operands.
514 if (Constant *CLHS = dyn_cast<Constant>(V))
515 if (Constant *CRHS = dyn_cast<Constant>(Idx))
David Blaikie19443c12015-04-02 18:55:32 +0000516 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
517 CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000518
519 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
520 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000521 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
522 // Scanning starts from the last instruction before the insertion point.
523 BasicBlock::iterator IP = Builder.GetInsertPoint();
524 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000525 --IP;
526 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000527 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
528 // generated code.
529 if (isa<DbgInfoIntrinsic>(IP))
530 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000531 if (IP->getOpcode() == Instruction::GetElementPtr &&
532 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000533 return &*IP;
Dan Gohman5be18e82009-05-19 02:15:55 +0000534 if (IP == BlockBegin) break;
535 }
536 }
537
Dan Gohman087bd1e2010-03-03 05:29:13 +0000538 // Save the original insertion point so we can restore it when we're done.
Geoff Berrye81e8032016-06-01 20:03:09 +0000539 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000540
541 // Move the insertion point out of as many loops as we can.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000542 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000543 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
544 BasicBlock *Preheader = L->getLoopPreheader();
545 if (!Preheader) break;
546
547 // Ok, move up a level.
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000548 Builder.SetInsertPoint(Preheader->getTerminator());
Dan Gohman087bd1e2010-03-03 05:29:13 +0000549 }
550
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000551 // Emit a GEP.
David Blaikiecf57d812015-04-03 19:41:44 +0000552 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000553 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000554
Dan Gohman5be18e82009-05-19 02:15:55 +0000555 return GEP;
556 }
557
Geoff Berrye81e8032016-06-01 20:03:09 +0000558 {
559 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000560
Geoff Berrye81e8032016-06-01 20:03:09 +0000561 // Move the insertion point out of as many loops as we can.
562 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
563 if (!L->isLoopInvariant(V)) break;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000564
David Majnemerdc9c7372016-08-11 21:15:00 +0000565 bool AnyIndexNotLoopInvariant = any_of(
566 GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
Sanjoy Das108f8f32015-11-21 23:20:10 +0000567
Geoff Berrye81e8032016-06-01 20:03:09 +0000568 if (AnyIndexNotLoopInvariant)
569 break;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000570
Geoff Berrye81e8032016-06-01 20:03:09 +0000571 BasicBlock *Preheader = L->getLoopPreheader();
572 if (!Preheader) break;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000573
Geoff Berrye81e8032016-06-01 20:03:09 +0000574 // Ok, move up a level.
575 Builder.SetInsertPoint(Preheader->getTerminator());
576 }
577
578 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
579 // because ScalarEvolution may have changed the address arithmetic to
580 // compute a value which is beyond the end of the allocated object.
581 Value *Casted = V;
582 if (V->getType() != PTy)
583 Casted = InsertNoopCastOfTo(Casted, PTy);
584 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
585 Ops.push_back(SE.getUnknown(GEP));
586 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000587 }
588
Dan Gohman5be18e82009-05-19 02:15:55 +0000589 return expand(SE.getAddExpr(Ops));
590}
591
Keno Fischerdb695a12018-07-26 21:55:03 +0000592Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
593 Value *V) {
594 const SCEV *const Ops[1] = {Op};
595 return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
596}
597
Dan Gohman087bd1e2010-03-03 05:29:13 +0000598/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
599/// SCEV expansion. If they are nested, this is the most nested. If they are
600/// neighboring, pick the later.
601static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
602 DominatorTree &DT) {
603 if (!A) return B;
604 if (!B) return A;
605 if (A->contains(B)) return B;
606 if (B->contains(A)) return A;
607 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
608 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
609 return A; // Arbitrarily break the tie.
610}
611
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000612/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000613/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000614const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
615 // Test whether we've already computed the most relevant loop for this SCEV.
Sanjoy Das108f8f32015-11-21 23:20:10 +0000616 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000617 if (!Pair.second)
618 return Pair.first->second;
619
Dan Gohman087bd1e2010-03-03 05:29:13 +0000620 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000621 // A constant has no relevant loops.
Craig Topper570e52c2014-04-15 04:59:12 +0000622 return nullptr;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000623 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
624 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000625 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000626 // A non-instruction has no relevant loops.
Craig Topper570e52c2014-04-15 04:59:12 +0000627 return nullptr;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000628 }
629 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper570e52c2014-04-15 04:59:12 +0000630 const Loop *L = nullptr;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000631 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
632 L = AR->getLoop();
Sanjoy Das108f8f32015-11-21 23:20:10 +0000633 for (const SCEV *Op : N->operands())
634 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000635 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000636 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000637 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
638 const Loop *Result = getRelevantLoop(C->getOperand());
639 return RelevantLoops[C] = Result;
640 }
641 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000642 const Loop *Result = PickMostRelevantLoop(
643 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000644 return RelevantLoops[D] = Result;
645 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000646 llvm_unreachable("Unexpected SCEV type!");
647}
648
Dan Gohmanb3579832010-04-15 17:08:50 +0000649namespace {
650
Dan Gohman087bd1e2010-03-03 05:29:13 +0000651/// LoopCompare - Compare loops by PickMostRelevantLoop.
652class LoopCompare {
653 DominatorTree &DT;
654public:
655 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
656
657 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
658 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000659 // Keep pointer operands sorted at the end.
660 if (LHS.second->getType()->isPointerTy() !=
661 RHS.second->getType()->isPointerTy())
662 return LHS.second->getType()->isPointerTy();
663
Dan Gohman087bd1e2010-03-03 05:29:13 +0000664 // Compare loops with PickMostRelevantLoop.
665 if (LHS.first != RHS.first)
666 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
667
668 // If one operand is a non-constant negative and the other is not,
669 // put the non-constant negative on the right so that a sub can
670 // be used instead of a negate and add.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000671 if (LHS.second->isNonConstantNegative()) {
672 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000673 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000674 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000675 return true;
676
677 // Otherwise they are equivalent according to this comparison.
678 return false;
679 }
680};
681
Alexander Kornienkocd52a7a2015-06-23 09:49:53 +0000682}
Dan Gohmanb3579832010-04-15 17:08:50 +0000683
Dan Gohman890f92b2009-04-18 17:56:28 +0000684Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000685 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000686
Dan Gohman087bd1e2010-03-03 05:29:13 +0000687 // Collect all the add operands in a loop, along with their associated loops.
688 // Iterate in reverse so that constants are emitted last, all else equal, and
689 // so that pointer operands are inserted first, which the code below relies on
690 // to form more involved GEPs.
691 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
692 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
693 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000694 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000695
Dan Gohman087bd1e2010-03-03 05:29:13 +0000696 // Sort by loop. Use a stable sort so that constants follow non-constants and
697 // pointer operands precede non-pointer operands.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000698 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000699
Dan Gohman087bd1e2010-03-03 05:29:13 +0000700 // Emit instructions to add all the operands. Hoist as much as possible
701 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper570e52c2014-04-15 04:59:12 +0000702 Value *Sum = nullptr;
Sanjoy Das108f8f32015-11-21 23:20:10 +0000703 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000704 const Loop *CurLoop = I->first;
705 const SCEV *Op = I->second;
706 if (!Sum) {
707 // This is the first operand. Just expand it.
708 Sum = expand(Op);
709 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000710 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000711 // The running sum expression is a pointer. Try to form a getelementptr
712 // at this level with that as the base.
713 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000714 for (; I != E && I->first == CurLoop; ++I) {
715 // If the operand is SCEVUnknown and not instructions, peek through
716 // it, to enable more of it to be folded into the GEP.
717 const SCEV *X = I->second;
718 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
719 if (!isa<Instruction>(U->getValue()))
720 X = SE.getSCEV(U->getValue());
721 NewOps.push_back(X);
722 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000723 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000724 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000725 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000726 // Try to form a getelementptr. If the running sum is instructions,
727 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000728 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000729 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
730 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000731 for (++I; I != E && I->first == CurLoop; ++I)
732 NewOps.push_back(I->second);
733 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000734 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000735 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000736 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000737 Sum = InsertNoopCastOfTo(Sum, Ty);
738 Sum = InsertBinop(Instruction::Sub, Sum, W);
739 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000740 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000741 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000742 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000743 Sum = InsertNoopCastOfTo(Sum, Ty);
744 // Canonicalize a constant to the RHS.
745 if (isa<Constant>(Sum)) std::swap(Sum, W);
746 Sum = InsertBinop(Instruction::Add, Sum, W);
747 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000748 }
749 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000750
751 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000752}
Dan Gohman5be18e82009-05-19 02:15:55 +0000753
Dan Gohman890f92b2009-04-18 17:56:28 +0000754Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000755 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891bd2005-07-30 00:12:19 +0000756
Dan Gohman087bd1e2010-03-03 05:29:13 +0000757 // Collect all the mul operands in a loop, along with their associated loops.
758 // Iterate in reverse so that constants are emitted last, all else equal.
759 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
760 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
761 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000762 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891bd2005-07-30 00:12:19 +0000763
Dan Gohman087bd1e2010-03-03 05:29:13 +0000764 // Sort by loop. Use a stable sort so that constants follow non-constants.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000765 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000766
767 // Emit instructions to mul all the operands. Hoist as much as possible
768 // out of loops.
Craig Topper570e52c2014-04-15 04:59:12 +0000769 Value *Prod = nullptr;
Max Kazantsev9026c3d2017-06-19 06:24:53 +0000770 auto I = OpsAndLoops.begin();
771
772 // Expand the calculation of X pow N in the following manner:
773 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
774 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
775 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
776 auto E = I;
777 // Calculate how many times the same operand from the same loop is included
778 // into this power.
779 uint64_t Exponent = 0;
780 const uint64_t MaxExponent = UINT64_MAX >> 1;
781 // No one sane will ever try to calculate such huge exponents, but if we
782 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
783 // below when the power of 2 exceeds our Exponent, and we want it to be
784 // 1u << 31 at most to not deal with unsigned overflow.
785 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
786 ++Exponent;
787 ++E;
788 }
789 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
790
791 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
792 // that are needed into the result.
793 Value *P = expandCodeFor(I->second, Ty);
794 Value *Result = nullptr;
795 if (Exponent & 1)
796 Result = P;
797 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
798 P = InsertBinop(Instruction::Mul, P, P);
799 if (Exponent & BinExp)
800 Result = Result ? InsertBinop(Instruction::Mul, Result, P) : P;
801 }
802
803 I = E;
804 assert(Result && "Nothing was expanded?");
805 return Result;
806 };
807
808 while (I != OpsAndLoops.end()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000809 if (!Prod) {
810 // This is the first operand. Just expand it.
Max Kazantsev9026c3d2017-06-19 06:24:53 +0000811 Prod = ExpandOpBinPowN();
812 } else if (I->second->isAllOnesValue()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000813 // Instead of doing a multiply by negative one, just do a negate.
814 Prod = InsertNoopCastOfTo(Prod, Ty);
815 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
Max Kazantsev9026c3d2017-06-19 06:24:53 +0000816 ++I;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000817 } else {
818 // A simple mul.
Max Kazantsev9026c3d2017-06-19 06:24:53 +0000819 Value *W = ExpandOpBinPowN();
Dan Gohman087bd1e2010-03-03 05:29:13 +0000820 Prod = InsertNoopCastOfTo(Prod, Ty);
821 // Canonicalize a constant to the RHS.
822 if (isa<Constant>(Prod)) std::swap(Prod, W);
Jingyue Wu5d593152015-06-24 19:28:40 +0000823 const APInt *RHS;
824 if (match(W, m_Power2(RHS))) {
825 // Canonicalize Prod*(1<<C) to Prod<<C.
826 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
827 Prod = InsertBinop(Instruction::Shl, Prod,
828 ConstantInt::get(Ty, RHS->logBase2()));
829 } else {
830 Prod = InsertBinop(Instruction::Mul, Prod, W);
831 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000832 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000833 }
834
Dan Gohman087bd1e2010-03-03 05:29:13 +0000835 return Prod;
Nate Begeman36f891bd2005-07-30 00:12:19 +0000836}
837
Dan Gohman890f92b2009-04-18 17:56:28 +0000838Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000839 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000840
Dan Gohman92fcdca2009-06-09 17:18:38 +0000841 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000842 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Sanjoy Das4b892412015-12-17 20:28:46 +0000843 const APInt &RHS = SC->getAPInt();
Nick Lewycky6177fd42008-07-08 05:05:37 +0000844 if (RHS.isPowerOf2())
845 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000846 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000847 }
848
Dan Gohman92fcdca2009-06-09 17:18:38 +0000849 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000850 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000851}
852
Dan Gohman453aa4f2009-05-24 18:06:31 +0000853/// Move parts of Base into Rest to leave Base with the minimal
854/// expression that provides a pointer operand suitable for a
855/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000856static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000857 ScalarEvolution &SE) {
858 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
859 Base = A->getStart();
860 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000861 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000862 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000863 A->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +0000864 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000865 }
866 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
867 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000868 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000869 NewAddOps.back() = Rest;
870 Rest = SE.getAddExpr(NewAddOps);
871 ExposePointerBase(Base, Rest, SE);
872 }
873}
874
Andrew Trickc5701912011-10-07 23:46:21 +0000875/// Determine if this is a well-behaved chain of instructions leading back to
876/// the PHI. If so, it may be reused by expanded expressions.
877bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
878 const Loop *L) {
879 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
880 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
881 return false;
882 // If any of the operands don't dominate the insert position, bail.
883 // Addrec operands are always loop-invariant, so this can only happen
884 // if there are instructions which haven't been hoisted.
885 if (L == IVIncInsertLoop) {
886 for (User::op_iterator OI = IncV->op_begin()+1,
887 OE = IncV->op_end(); OI != OE; ++OI)
888 if (Instruction *OInst = dyn_cast<Instruction>(OI))
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000889 if (!SE.DT.dominates(OInst, IVIncInsertPos))
Andrew Trickc5701912011-10-07 23:46:21 +0000890 return false;
891 }
892 // Advance to the next instruction.
893 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
894 if (!IncV)
895 return false;
896
897 if (IncV->mayHaveSideEffects())
898 return false;
899
Bjorn Petterssone7acf092017-12-14 14:47:52 +0000900 if (IncV == PN)
Andrew Trickc5701912011-10-07 23:46:21 +0000901 return true;
902
903 return isNormalAddRecExprPHI(PN, IncV, L);
904}
905
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000906/// getIVIncOperand returns an induction variable increment's induction
907/// variable operand.
908///
909/// If allowScale is set, any type of GEP is allowed as long as the nonIV
910/// operands dominate InsertPos.
911///
912/// If allowScale is not set, ensure that a GEP increment conforms to one of the
913/// simple patterns generated by getAddRecExprPHILiterally and
914/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
915Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
916 Instruction *InsertPos,
917 bool allowScale) {
918 if (IncV == InsertPos)
Craig Topper570e52c2014-04-15 04:59:12 +0000919 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000920
921 switch (IncV->getOpcode()) {
922 default:
Craig Topper570e52c2014-04-15 04:59:12 +0000923 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000924 // Check for a simple Add/Sub or GEP of a loop invariant step.
925 case Instruction::Add:
926 case Instruction::Sub: {
927 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000928 if (!OInst || SE.DT.dominates(OInst, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000929 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper570e52c2014-04-15 04:59:12 +0000930 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000931 }
932 case Instruction::BitCast:
933 return dyn_cast<Instruction>(IncV->getOperand(0));
934 case Instruction::GetElementPtr:
Sanjoy Das108f8f32015-11-21 23:20:10 +0000935 for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000936 if (isa<Constant>(*I))
937 continue;
938 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000939 if (!SE.DT.dominates(OInst, InsertPos))
Craig Topper570e52c2014-04-15 04:59:12 +0000940 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000941 }
942 if (allowScale) {
943 // allow any kind of GEP as long as it can be hoisted.
944 continue;
945 }
946 // This must be a pointer addition of constants (pretty), which is already
947 // handled, or some number of address-size elements (ugly). Ugly geps
948 // have 2 operands. i1* is used by the expander to represent an
949 // address-size element.
950 if (IncV->getNumOperands() != 2)
Craig Topper570e52c2014-04-15 04:59:12 +0000951 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000952 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
953 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
954 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper570e52c2014-04-15 04:59:12 +0000955 return nullptr;
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000956 break;
957 }
958 return dyn_cast<Instruction>(IncV->getOperand(0));
959 }
960}
961
Geoff Berrye81e8032016-06-01 20:03:09 +0000962/// If the insert point of the current builder or any of the builders on the
963/// stack of saved builders has 'I' as its insert point, update it to point to
964/// the instruction after 'I'. This is intended to be used when the instruction
965/// 'I' is being moved. If this fixup is not done and 'I' is moved to a
966/// different block, the inconsistent insert point (with a mismatched
967/// Instruction and Block) can lead to an instruction being inserted in a block
968/// other than its parent.
969void SCEVExpander::fixupInsertPoints(Instruction *I) {
970 BasicBlock::iterator It(*I);
971 BasicBlock::iterator NewInsertPt = std::next(It);
972 if (Builder.GetInsertPoint() == It)
973 Builder.SetInsertPoint(&*NewInsertPt);
974 for (auto *InsertPtGuard : InsertPointGuards)
975 if (InsertPtGuard->GetInsertPoint() == It)
976 InsertPtGuard->SetInsertPoint(NewInsertPt);
977}
978
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000979/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
980/// it available to other uses in this loop. Recursively hoist any operands,
981/// until we reach a value that dominates InsertPos.
982bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000983 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000984 return true;
985
986 // InsertPos must itself dominate IncV so that IncV's new position satisfies
987 // its existing users.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +0000988 if (isa<PHINode>(InsertPos) ||
989 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000990 return false;
991
Sanjoy Das51d40ae2015-12-08 00:13:17 +0000992 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
993 return false;
994
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000995 // Check that the chain of IV operands leading back to Phi can be hoisted.
996 SmallVector<Instruction*, 4> IVIncs;
997 for(;;) {
998 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
999 if (!Oper)
1000 return false;
1001 // IncV is safe to hoist.
1002 IVIncs.push_back(IncV);
1003 IncV = Oper;
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00001004 if (SE.DT.dominates(IncV, InsertPos))
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001005 break;
1006 }
Sanjoy Das108f8f32015-11-21 23:20:10 +00001007 for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
Geoff Berrye81e8032016-06-01 20:03:09 +00001008 fixupInsertPoints(*I);
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001009 (*I)->moveBefore(InsertPos);
1010 }
1011 return true;
1012}
1013
Andrew Trickc5701912011-10-07 23:46:21 +00001014/// Determine if this cyclic phi is in a form that would have been generated by
1015/// LSR. We don't care if the phi was actually expanded in this pass, as long
1016/// as it is in a low-cost form, for example, no implied multiplication. This
1017/// should match any patterns generated by getAddRecExprPHILiterally and
1018/// expandAddtoGEP.
1019bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +00001020 const Loop *L) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001021 for(Instruction *IVOper = IncV;
1022 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
1023 /*allowScale=*/false));) {
1024 if (IVOper == PN)
1025 return true;
Andrew Trickc5701912011-10-07 23:46:21 +00001026 }
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001027 return false;
Andrew Trickc5701912011-10-07 23:46:21 +00001028}
1029
Andrew Trick553fe052011-11-30 06:07:54 +00001030/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1031/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1032/// need to materialize IV increments elsewhere to handle difficult situations.
1033Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1034 Type *ExpandTy, Type *IntTy,
1035 bool useSubtract) {
1036 Value *IncV;
1037 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1038 if (ExpandTy->isPointerTy()) {
1039 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1040 // If the step isn't constant, don't use an implicitly scaled GEP, because
1041 // that would require a multiply inside the loop.
1042 if (!isa<ConstantInt>(StepV))
1043 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1044 GEPPtrTy->getAddressSpace());
Keno Fischerdb695a12018-07-26 21:55:03 +00001045 IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
Andrew Trick553fe052011-11-30 06:07:54 +00001046 if (IncV->getType() != PN->getType()) {
1047 IncV = Builder.CreateBitCast(IncV, PN->getType());
1048 rememberInstruction(IncV);
1049 }
1050 } else {
1051 IncV = useSubtract ?
1052 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1053 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1054 rememberInstruction(IncV);
1055 }
1056 return IncV;
1057}
1058
Adrian Prantl26b584c2018-05-01 15:54:18 +00001059/// Hoist the addrec instruction chain rooted in the loop phi above the
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001060/// position. This routine assumes that this is possible (has been checked).
Geoff Berrye81e8032016-06-01 20:03:09 +00001061void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1062 Instruction *Pos, PHINode *LoopPhi) {
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001063 do {
1064 if (DT->dominates(InstToHoist, Pos))
1065 break;
1066 // Make sure the increment is where we want it. But don't move it
1067 // down past a potential existing post-inc user.
Geoff Berrye81e8032016-06-01 20:03:09 +00001068 fixupInsertPoints(InstToHoist);
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001069 InstToHoist->moveBefore(Pos);
1070 Pos = InstToHoist;
1071 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1072 } while (InstToHoist != LoopPhi);
1073}
1074
Adrian Prantl26b584c2018-05-01 15:54:18 +00001075/// Check whether we can cheaply express the requested SCEV in terms of
Benjamin Kramerd3c712e2015-08-08 18:27:36 +00001076/// the available PHI SCEV by truncation and/or inversion of the step.
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001077static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1078 const SCEVAddRecExpr *Phi,
1079 const SCEVAddRecExpr *Requested,
1080 bool &InvertStep) {
1081 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1082 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1083
1084 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1085 return false;
1086
1087 // Try truncate it if necessary.
1088 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1089 if (!Phi)
1090 return false;
1091
1092 // Check whether truncation will help.
1093 if (Phi == Requested) {
1094 InvertStep = false;
1095 return true;
1096 }
1097
1098 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1099 if (SE.getAddExpr(Requested->getStart(),
1100 SE.getNegativeSCEV(Requested)) == Phi) {
1101 InvertStep = true;
1102 return true;
1103 }
1104
1105 return false;
1106}
1107
Sanjoy Dasa0a0b402015-02-25 20:02:59 +00001108static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1109 if (!isa<IntegerType>(AR->getType()))
1110 return false;
1111
1112 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1113 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1114 const SCEV *Step = AR->getStepRecurrence(SE);
1115 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1116 SE.getSignExtendExpr(AR, WideTy));
1117 const SCEV *ExtendAfterOp =
1118 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1119 return ExtendAfterOp == OpAfterExtend;
1120}
1121
1122static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1123 if (!isa<IntegerType>(AR->getType()))
1124 return false;
1125
1126 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1127 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1128 const SCEV *Step = AR->getStepRecurrence(SE);
1129 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1130 SE.getZeroExtendExpr(AR, WideTy));
1131 const SCEV *ExtendAfterOp =
1132 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1133 return ExtendAfterOp == OpAfterExtend;
1134}
1135
Dan Gohmana10756e2010-01-21 02:09:26 +00001136/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1137/// the base addrec, which is the addrec without any non-loop-dominating
1138/// values, and return the PHI.
1139PHINode *
1140SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1141 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001142 Type *ExpandTy,
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001143 Type *IntTy,
1144 Type *&TruncTy,
1145 bool &InvertStep) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001146 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +00001147
Dan Gohmana10756e2010-01-21 02:09:26 +00001148 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +00001149 BasicBlock *LatchBlock = L->getLoopLatch();
1150 if (LatchBlock) {
Craig Topper570e52c2014-04-15 04:59:12 +00001151 PHINode *AddRecPhiMatch = nullptr;
1152 Instruction *IncV = nullptr;
1153 TruncTy = nullptr;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001154 InvertStep = false;
1155
1156 // Only try partially matching scevs that need truncation and/or
1157 // step-inversion if we know this loop is outside the current loop.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00001158 bool TryNonMatchingSCEV =
1159 IVIncInsertLoop &&
1160 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001161
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001162 for (PHINode &PN : L->getHeader()->phis()) {
1163 if (!SE.isSCEVable(PN.getType()))
Andrew Trickc5701912011-10-07 23:46:21 +00001164 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001165
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001166 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001167 if (!PhiSCEV)
1168 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001169
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001170 bool IsMatchingSCEV = PhiSCEV == Normalized;
1171 // We only handle truncation and inversion of phi recurrences for the
1172 // expanded expression if the expanded expression's loop dominates the
1173 // loop we insert to. Check now, so we can bail out early.
1174 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1175 continue;
1176
Roman Lebedev998f8602018-06-29 07:44:20 +00001177 // TODO: this possibly can be reworked to avoid this cast at all.
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001178 Instruction *TempIncV =
Roman Lebedev998f8602018-06-29 07:44:20 +00001179 dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
1180 if (!TempIncV)
1181 continue;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001182
1183 // Check whether we can reuse this PHI node.
Andrew Trickc5701912011-10-07 23:46:21 +00001184 if (LSRMode) {
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001185 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +00001186 continue;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001187 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1188 continue;
1189 } else {
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001190 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001191 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001192 }
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001193
1194 // Stop if we have found an exact match SCEV.
1195 if (IsMatchingSCEV) {
1196 IncV = TempIncV;
Craig Topper570e52c2014-04-15 04:59:12 +00001197 TruncTy = nullptr;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001198 InvertStep = false;
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001199 AddRecPhiMatch = &PN;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001200 break;
Andrew Trickc5701912011-10-07 23:46:21 +00001201 }
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001202
1203 // Try whether the phi can be translated into the requested form
1204 // (truncated and/or offset by a constant).
1205 if ((!TruncTy || InvertStep) &&
1206 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1207 // Record the phi node. But don't stop we might find an exact match
1208 // later.
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001209 AddRecPhiMatch = &PN;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001210 IncV = TempIncV;
1211 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1212 }
1213 }
1214
1215 if (AddRecPhiMatch) {
1216 // Potentially, move the increment. We have made sure in
1217 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1218 if (L == IVIncInsertLoop)
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00001219 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001220
Andrew Trickc5701912011-10-07 23:46:21 +00001221 // Ok, the add recurrence looks usable.
1222 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001223 InsertedValues.insert(AddRecPhiMatch);
Andrew Trickc5701912011-10-07 23:46:21 +00001224 // Remember the increment.
1225 rememberInstruction(IncV);
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001226 return AddRecPhiMatch;
Andrew Trickc5701912011-10-07 23:46:21 +00001227 }
1228 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001229
1230 // Save the original insertion point so we can restore it when we're done.
Geoff Berrye81e8032016-06-01 20:03:09 +00001231 SCEVInsertPointGuard Guard(Builder, this);
Dan Gohmana10756e2010-01-21 02:09:26 +00001232
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001233 // Another AddRec may need to be recursively expanded below. For example, if
1234 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1235 // loop. Remove this loop from the PostIncLoops set before expanding such
1236 // AddRecs. Otherwise, we cannot find a valid position for the step
1237 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1238 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1239 // so it's not worth implementing SmallPtrSet::swap.
1240 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1241 PostIncLoops.clear();
1242
Sanjoy Das7af32782016-12-11 19:02:21 +00001243 // Expand code for the start value into the loop preheader.
1244 assert(L->getLoopPreheader() &&
1245 "Can't expand add recurrences without a loop preheader!");
1246 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1247 L->getLoopPreheader()->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +00001248
Sanjoy Das7af32782016-12-11 19:02:21 +00001249 // StartV must have been be inserted into L's preheader to dominate the new
1250 // phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001251 assert(!isa<Instruction>(StartV) ||
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00001252 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1253 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001254
Andrew Trick553fe052011-11-30 06:07:54 +00001255 // Expand code for the step value. Do this before creating the PHI so that PHI
1256 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001257 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001258 // If the stride is negative, insert a sub instead of an add for the increment
1259 // (unless it's a constant, because subtracts of constants are canonicalized
1260 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001261 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001262 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001263 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001264 // Expand the step somewhere that dominates the loop header.
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001265 Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Dan Gohmana10756e2010-01-21 02:09:26 +00001266
Sanjoy Dase836f052015-02-26 19:51:35 +00001267 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1268 // we actually do emit an addition. It does not apply if we emit a
1269 // subtraction.
1270 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1271 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1272
Dan Gohmana10756e2010-01-21 02:09:26 +00001273 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001274 BasicBlock *Header = L->getHeader();
1275 Builder.SetInsertPoint(Header, Header->begin());
1276 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001277 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001278 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001279 rememberInstruction(PN);
1280
1281 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001282 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001283 BasicBlock *Pred = *HPI;
1284
1285 // Add a start value.
1286 if (!L->contains(Pred)) {
1287 PN->addIncoming(StartV, Pred);
1288 continue;
1289 }
1290
Andrew Trick553fe052011-11-30 06:07:54 +00001291 // Create a step value and add it to the PHI.
1292 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1293 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001294 Instruction *InsertPos = L == IVIncInsertLoop ?
1295 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001296 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001297 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasa0a0b402015-02-25 20:02:59 +00001298
Andrew Trick409443b2013-07-14 02:50:07 +00001299 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasa0a0b402015-02-25 20:02:59 +00001300 if (IncrementIsNUW)
Andrew Trick409443b2013-07-14 02:50:07 +00001301 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasa0a0b402015-02-25 20:02:59 +00001302 if (IncrementIsNSW)
Andrew Trick409443b2013-07-14 02:50:07 +00001303 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1304 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001305 PN->addIncoming(IncV, Pred);
1306 }
1307
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001308 // After expanding subexpressions, restore the PostIncLoops set so the caller
1309 // can ensure that IVIncrement dominates the current uses.
1310 PostIncLoops = SavedPostIncLoops;
1311
Dan Gohmana10756e2010-01-21 02:09:26 +00001312 // Remember this PHI, even in post-inc mode.
1313 InsertedValues.insert(PN);
1314
1315 return PN;
1316}
1317
1318Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001319 Type *STy = S->getType();
1320 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001321 const Loop *L = S->getLoop();
1322
1323 // Determine a normalized form of this expression, which is the expression
1324 // before any post-inc adjustment is made.
1325 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001326 if (PostIncLoops.count(L)) {
1327 PostIncLoopSet Loops;
1328 Loops.insert(L);
Sanjoy Dasfe33eb82017-04-14 15:49:59 +00001329 Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
Dan Gohmana10756e2010-01-21 02:09:26 +00001330 }
1331
1332 // Strip off any non-loop-dominating component from the addrec start.
1333 const SCEV *Start = Normalized->getStart();
Craig Topper570e52c2014-04-15 04:59:12 +00001334 const SCEV *PostLoopOffset = nullptr;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001335 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001336 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001337 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001338 Normalized = cast<SCEVAddRecExpr>(
1339 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1340 Normalized->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001341 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001342 }
1343
1344 // Strip off any non-loop-dominating component from the addrec step.
1345 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper570e52c2014-04-15 04:59:12 +00001346 const SCEV *PostLoopScale = nullptr;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001347 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001348 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001349 Step = SE.getConstant(Normalized->getType(), 1);
Keno Fischerc8ce9e52016-07-13 01:28:12 +00001350 if (!Start->isZero()) {
1351 // The normalization below assumes that Start is constant zero, so if
1352 // it isn't re-associate Start to PostLoopOffset.
1353 assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1354 PostLoopOffset = Start;
1355 Start = SE.getConstant(Normalized->getType(), 0);
1356 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001357 Normalized =
Andrew Trick6f71dd72013-07-14 03:10:08 +00001358 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1359 Start, Step, Normalized->getLoop(),
1360 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmana10756e2010-01-21 02:09:26 +00001361 }
1362
1363 // Expand the core addrec. If we need post-loop scaling, force it to
1364 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001365 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Keno Fischer65ac22c2017-05-27 03:22:55 +00001366 // We can't use a pointer type for the addrec if the pointer type is
1367 // non-integral.
1368 Type *AddRecPHIExpandTy =
1369 DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
1370
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001371 // In some cases, we decide to reuse an existing phi node but need to truncate
1372 // it and/or invert the step.
Craig Topper570e52c2014-04-15 04:59:12 +00001373 Type *TruncTy = nullptr;
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001374 bool InvertStep = false;
Keno Fischer65ac22c2017-05-27 03:22:55 +00001375 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1376 IntTy, TruncTy, InvertStep);
Dan Gohmana10756e2010-01-21 02:09:26 +00001377
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001378 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001379 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001380 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001381 Result = PN;
1382 else {
1383 // In PostInc mode, use the post-incremented value.
1384 BasicBlock *LatchBlock = L->getLoopLatch();
1385 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1386 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001387
1388 // For an expansion to use the postinc form, the client must call
1389 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1390 // or dominated by IVIncInsertPos.
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00001391 if (isa<Instruction>(Result) &&
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001392 !SE.DT.dominates(cast<Instruction>(Result),
1393 &*Builder.GetInsertPoint())) {
Andrew Trick553fe052011-11-30 06:07:54 +00001394 // The induction variable's postinc expansion does not dominate this use.
1395 // IVUsers tries to prevent this case, so it is rare. However, it can
1396 // happen when an IVUser outside the loop is not dominated by the latch
1397 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
Vedant Kumard9244422018-03-02 18:57:02 +00001398 // all cases. Consider a phi outside whose operand is replaced during
Andrew Trick553fe052011-11-30 06:07:54 +00001399 // expansion with the value of the postinc user. Without fundamentally
1400 // changing the way postinc users are tracked, the only remedy is
1401 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1402 // but hopefully expandCodeFor handles that.
1403 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001404 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001405 if (useSubtract)
1406 Step = SE.getNegativeSCEV(Step);
Benjamin Kramerd4278822013-09-30 15:40:17 +00001407 Value *StepV;
1408 {
1409 // Expand the step somewhere that dominates the loop header.
Geoff Berrye81e8032016-06-01 20:03:09 +00001410 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001411 StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
Benjamin Kramerd4278822013-09-30 15:40:17 +00001412 }
Andrew Trick553fe052011-11-30 06:07:54 +00001413 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1414 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001415 }
1416
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001417 // We have decided to reuse an induction variable of a dominating loop. Apply
Vedant Kumard9244422018-03-02 18:57:02 +00001418 // truncation and/or inversion of the step.
Arnold Schwaighofer2ced3382014-02-16 15:49:50 +00001419 if (TruncTy) {
1420 Type *ResTy = Result->getType();
1421 // Normalize the result type.
1422 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1423 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1424 // Truncate the result.
1425 if (TruncTy != Result->getType()) {
1426 Result = Builder.CreateTrunc(Result, TruncTy);
1427 rememberInstruction(Result);
1428 }
1429 // Invert the result.
1430 if (InvertStep) {
1431 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1432 Result);
1433 rememberInstruction(Result);
1434 }
1435 }
1436
Dan Gohmana10756e2010-01-21 02:09:26 +00001437 // Re-apply any non-loop-dominating scale.
1438 if (PostLoopScale) {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00001439 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman0a799ab2010-02-12 20:39:25 +00001440 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001441 Result = Builder.CreateMul(Result,
1442 expandCodeFor(PostLoopScale, IntTy));
1443 rememberInstruction(Result);
1444 }
1445
1446 // Re-apply any non-loop-dominating offset.
1447 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001448 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Keno Fischer65ac22c2017-05-27 03:22:55 +00001449 if (Result->getType()->isIntegerTy()) {
1450 Value *Base = expandCodeFor(PostLoopOffset, ExpandTy);
Keno Fischerdb695a12018-07-26 21:55:03 +00001451 Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
Keno Fischer65ac22c2017-05-27 03:22:55 +00001452 } else {
Keno Fischerdb695a12018-07-26 21:55:03 +00001453 Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
Keno Fischer65ac22c2017-05-27 03:22:55 +00001454 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001455 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001456 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001457 Result = Builder.CreateAdd(Result,
1458 expandCodeFor(PostLoopOffset, IntTy));
1459 rememberInstruction(Result);
1460 }
1461 }
1462
1463 return Result;
1464}
1465
Dan Gohman890f92b2009-04-18 17:56:28 +00001466Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001467 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1468
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001469 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891bd2005-07-30 00:12:19 +00001470 const Loop *L = S->getLoop();
Nate Begeman36f891bd2005-07-30 00:12:19 +00001471
Dan Gohman4d8414f2009-06-13 16:25:49 +00001472 // First check for an existing canonical IV in a suitable type.
Craig Topper570e52c2014-04-15 04:59:12 +00001473 PHINode *CanonicalIV = nullptr;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001474 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001475 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001476 CanonicalIV = PN;
1477
1478 // Rewrite an AddRec in terms of the canonical induction variable, if
1479 // its type is more narrow.
1480 if (CanonicalIV &&
1481 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1482 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001483 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1484 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1485 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001486 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trick6f71dd72013-07-14 03:10:08 +00001487 S->getNoWrapFlags(SCEV::FlagNW)));
Florian Hahn26ac94d2018-06-25 20:55:26 +00001488 BasicBlock::iterator NewInsertPt =
1489 findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
Craig Topper570e52c2014-04-15 04:59:12 +00001490 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001491 &*NewInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001492 return V;
1493 }
1494
Nate Begeman36f891bd2005-07-30 00:12:19 +00001495 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001496 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001497 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001498 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick6f71dd72013-07-14 03:10:08 +00001499 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1500 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman453aa4f2009-05-24 18:06:31 +00001501
1502 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1503 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001504 const SCEV *Base = S->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001505 // Dig into the expression to find the pointer base for a GEP.
Keno Fischerdb695a12018-07-26 21:55:03 +00001506 const SCEV *ExposedRest = Rest;
1507 ExposePointerBase(Base, ExposedRest, SE);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001508 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001509 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001510 // Make sure the Base isn't something exotic, such as a multiplied
1511 // or divided pointer value. In those cases, the result type isn't
1512 // actually a pointer type.
1513 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1514 Value *StartV = expand(Base);
1515 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
Keno Fischerdb695a12018-07-26 21:55:03 +00001516 return expandAddToGEP(ExposedRest, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001517 }
1518 }
1519
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001520 // Just do a normal add. Pre-expand the operands to suppress folding.
Patrik Hagglund7293ea52016-06-20 10:19:04 +00001521 //
1522 // The LHS and RHS values are factored out of the expand call to make the
1523 // output independent of the argument evaluation order.
1524 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1525 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1526 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
Nate Begeman36f891bd2005-07-30 00:12:19 +00001527 }
1528
Dan Gohman6ebfd722010-07-26 18:28:14 +00001529 // If we don't yet have a canonical IV, create one.
1530 if (!CanonicalIV) {
Nate Begeman36f891bd2005-07-30 00:12:19 +00001531 // Create and insert the PHI node for the induction variable in the
1532 // specified loop.
1533 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001534 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001535 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001536 &Header->front());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001537 rememberInstruction(CanonicalIV);
Nate Begeman36f891bd2005-07-30 00:12:19 +00001538
Hal Finkel19046ec2013-08-18 00:16:23 +00001539 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersoneed707b2009-07-24 23:12:02 +00001540 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001541 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001542 BasicBlock *HP = *HPI;
David Blaikie5401ba72014-11-19 07:49:26 +00001543 if (!PredSeen.insert(HP).second) {
Hal Finkel50c05c92014-07-31 19:13:38 +00001544 // There must be an incoming value for each predecessor, even the
1545 // duplicates!
1546 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel19046ec2013-08-18 00:16:23 +00001547 continue;
Hal Finkel50c05c92014-07-31 19:13:38 +00001548 }
Hal Finkel19046ec2013-08-18 00:16:23 +00001549
Gabor Greif76560182010-07-09 15:40:10 +00001550 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001551 // Insert a unit add instruction right before the terminator
1552 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001553 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1554 "indvar.next",
1555 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001556 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001557 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001558 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001559 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001560 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001561 }
Gabor Greif76560182010-07-09 15:40:10 +00001562 }
Nate Begeman36f891bd2005-07-30 00:12:19 +00001563 }
1564
Dan Gohman6ebfd722010-07-26 18:28:14 +00001565 // {0,+,1} --> Insert a canonical induction variable into the loop!
1566 if (S->isAffine() && S->getOperand(1)->isOne()) {
1567 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1568 "IVs with types different from the canonical IV should "
1569 "already have been handled!");
1570 return CanonicalIV;
1571 }
1572
Dan Gohman4d8414f2009-06-13 16:25:49 +00001573 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891bd2005-07-30 00:12:19 +00001574
Chris Lattnerdf14a042005-10-30 06:24:33 +00001575 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001576 if (S->isAffine()) // {0,+,F} --> i*F
1577 return
1578 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001579 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001580 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001581 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001582 Ty));
Nate Begeman36f891bd2005-07-30 00:12:19 +00001583
1584 // If this is a chain of recurrences, turn it into a closed form, using the
1585 // folders, then expandCodeFor the closed form. This allows the folders to
1586 // simplify the expression without having to build a bunch of special code
1587 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001588 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891bd2005-07-30 00:12:19 +00001589
Dan Gohman4d8414f2009-06-13 16:25:49 +00001590 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001591 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001592 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001593 if (isa<SCEVAddRecExpr>(Ext))
1594 NewS = Ext;
1595
Dan Gohman0bba49c2009-07-07 17:06:11 +00001596 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001597 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891bd2005-07-30 00:12:19 +00001598
Dan Gohman4d8414f2009-06-13 16:25:49 +00001599 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001600 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001601 return expand(T);
Nate Begeman36f891bd2005-07-30 00:12:19 +00001602}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001603
Dan Gohman890f92b2009-04-18 17:56:28 +00001604Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001605 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001606 Value *V = expandCodeFor(S->getOperand(),
1607 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001608 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001609 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001610 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001611}
1612
Dan Gohman890f92b2009-04-18 17:56:28 +00001613Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001614 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001615 Value *V = expandCodeFor(S->getOperand(),
1616 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001617 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001618 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001619 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001620}
1621
Dan Gohman890f92b2009-04-18 17:56:28 +00001622Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001623 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001624 Value *V = expandCodeFor(S->getOperand(),
1625 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001626 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001627 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001628 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001629}
1630
Dan Gohman890f92b2009-04-18 17:56:28 +00001631Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001632 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001633 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001634 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1635 // In the case of mixed integer and pointer types, do the
1636 // rest of the comparisons as integer.
1637 if (S->getOperand(i)->getType() != Ty) {
1638 Ty = SE.getEffectiveSCEVType(Ty);
1639 LHS = InsertNoopCastOfTo(LHS, Ty);
1640 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001641 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001642 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001643 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001644 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001645 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001646 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001647 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001648 // In the case of mixed integer and pointer types, cast the
1649 // final result back to the pointer type.
1650 if (LHS->getType() != S->getType())
1651 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001652 return LHS;
1653}
1654
Dan Gohman890f92b2009-04-18 17:56:28 +00001655Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001656 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001657 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001658 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1659 // In the case of mixed integer and pointer types, do the
1660 // rest of the comparisons as integer.
1661 if (S->getOperand(i)->getType() != Ty) {
1662 Ty = SE.getEffectiveSCEVType(Ty);
1663 LHS = InsertNoopCastOfTo(LHS, Ty);
1664 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001665 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001666 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001667 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001668 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001669 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001670 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001671 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001672 // In the case of mixed integer and pointer types, cast the
1673 // final result back to the pointer type.
1674 if (LHS->getType() != S->getType())
1675 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001676 return LHS;
1677}
1678
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001679Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001680 Instruction *IP) {
Geoff Berry510ec202016-08-11 21:05:17 +00001681 setInsertPoint(IP);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001682 return expandCodeFor(SH, Ty);
1683}
1684
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001685Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001686 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001687 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001688 if (Ty) {
1689 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1690 "non-trivial casts should be done with the SCEVs directly!");
1691 V = InsertNoopCastOfTo(V, Ty);
1692 }
1693 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001694}
1695
Wei Mi8b932252016-08-09 20:37:50 +00001696ScalarEvolution::ValueOffsetPair
1697SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1698 const Instruction *InsertPt) {
1699 SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S);
Junmo Park4ee5ab92016-02-16 06:46:58 +00001700 // If the expansion is not in CanonicalMode, and the SCEV contains any
1701 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1702 if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1703 // If S is scConstant, it may be worse to reuse an existing Value.
1704 if (S->getSCEVType() != scConstant && Set) {
1705 // Choose a Value from the set which dominates the insertPt.
1706 // insertPt should be inside the Value's parent loop so as not to break
1707 // the LCSSA form.
Wei Mi8b932252016-08-09 20:37:50 +00001708 for (auto const &VOPair : *Set) {
1709 Value *V = VOPair.first;
1710 ConstantInt *Offset = VOPair.second;
Junmo Park4ee5ab92016-02-16 06:46:58 +00001711 Instruction *EntInst = nullptr;
Wei Mi8b932252016-08-09 20:37:50 +00001712 if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
1713 S->getType() == V->getType() &&
Junmo Park4ee5ab92016-02-16 06:46:58 +00001714 EntInst->getFunction() == InsertPt->getFunction() &&
1715 SE.DT.dominates(EntInst, InsertPt) &&
1716 (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
Wei Mi8b932252016-08-09 20:37:50 +00001717 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1718 return {V, Offset};
Junmo Park4ee5ab92016-02-16 06:46:58 +00001719 }
1720 }
1721 }
Wei Mi8b932252016-08-09 20:37:50 +00001722 return {nullptr, nullptr};
Junmo Park4ee5ab92016-02-16 06:46:58 +00001723}
1724
Wei Mieafb39b2016-02-04 01:27:38 +00001725// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1726// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1727// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1728// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1729// the expansion will try to reuse Value from ExprValueMap, and only when it
1730// fails, expand the SCEV literally.
Dan Gohman890f92b2009-04-18 17:56:28 +00001731Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001732 // Compute an insertion point for this SCEV object. Hoist the instructions
1733 // as far out in the loop nest as possible.
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001734 Instruction *InsertPt = &*Builder.GetInsertPoint();
David L. Jonesad6bed62018-12-05 23:13:50 +00001735 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1736 L = L->getParentLoop())
1737 if (SE.isLoopInvariant(S, L)) {
1738 if (!L) break;
1739 if (BasicBlock *Preheader = L->getLoopPreheader())
1740 InsertPt = Preheader->getTerminator();
1741 else {
1742 // LSR sets the insertion point for AddRec start/step values to the
1743 // block start to simplify value reuse, even though it's an invalid
1744 // position. SCEVExpander must correct for this in all cases.
1745 InsertPt = &*L->getHeader()->getFirstInsertionPt();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001746 }
David L. Jonesad6bed62018-12-05 23:13:50 +00001747 } else {
1748 // We can move insertion point only if there is no div or rem operations
1749 // otherwise we are risky to move it over the check for zero denominator.
1750 auto SafeToHoist = [](const SCEV *S) {
1751 return !SCEVExprContains(S, [](const SCEV *S) {
1752 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1753 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1754 // Division by non-zero constants can be hoisted.
1755 return SC->getValue()->isZero();
1756 // All other divisions should not be moved as they may be
1757 // divisions by zero and should be kept within the
1758 // conditions of the surrounding loops that guard their
1759 // execution (see PR35406).
1760 return true;
1761 }
1762 return false;
1763 });
1764 };
1765 // If the SCEV is computable at this level, insert it into the header
1766 // after the PHIs (and after any other instructions that we've inserted
1767 // there) so that it is guaranteed to dominate any user inside the loop.
1768 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L) &&
1769 SafeToHoist(S))
1770 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1771 while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1772 (isInsertedInstruction(InsertPt) ||
1773 isa<DbgInfoIntrinsic>(InsertPt))) {
1774 InsertPt = &*std::next(InsertPt->getIterator());
1775 }
1776 break;
Reid Kleckner56976902016-12-12 18:52:32 +00001777 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001778
Dan Gohman667d7872009-06-26 22:53:46 +00001779 // Check to see if we already expanded this here.
Sanjoy Das108f8f32015-11-21 23:20:10 +00001780 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001781 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001782 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001783
Geoff Berrye81e8032016-06-01 20:03:09 +00001784 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001785 Builder.SetInsertPoint(InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001786
1787 // Expand the expression into instructions.
Wei Mi8b932252016-08-09 20:37:50 +00001788 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
1789 Value *V = VO.first;
Junmo Park4ee5ab92016-02-16 06:46:58 +00001790
Wei Mieafb39b2016-02-04 01:27:38 +00001791 if (!V)
1792 V = visit(S);
Wei Mi81a2b892016-09-14 04:39:50 +00001793 else if (VO.second) {
1794 if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
1795 Type *Ety = Vty->getPointerElementType();
1796 int64_t Offset = VO.second->getSExtValue();
1797 int64_t ESize = SE.getTypeSizeInBits(Ety);
1798 if ((Offset * 8) % ESize == 0) {
1799 ConstantInt *Idx =
1800 ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize);
1801 V = Builder.CreateGEP(Ety, V, Idx, "scevgep");
1802 } else {
1803 ConstantInt *Idx =
1804 ConstantInt::getSigned(VO.second->getType(), -Offset);
1805 unsigned AS = Vty->getAddressSpace();
1806 V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
1807 V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
1808 "uglygep");
1809 V = Builder.CreateBitCast(V, Vty);
1810 }
1811 } else {
1812 V = Builder.CreateSub(V, VO.second);
1813 }
1814 }
Dan Gohman667d7872009-06-26 22:53:46 +00001815 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001816 //
1817 // This is independent of PostIncLoops. The mapped value simply materializes
1818 // the expression at this insertion point. If the mapped value happened to be
Alp Toker087ab612013-12-05 05:44:44 +00001819 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick48ba0e42011-10-13 21:55:29 +00001820 // its insertion point was already at the head of the loop.
1821 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001822 return V;
1823}
Dan Gohman1d09de32009-06-05 16:35:53 +00001824
Dan Gohman1d826a72010-02-14 03:12:47 +00001825void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001826 if (!PostIncLoops.empty())
1827 InsertedPostIncValues.insert(I);
1828 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001829 InsertedValues.insert(I);
Dan Gohman1d826a72010-02-14 03:12:47 +00001830}
1831
Dan Gohman1d09de32009-06-05 16:35:53 +00001832/// getOrInsertCanonicalInductionVariable - This method returns the
1833/// canonical induction variable of the specified type for the specified
1834/// loop (inserting one if there is none). A canonical induction variable
1835/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001836PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001837SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001838 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001839 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001840
1841 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001842 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001843 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001844 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001845
1846 // Emit code for it.
Geoff Berrye81e8032016-06-01 20:03:09 +00001847 SCEVInsertPointGuard Guard(Builder, this);
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001848 PHINode *V =
1849 cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
Dan Gohman133e2952010-07-20 16:46:58 +00001850
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001851 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001852}
Andrew Trick20449412011-10-11 02:28:51 +00001853
Andrew Trick20449412011-10-11 02:28:51 +00001854/// replaceCongruentIVs - Check for congruent phis in this loop header and
1855/// replace them with their most canonical representative. Return the number of
1856/// phis eliminated.
1857///
1858/// This does not depend on any SCEVExpander state but should be used in
1859/// the same context that SCEVExpander is used.
Sanjoy Das399b4d02017-05-01 17:07:49 +00001860unsigned
1861SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1862 SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1863 const TargetTransformInfo *TTI) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001864 // Find integer phis in order of increasing width.
1865 SmallVector<PHINode*, 8> Phis;
Benjamin Kramer66f3fb92017-12-30 15:27:33 +00001866 for (PHINode &PN : L->getHeader()->phis())
1867 Phis.push_back(&PN);
Sanjoy Das108f8f32015-11-21 23:20:10 +00001868
Chandler Carruthe4ba75f2013-01-07 14:41:08 +00001869 if (TTI)
Fangrui Song3b35e172018-09-27 02:13:45 +00001870 llvm::sort(Phis, [](Value *LHS, Value *RHS) {
Benjamin Kramere1362f12014-03-07 21:35:39 +00001871 // Put pointers at the back and make sure pointer < pointer = false.
1872 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1873 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1874 return RHS->getType()->getPrimitiveSizeInBits() <
1875 LHS->getType()->getPrimitiveSizeInBits();
1876 });
Andrew Trickee98aa82012-01-07 01:12:09 +00001877
Andrew Trick20449412011-10-11 02:28:51 +00001878 unsigned NumElim = 0;
1879 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Eric Christopher933d2bd2015-06-19 01:53:21 +00001880 // Process phis from wide to narrow. Map wide phis to their truncation
Andrew Trickee98aa82012-01-07 01:12:09 +00001881 // so narrow phis can reuse them.
Sanjoy Das108f8f32015-11-21 23:20:10 +00001882 for (PHINode *Phi : Phis) {
Silviu Baranga94652ab2015-11-03 16:27:04 +00001883 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
Daniel Berline2c51262017-04-28 19:55:38 +00001884 if (Value *V = SimplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
Silviu Baranga94652ab2015-11-03 16:27:04 +00001885 return V;
1886 if (!SE.isSCEVable(PN->getType()))
1887 return nullptr;
1888 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1889 if (!Const)
1890 return nullptr;
1891 return Const->getValue();
1892 };
1893
Benjamin Kramer239fd442012-10-19 16:37:30 +00001894 // Fold constant phis. They may be congruent to other constant phis and
1895 // would confuse the logic below that expects proper IVs.
Silviu Baranga94652ab2015-11-03 16:27:04 +00001896 if (Value *V = SimplifyPHINode(Phi)) {
1897 if (V->getType() != Phi->getType())
1898 continue;
Benjamin Kramer239fd442012-10-19 16:37:30 +00001899 Phi->replaceAllUsesWith(V);
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001900 DeadInsts.emplace_back(Phi);
Benjamin Kramer239fd442012-10-19 16:37:30 +00001901 ++NumElim;
1902 DEBUG_WITH_TYPE(DebugType, dbgs()
1903 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1904 continue;
1905 }
1906
Andrew Trick20449412011-10-11 02:28:51 +00001907 if (!SE.isSCEVable(Phi->getType()))
1908 continue;
1909
1910 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1911 if (!OrigPhiRef) {
1912 OrigPhiRef = Phi;
Sanjoy Dasb03e0b72016-05-10 00:32:31 +00001913 if (Phi->getType()->isIntegerTy() && TTI &&
1914 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001915 // This phi can be freely truncated to the narrowest phi type. Map the
1916 // truncated expression to it so it will be reused for narrow types.
1917 const SCEV *TruncExpr =
1918 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1919 ExprToIVMap[TruncExpr] = Phi;
1920 }
Andrew Trick20449412011-10-11 02:28:51 +00001921 continue;
1922 }
1923
Andrew Trickee98aa82012-01-07 01:12:09 +00001924 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1925 // sense.
1926 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001927 continue;
1928
1929 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Sanjoy Das2731c7a2016-05-11 17:41:41 +00001930 Instruction *OrigInc = dyn_cast<Instruction>(
1931 OrigPhiRef->getIncomingValueForBlock(LatchBlock));
Andrew Trick20449412011-10-11 02:28:51 +00001932 Instruction *IsomorphicInc =
Sanjoy Das2731c7a2016-05-11 17:41:41 +00001933 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
Andrew Trick20449412011-10-11 02:28:51 +00001934
Sanjoy Das2731c7a2016-05-11 17:41:41 +00001935 if (OrigInc && IsomorphicInc) {
1936 // If this phi has the same width but is more canonical, replace the
1937 // original with it. As part of the "more canonical" determination,
1938 // respect a prior decision to use an IV chain.
1939 if (OrigPhiRef->getType() == Phi->getType() &&
1940 !(ChainedPhis.count(Phi) ||
1941 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1942 (ChainedPhis.count(Phi) ||
1943 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1944 std::swap(OrigPhiRef, Phi);
1945 std::swap(OrigInc, IsomorphicInc);
Andrew Trickee98aa82012-01-07 01:12:09 +00001946 }
Sanjoy Das2731c7a2016-05-11 17:41:41 +00001947 // Replacing the congruent phi is sufficient because acyclic
1948 // redundancy elimination, CSE/GVN, should handle the
1949 // rest. However, once SCEV proves that a phi is congruent,
1950 // it's often the head of an IV user cycle that is isomorphic
1951 // with the original phi. It's worth eagerly cleaning up the
1952 // common case of a single IV increment so that DeleteDeadPHIs
1953 // can remove cycles that had postinc uses.
1954 const SCEV *TruncExpr =
1955 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1956 if (OrigInc != IsomorphicInc &&
1957 TruncExpr == SE.getSCEV(IsomorphicInc) &&
1958 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
1959 hoistIVInc(OrigInc, IsomorphicInc)) {
1960 DEBUG_WITH_TYPE(DebugType,
1961 dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1962 << *IsomorphicInc << '\n');
1963 Value *NewInc = OrigInc;
1964 if (OrigInc->getType() != IsomorphicInc->getType()) {
1965 Instruction *IP = nullptr;
1966 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1967 IP = &*PN->getParent()->getFirstInsertionPt();
1968 else
1969 IP = OrigInc->getNextNode();
1970
1971 IRBuilder<> Builder(IP);
1972 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1973 NewInc = Builder.CreateTruncOrBitCast(
1974 OrigInc, IsomorphicInc->getType(), IVName);
1975 }
1976 IsomorphicInc->replaceAllUsesWith(NewInc);
1977 DeadInsts.emplace_back(IsomorphicInc);
1978 }
Andrew Trick20449412011-10-11 02:28:51 +00001979 }
1980 }
Sanjoy Dasb03e0b72016-05-10 00:32:31 +00001981 DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
1982 << *Phi << '\n');
Andrew Trick20449412011-10-11 02:28:51 +00001983 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001984 Value *NewIV = OrigPhiRef;
1985 if (OrigPhiRef->getType() != Phi->getType()) {
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +00001986 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
Andrew Trickee98aa82012-01-07 01:12:09 +00001987 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1988 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1989 }
1990 Phi->replaceAllUsesWith(NewIV);
Benjamin Kramer9589ff82015-05-29 19:43:39 +00001991 DeadInsts.emplace_back(Phi);
Andrew Trick20449412011-10-11 02:28:51 +00001992 }
1993 return NumElim;
1994}
Andrew Tricke08c3222012-07-13 23:33:10 +00001995
Wei Mifc25cfb2016-08-09 20:40:03 +00001996Value *SCEVExpander::getExactExistingExpansion(const SCEV *S,
1997 const Instruction *At, Loop *L) {
1998 Optional<ScalarEvolution::ValueOffsetPair> VO =
1999 getRelatedExistingExpansion(S, At, L);
2000 if (VO && VO.getValue().second == nullptr)
2001 return VO.getValue().first;
2002 return nullptr;
2003}
2004
2005Optional<ScalarEvolution::ValueOffsetPair>
2006SCEVExpander::getRelatedExistingExpansion(const SCEV *S, const Instruction *At,
2007 Loop *L) {
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002008 using namespace llvm::PatternMatch;
2009
Igor Laevskydcf74882015-08-17 16:37:04 +00002010 SmallVector<BasicBlock *, 4> ExitingBlocks;
2011 L->getExitingBlocks(ExitingBlocks);
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002012
Igor Laevskydcf74882015-08-17 16:37:04 +00002013 // Look for suitable value in simple conditions at the loop exits.
2014 for (BasicBlock *BB : ExitingBlocks) {
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002015 ICmpInst::Predicate Pred;
2016 Instruction *LHS, *RHS;
2017 BasicBlock *TrueBB, *FalseBB;
2018
2019 if (!match(BB->getTerminator(),
2020 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2021 TrueBB, FalseBB)))
2022 continue;
2023
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00002024 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
Wei Mifc25cfb2016-08-09 20:40:03 +00002025 return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002026
Chandler Carruthbfe1f1c2015-08-17 02:08:17 +00002027 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
Wei Mifc25cfb2016-08-09 20:40:03 +00002028 return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002029 }
2030
Junmo Park4ee5ab92016-02-16 06:46:58 +00002031 // Use expand's logic which is used for reusing a previous Value in
2032 // ExprValueMap.
Wei Mifc25cfb2016-08-09 20:40:03 +00002033 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
2034 if (VO.first)
2035 return VO;
Junmo Park4ee5ab92016-02-16 06:46:58 +00002036
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002037 // There is potential to make this significantly smarter, but this simple
2038 // heuristic already gets some interesting cases.
2039
2040 // Can not find suitable value.
Wei Mifc25cfb2016-08-09 20:40:03 +00002041 return None;
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002042}
2043
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002044bool SCEVExpander::isHighCostExpansionHelper(
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002045 const SCEV *S, Loop *L, const Instruction *At,
2046 SmallPtrSetImpl<const SCEV *> &Processed) {
2047
Simon Pilgrim84d1e912016-11-20 13:47:59 +00002048 // If we can find an existing value for this scev available at the point "At"
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002049 // then consider the expression cheap.
Wei Mifc25cfb2016-08-09 20:40:03 +00002050 if (At && getRelatedExistingExpansion(S, At, L))
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002051 return false;
Wei Mi61897e82015-05-28 21:49:07 +00002052
2053 // Zero/One operand expressions
2054 switch (S->getSCEVType()) {
2055 case scUnknown:
2056 case scConstant:
2057 return false;
2058 case scTruncate:
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002059 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
2060 L, At, Processed);
Wei Mi61897e82015-05-28 21:49:07 +00002061 case scZeroExtend:
2062 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002063 L, At, Processed);
Wei Mi61897e82015-05-28 21:49:07 +00002064 case scSignExtend:
2065 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
Igor Laevskyb1b95a52015-08-10 18:23:58 +00002066 L, At, Processed);
Wei Mi61897e82015-05-28 21:49:07 +00002067 }
2068
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002069 if (!Processed.insert(S).second)
2070 return false;
2071
Sanjoy Das17e08f52015-04-14 03:20:32 +00002072 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
2073 // If the divisor is a power of two and the SCEV type fits in a native
Benjamin Kramerd3c712e2015-08-08 18:27:36 +00002074 // integer, consider the division cheap irrespective of whether it occurs in
Sanjoy Das17e08f52015-04-14 03:20:32 +00002075 // the user code since it can be lowered into a right shift.
2076 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
Sanjoy Das4b892412015-12-17 20:28:46 +00002077 if (SC->getAPInt().isPowerOf2()) {
Sanjoy Das17e08f52015-04-14 03:20:32 +00002078 const DataLayout &DL =
2079 L->getHeader()->getParent()->getParent()->getDataLayout();
2080 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
2081 return DL.isIllegalInteger(Width);
2082 }
2083
2084 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2085 // HowManyLessThans produced to compute a precise expression, rather than a
2086 // UDiv from the user's code. If we can't find a UDiv in the code with some
2087 // simple searching, assume the former consider UDivExpr expensive to
2088 // compute.
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002089 BasicBlock *ExitingBB = L->getExitingBlock();
2090 if (!ExitingBB)
2091 return true;
2092
Igor Laevskydcf74882015-08-17 16:37:04 +00002093 // At the beginning of this function we already tried to find existing value
2094 // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
2095 // involving division. This is just a simple search heuristic.
2096 if (!At)
2097 At = &ExitingBB->back();
Wei Mifc25cfb2016-08-09 20:40:03 +00002098 if (!getRelatedExistingExpansion(
Igor Laevskydcf74882015-08-17 16:37:04 +00002099 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002100 return true;
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002101 }
2102
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002103 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
2104 // the exit condition.
2105 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
2106 return true;
2107
Wei Mi61897e82015-05-28 21:49:07 +00002108 // Recurse past nary expressions, which commonly occur in the
2109 // BackedgeTakenCount. They may already exist in program code, and if not,
2110 // they are not too expensive rematerialize.
2111 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
Sanjoy Das108f8f32015-11-21 23:20:10 +00002112 for (auto *Op : NAry->operands())
2113 if (isHighCostExpansionHelper(Op, L, At, Processed))
Wei Mi61897e82015-05-28 21:49:07 +00002114 return true;
Wei Mi61897e82015-05-28 21:49:07 +00002115 }
2116
Sanjoy Dasdee1e822015-04-14 03:20:28 +00002117 // If we haven't recognized an expensive SCEV pattern, assume it's an
2118 // expression produced by program code.
2119 return false;
2120}
2121
Silviu Barangaa0b73c22015-11-02 14:41:02 +00002122Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2123 Instruction *IP) {
2124 assert(IP);
2125 switch (Pred->getKind()) {
2126 case SCEVPredicate::P_Union:
2127 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2128 case SCEVPredicate::P_Equal:
2129 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
Silviu Barangae942cf82016-02-08 17:02:45 +00002130 case SCEVPredicate::P_Wrap: {
2131 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2132 return expandWrapPredicate(AddRecPred, IP);
2133 }
Silviu Barangaa0b73c22015-11-02 14:41:02 +00002134 }
2135 llvm_unreachable("Unknown SCEV predicate type");
2136}
2137
2138Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
2139 Instruction *IP) {
2140 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2141 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2142
2143 Builder.SetInsertPoint(IP);
2144 auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2145 return I;
2146}
2147
Silviu Barangae942cf82016-02-08 17:02:45 +00002148Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2149 Instruction *Loc, bool Signed) {
2150 assert(AR->isAffine() && "Cannot generate RT check for "
2151 "non-affine expression");
2152
Silviu Barangad8cc8162016-04-08 14:29:09 +00002153 SCEVUnionPredicate Pred;
2154 const SCEV *ExitCount =
2155 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
Silviu Barangae942cf82016-02-08 17:02:45 +00002156
2157 assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2158
Silviu Baranga5a397272016-04-25 09:27:16 +00002159 const SCEV *Step = AR->getStepRecurrence(SE);
2160 const SCEV *Start = AR->getStart();
Silviu Barangae942cf82016-02-08 17:02:45 +00002161
Keno Fischer3cb83a52018-07-26 21:55:06 +00002162 Type *ARTy = AR->getType();
Silviu Baranga5a397272016-04-25 09:27:16 +00002163 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
Keno Fischer3cb83a52018-07-26 21:55:06 +00002164 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
Silviu Barangae942cf82016-02-08 17:02:45 +00002165
Silviu Baranga5a397272016-04-25 09:27:16 +00002166 // The expression {Start,+,Step} has nusw/nssw if
2167 // Step < 0, Start - |Step| * Backedge <= Start
2168 // Step >= 0, Start + |Step| * Backedge > Start
2169 // and |Step| * Backedge doesn't unsigned overflow.
Silviu Barangae942cf82016-02-08 17:02:45 +00002170
Silviu Baranga5a397272016-04-25 09:27:16 +00002171 IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2172 Builder.SetInsertPoint(Loc);
2173 Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2174
2175 IntegerType *Ty =
Keno Fischer3cb83a52018-07-26 21:55:06 +00002176 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2177 Type *ARExpandTy = DL.isNonIntegralPointerType(ARTy) ? ARTy : Ty;
Silviu Baranga5a397272016-04-25 09:27:16 +00002178
2179 Value *StepValue = expandCodeFor(Step, Ty, Loc);
2180 Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
Keno Fischer3cb83a52018-07-26 21:55:06 +00002181 Value *StartValue = expandCodeFor(Start, ARExpandTy, Loc);
Silviu Baranga5a397272016-04-25 09:27:16 +00002182
2183 ConstantInt *Zero =
2184 ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits));
Silviu Barangae942cf82016-02-08 17:02:45 +00002185
2186 Builder.SetInsertPoint(Loc);
Silviu Baranga5a397272016-04-25 09:27:16 +00002187 // Compute |Step|
2188 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2189 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
Silviu Barangae942cf82016-02-08 17:02:45 +00002190
Silviu Baranga5a397272016-04-25 09:27:16 +00002191 // Get the backedge taken count and truncate or extended to the AR type.
2192 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2193 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2194 Intrinsic::umul_with_overflow, Ty);
2195
2196 // Compute |Step| * Backedge
2197 CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2198 Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2199 Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2200
2201 // Compute:
2202 // Start + |Step| * Backedge < Start
2203 // Start - |Step| * Backedge > Start
Keno Fischer3cb83a52018-07-26 21:55:06 +00002204 Value *Add = nullptr, *Sub = nullptr;
2205 if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARExpandTy)) {
2206 const SCEV *MulS = SE.getSCEV(MulV);
2207 const SCEV *NegMulS = SE.getNegativeSCEV(MulS);
2208 Add = Builder.CreateBitCast(expandAddToGEP(MulS, ARPtrTy, Ty, StartValue),
2209 ARPtrTy);
2210 Sub = Builder.CreateBitCast(
2211 expandAddToGEP(NegMulS, ARPtrTy, Ty, StartValue), ARPtrTy);
2212 } else {
2213 Add = Builder.CreateAdd(StartValue, MulV);
2214 Sub = Builder.CreateSub(StartValue, MulV);
2215 }
Silviu Baranga5a397272016-04-25 09:27:16 +00002216
2217 Value *EndCompareGT = Builder.CreateICmp(
2218 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2219
2220 Value *EndCompareLT = Builder.CreateICmp(
2221 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2222
2223 // Select the answer based on the sign of Step.
2224 Value *EndCheck =
2225 Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2226
2227 // If the backedge taken count type is larger than the AR type,
2228 // check that we don't drop any bits by truncating it. If we are
Vedant Kumard9244422018-03-02 18:57:02 +00002229 // dropping bits, then we have overflow (unless the step is zero).
Silviu Baranga5a397272016-04-25 09:27:16 +00002230 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2231 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2232 auto *BackedgeCheck =
2233 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2234 ConstantInt::get(Loc->getContext(), MaxVal));
2235 BackedgeCheck = Builder.CreateAnd(
2236 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2237
2238 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2239 }
2240
2241 EndCheck = Builder.CreateOr(EndCheck, OfMul);
2242 return EndCheck;
Silviu Barangae942cf82016-02-08 17:02:45 +00002243}
2244
2245Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2246 Instruction *IP) {
2247 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2248 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2249
2250 // Add a check for NUSW
2251 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2252 NUSWCheck = generateOverflowCheck(A, IP, false);
2253
2254 // Add a check for NSSW
2255 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2256 NSSWCheck = generateOverflowCheck(A, IP, true);
2257
2258 if (NUSWCheck && NSSWCheck)
2259 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2260
2261 if (NUSWCheck)
2262 return NUSWCheck;
2263
2264 if (NSSWCheck)
2265 return NSSWCheck;
2266
2267 return ConstantInt::getFalse(IP->getContext());
2268}
2269
Silviu Barangaa0b73c22015-11-02 14:41:02 +00002270Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2271 Instruction *IP) {
2272 auto *BoolType = IntegerType::get(IP->getContext(), 1);
2273 Value *Check = ConstantInt::getNullValue(BoolType);
2274
2275 // Loop over all checks in this set.
2276 for (auto Pred : Union->getPredicates()) {
2277 auto *NextCheck = expandCodeForPredicate(Pred, IP);
2278 Builder.SetInsertPoint(IP);
2279 Check = Builder.CreateOr(Check, NextCheck);
2280 }
2281
2282 return Check;
2283}
2284
Andrew Tricke08c3222012-07-13 23:33:10 +00002285namespace {
2286// Search for a SCEV subexpression that is not safe to expand. Any expression
2287// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2288// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2289// instruction, but the important thing is that we prove the denominator is
2290// nonzero before expansion.
2291//
2292// IVUsers already checks that IV-derived expressions are safe. So this check is
2293// only needed when the expression includes some subexpression that is not IV
2294// derived.
2295//
Max Kazantsev11fa8e32017-10-27 04:17:44 +00002296// Currently, we only allow division by a nonzero constant here. If this is
2297// inadequate, we could easily allow division by SCEVUnknown by using
2298// ValueTracking to check isKnownNonZero().
2299//
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002300// We cannot generally expand recurrences unless the step dominates the loop
2301// header. The expander handles the special case of affine recurrences by
2302// scaling the recurrence outside the loop, but this technique isn't generally
2303// applicable. Expanding a nested recurrence outside a loop requires computing
2304// binomial coefficients. This could be done, but the recurrence has to be in a
2305// perfectly reduced form, which can't be guaranteed.
Andrew Tricke08c3222012-07-13 23:33:10 +00002306struct SCEVFindUnsafe {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002307 ScalarEvolution &SE;
Andrew Tricke08c3222012-07-13 23:33:10 +00002308 bool IsUnsafe;
2309
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002310 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Tricke08c3222012-07-13 23:33:10 +00002311
2312 bool follow(const SCEV *S) {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002313 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
Max Kazantsev11fa8e32017-10-27 04:17:44 +00002314 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2315 if (!SC || SC->getValue()->isZero()) {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002316 IsUnsafe = true;
2317 return false;
2318 }
Max Kazantsev11fa8e32017-10-27 04:17:44 +00002319 }
2320 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002321 const SCEV *Step = AR->getStepRecurrence(SE);
2322 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2323 IsUnsafe = true;
2324 return false;
2325 }
2326 }
2327 return true;
Andrew Tricke08c3222012-07-13 23:33:10 +00002328 }
2329 bool isDone() const { return IsUnsafe; }
2330};
Alexander Kornienkocd52a7a2015-06-23 09:49:53 +00002331}
Andrew Tricke08c3222012-07-13 23:33:10 +00002332
2333namespace llvm {
Andrew Trick4d4bbaf2013-10-25 21:35:56 +00002334bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2335 SCEVFindUnsafe Search(SE);
Andrew Tricke08c3222012-07-13 23:33:10 +00002336 visitAll(S, Search);
2337 return !Search.IsUnsafe;
2338}
Max Kazantsevcb0def42017-11-16 05:10:56 +00002339
2340bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint,
2341 ScalarEvolution &SE) {
2342 return isSafeToExpand(S, SE) && SE.dominates(S, InsertionPoint->getParent());
2343}
Andrew Tricke08c3222012-07-13 23:33:10 +00002344}